From 332657cbce4e2c866007a59909353898cd0e3ef0 Mon Sep 17 00:00:00 2001 From: lostways Date: Sun, 11 Sep 2022 18:25:22 -0700 Subject: [PATCH 1/2] upgraded three js version --- build/three-js-wrapper.js | 55370 +++++++++++++++-------------- build/three-js-wrapper.min.js | 9 +- build/three-js-wrapper.module.js | 55370 +++++++++++++++-------------- 3 files changed, 56697 insertions(+), 54052 deletions(-) diff --git a/build/three-js-wrapper.js b/build/three-js-wrapper.js index b0c8172..3b0eee8 100644 --- a/build/three-js-wrapper.js +++ b/build/three-js-wrapper.js @@ -2,8 +2,12 @@ Object.defineProperty(exports, '__esModule', { value: true }); -// threejs.org/license -const REVISION = '126'; +/** + * @license + * Copyright 2010-2022 Three.js Authors + * SPDX-License-Identifier: MIT + */ +const REVISION = '144'; const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; const CullFaceNone = 0; @@ -17,8 +21,6 @@ const VSMShadowMap = 3; const FrontSide = 0; const BackSide = 1; const DoubleSide = 2; -const FlatShading = 1; -const SmoothShading = 2; const NoBlending = 0; const NormalBlending = 1; const AdditiveBlending = 2; @@ -65,7 +67,6 @@ const CubeRefractionMapping = 302; const EquirectangularReflectionMapping = 303; const EquirectangularRefractionMapping = 304; const CubeUVReflectionMapping = 306; -const CubeUVRefractionMapping = 307; const RepeatWrapping = 1000; const ClampToEdgeWrapping = 1001; const MirroredRepeatWrapping = 1002; @@ -89,21 +90,18 @@ const FloatType = 1015; const HalfFloatType = 1016; const UnsignedShort4444Type = 1017; const UnsignedShort5551Type = 1018; -const UnsignedShort565Type = 1019; const UnsignedInt248Type = 1020; const AlphaFormat = 1021; -const RGBFormat = 1022; +const RGBFormat = 1022; // @deprecated since r137 const RGBAFormat = 1023; const LuminanceFormat = 1024; const LuminanceAlphaFormat = 1025; -const RGBEFormat = RGBAFormat; const DepthFormat = 1026; const DepthStencilFormat = 1027; const RedFormat = 1028; const RedIntegerFormat = 1029; const RGFormat = 1030; const RGIntegerFormat = 1031; -const RGBIntegerFormat = 1032; const RGBAIntegerFormat = 1033; const RGB_S3TC_DXT1_Format = 33776; @@ -132,20 +130,6 @@ const RGBA_ASTC_10x10_Format = 37819; const RGBA_ASTC_12x10_Format = 37820; const RGBA_ASTC_12x12_Format = 37821; const RGBA_BPTC_Format = 36492; -const SRGB8_ALPHA8_ASTC_4x4_Format = 37840; -const SRGB8_ALPHA8_ASTC_5x4_Format = 37841; -const SRGB8_ALPHA8_ASTC_5x5_Format = 37842; -const SRGB8_ALPHA8_ASTC_6x5_Format = 37843; -const SRGB8_ALPHA8_ASTC_6x6_Format = 37844; -const SRGB8_ALPHA8_ASTC_8x5_Format = 37845; -const SRGB8_ALPHA8_ASTC_8x6_Format = 37846; -const SRGB8_ALPHA8_ASTC_8x8_Format = 37847; -const SRGB8_ALPHA8_ASTC_10x5_Format = 37848; -const SRGB8_ALPHA8_ASTC_10x6_Format = 37849; -const SRGB8_ALPHA8_ASTC_10x8_Format = 37850; -const SRGB8_ALPHA8_ASTC_10x10_Format = 37851; -const SRGB8_ALPHA8_ASTC_12x10_Format = 37852; -const SRGB8_ALPHA8_ASTC_12x12_Format = 37853; const LoopOnce = 2200; const LoopRepeat = 2201; const LoopPingPong = 2202; @@ -162,17 +146,16 @@ const TriangleStripDrawMode = 1; const TriangleFanDrawMode = 2; const LinearEncoding = 3000; const sRGBEncoding = 3001; -const GammaEncoding = 3007; -const RGBEEncoding = 3002; -const LogLuvEncoding = 3003; -const RGBM7Encoding = 3004; -const RGBM16Encoding = 3005; -const RGBDEncoding = 3006; const BasicDepthPacking = 3200; const RGBADepthPacking = 3201; const TangentSpaceNormalMap = 0; const ObjectSpaceNormalMap = 1; +// Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available. +const NoColorSpace = ''; +const SRGBColorSpace = 'srgb'; +const LinearSRGBColorSpace = 'srgb-linear'; + const ZeroStencilOp = 0; const KeepStencilOp = 7680; const ReplaceStencilOp = 7681; @@ -204,15 +187,15 @@ const StreamCopyUsage = 35042; const GLSL1 = '100'; const GLSL3 = '300 es'; +const _SRGBAFormat = 1035; // fallback for WebGL 1 + /** * https://github.com/mrdoob/eventdispatcher.js/ */ -function EventDispatcher() {} +class EventDispatcher { -Object.assign( EventDispatcher.prototype, { - - addEventListener: function ( type, listener ) { + addEventListener( type, listener ) { if ( this._listeners === undefined ) this._listeners = {}; @@ -230,9 +213,9 @@ Object.assign( EventDispatcher.prototype, { } - }, + } - hasEventListener: function ( type, listener ) { + hasEventListener( type, listener ) { if ( this._listeners === undefined ) return false; @@ -240,9 +223,9 @@ Object.assign( EventDispatcher.prototype, { return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; - }, + } - removeEventListener: function ( type, listener ) { + removeEventListener( type, listener ) { if ( this._listeners === undefined ) return; @@ -261,9 +244,9 @@ Object.assign( EventDispatcher.prototype, { } - }, + } - dispatchEvent: function ( event ) { + dispatchEvent( event ) { if ( this._listeners === undefined ) return; @@ -283,246 +266,341 @@ Object.assign( EventDispatcher.prototype, { } + event.target = null; + } } -} ); +} + +const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; + +let _seed = 1234567; + + +const DEG2RAD = Math.PI / 180; +const RAD2DEG = 180 / Math.PI; -const _lut = []; +// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 +function generateUUID() { -for ( let i = 0; i < 256; i ++ ) { + const d0 = Math.random() * 0xffffffff | 0; + const d1 = Math.random() * 0xffffffff | 0; + const d2 = Math.random() * 0xffffffff | 0; + const d3 = Math.random() * 0xffffffff | 0; + const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; - _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); + // .toLowerCase() here flattens concatenated strings to save heap memory space. + return uuid.toLowerCase(); } -let _seed = 1234567; +function clamp( value, min, max ) { -const MathUtils = { + return Math.max( min, Math.min( max, value ) ); - DEG2RAD: Math.PI / 180, - RAD2DEG: 180 / Math.PI, +} - generateUUID: function () { +// compute euclidean modulo of m % n +// https://en.wikipedia.org/wiki/Modulo_operation +function euclideanModulo( n, m ) { - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 + return ( ( n % m ) + m ) % m; - const d0 = Math.random() * 0xffffffff | 0; - const d1 = Math.random() * 0xffffffff | 0; - const d2 = Math.random() * 0xffffffff | 0; - const d3 = Math.random() * 0xffffffff | 0; - const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + - _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + - _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + - _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; +} - // .toUpperCase() here flattens concatenated strings to save heap memory space. - return uuid.toUpperCase(); +// Linear mapping from range to range +function mapLinear( x, a1, a2, b1, b2 ) { - }, + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - clamp: function ( value, min, max ) { +} - return Math.max( min, Math.min( max, value ) ); +// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ +function inverseLerp( x, y, value ) { - }, + if ( x !== y ) { - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation + return ( value - x ) / ( y - x ); - euclideanModulo: function ( n, m ) { + } else { - return ( ( n % m ) + m ) % m; + return 0; - }, + } - // Linear mapping from range to range +} - mapLinear: function ( x, a1, a2, b1, b2 ) { +// https://en.wikipedia.org/wiki/Linear_interpolation +function lerp( x, y, t ) { - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + return ( 1 - t ) * x + t * y; - }, +} - // https://en.wikipedia.org/wiki/Linear_interpolation +// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ +function damp( x, y, lambda, dt ) { - lerp: function ( x, y, t ) { + return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); - return ( 1 - t ) * x + t * y; +} - }, +// https://www.desmos.com/calculator/vcsjnyz7x4 +function pingpong( x, length = 1 ) { - // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ + return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); - damp: function ( x, y, lambda, dt ) { +} - return MathUtils.lerp( x, y, 1 - Math.exp( - lambda * dt ) ); +// http://en.wikipedia.org/wiki/Smoothstep +function smoothstep( x, min, max ) { - }, + if ( x <= min ) return 0; + if ( x >= max ) return 1; - // https://www.desmos.com/calculator/vcsjnyz7x4 + x = ( x - min ) / ( max - min ); - pingpong: function ( x, length = 1 ) { + return x * x * ( 3 - 2 * x ); - return length - Math.abs( MathUtils.euclideanModulo( x, length * 2 ) - length ); +} - }, +function smootherstep( x, min, max ) { - // http://en.wikipedia.org/wiki/Smoothstep + if ( x <= min ) return 0; + if ( x >= max ) return 1; - smoothstep: function ( x, min, max ) { + x = ( x - min ) / ( max - min ); - if ( x <= min ) return 0; - if ( x >= max ) return 1; + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - x = ( x - min ) / ( max - min ); +} - return x * x * ( 3 - 2 * x ); +// Random integer from interval +function randInt( low, high ) { - }, + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - smootherstep: function ( x, min, max ) { +} + +// Random float from interval +function randFloat( low, high ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + return low + Math.random() * ( high - low ); - x = ( x - min ) / ( max - min ); +} - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); +// Random float from <-range/2, range/2> interval +function randFloatSpread( range ) { - }, + return range * ( 0.5 - Math.random() ); - // Random integer from interval +} - randInt: function ( low, high ) { +// Deterministic pseudo-random float in the interval [ 0, 1 ] +function seededRandom( s ) { - return low + Math.floor( Math.random() * ( high - low + 1 ) ); + if ( s !== undefined ) _seed = s; - }, + // Mulberry32 generator - // Random float from interval + let t = _seed += 0x6D2B79F5; - randFloat: function ( low, high ) { + t = Math.imul( t ^ t >>> 15, t | 1 ); - return low + Math.random() * ( high - low ); + t ^= t + Math.imul( t ^ t >>> 7, t | 61 ); - }, + return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296; - // Random float from <-range/2, range/2> interval +} - randFloatSpread: function ( range ) { +function degToRad( degrees ) { - return range * ( 0.5 - Math.random() ); + return degrees * DEG2RAD; - }, +} - // Deterministic pseudo-random float in the interval [ 0, 1 ] +function radToDeg( radians ) { - seededRandom: function ( s ) { + return radians * RAD2DEG; - if ( s !== undefined ) _seed = s % 2147483647; +} - // Park-Miller algorithm +function isPowerOfTwo( value ) { - _seed = _seed * 16807 % 2147483647; + return ( value & ( value - 1 ) ) === 0 && value !== 0; - return ( _seed - 1 ) / 2147483646; +} - }, +function ceilPowerOfTwo( value ) { - degToRad: function ( degrees ) { + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); - return degrees * MathUtils.DEG2RAD; +} - }, +function floorPowerOfTwo( value ) { - radToDeg: function ( radians ) { + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); - return radians * MathUtils.RAD2DEG; +} - }, +function setQuaternionFromProperEuler( q, a, b, c, order ) { - isPowerOfTwo: function ( value ) { + // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles - return ( value & ( value - 1 ) ) === 0 && value !== 0; + // rotations are applied to the axes in the order specified by 'order' + // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' + // angles are in radians - }, + const cos = Math.cos; + const sin = Math.sin; - ceilPowerOfTwo: function ( value ) { + const c2 = cos( b / 2 ); + const s2 = sin( b / 2 ); - return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); + const c13 = cos( ( a + c ) / 2 ); + const s13 = sin( ( a + c ) / 2 ); - }, + const c1_3 = cos( ( a - c ) / 2 ); + const s1_3 = sin( ( a - c ) / 2 ); - floorPowerOfTwo: function ( value ) { + const c3_1 = cos( ( c - a ) / 2 ); + const s3_1 = sin( ( c - a ) / 2 ); - return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); + switch ( order ) { - }, + case 'XYX': + q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); + break; - setQuaternionFromProperEuler: function ( q, a, b, c, order ) { + case 'YZY': + q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); + break; - // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles + case 'ZXZ': + q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); + break; - // rotations are applied to the axes in the order specified by 'order' - // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' - // angles are in radians + case 'XZX': + q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); + break; - const cos = Math.cos; - const sin = Math.sin; + case 'YXY': + q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); + break; - const c2 = cos( b / 2 ); - const s2 = sin( b / 2 ); + case 'ZYZ': + q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); + break; - const c13 = cos( ( a + c ) / 2 ); - const s13 = sin( ( a + c ) / 2 ); + default: + console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); - const c1_3 = cos( ( a - c ) / 2 ); - const s1_3 = sin( ( a - c ) / 2 ); + } - const c3_1 = cos( ( c - a ) / 2 ); - const s3_1 = sin( ( c - a ) / 2 ); +} - switch ( order ) { +function denormalize( value, array ) { - case 'XYX': - q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); - break; + switch ( array.constructor ) { - case 'YZY': - q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); - break; + case Float32Array: - case 'ZXZ': - q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); - break; + return value; - case 'XZX': - q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); - break; + case Uint16Array: - case 'YXY': - q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); - break; + return value / 65535.0; - case 'ZYZ': - q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); - break; + case Uint8Array: - default: - console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); + return value / 255.0; - } + case Int16Array: + + return Math.max( value / 32767.0, - 1.0 ); + + case Int8Array: + + return Math.max( value / 127.0, - 1.0 ); + + default: + + throw new Error( 'Invalid component type.' ); } -}; +} + +function normalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return Math.round( value * 65535.0 ); + + case Uint8Array: + + return Math.round( value * 255.0 ); + + case Int16Array: + + return Math.round( value * 32767.0 ); + + case Int8Array: + + return Math.round( value * 127.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + +} + +var MathUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + DEG2RAD: DEG2RAD, + RAD2DEG: RAD2DEG, + generateUUID: generateUUID, + clamp: clamp, + euclideanModulo: euclideanModulo, + mapLinear: mapLinear, + inverseLerp: inverseLerp, + lerp: lerp, + damp: damp, + pingpong: pingpong, + smoothstep: smoothstep, + smootherstep: smootherstep, + randInt: randInt, + randFloat: randFloat, + randFloatSpread: randFloatSpread, + seededRandom: seededRandom, + degToRad: degToRad, + radToDeg: radToDeg, + isPowerOfTwo: isPowerOfTwo, + ceilPowerOfTwo: ceilPowerOfTwo, + floorPowerOfTwo: floorPowerOfTwo, + setQuaternionFromProperEuler: setQuaternionFromProperEuler, + normalize: normalize, + denormalize: denormalize +}); class Vector2 { constructor( x = 0, y = 0 ) { + Vector2.prototype.isVector2 = true; + this.x = x; this.y = y; @@ -627,14 +705,7 @@ class Vector2 { } - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } + add( v ) { this.x += v.x; this.y += v.y; @@ -670,14 +741,7 @@ class Vector2 { } - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } + sub( v ) { this.x -= v.x; this.y -= v.y; @@ -953,13 +1017,7 @@ class Vector2 { } - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); - - } + fromBufferAttribute( attribute, index ) { this.x = attribute.getX( index ); this.y = attribute.getY( index ); @@ -991,14 +1049,21 @@ class Vector2 { } -} + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + + } -Vector2.prototype.isVector2 = true; +} class Matrix3 { constructor() { + Matrix3.prototype.isMatrix3 = true; + this.elements = [ 1, 0, 0, @@ -1007,12 +1072,6 @@ class Matrix3 { ]; - if ( arguments.length > 0 ) { - - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - - } - } set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { @@ -1331,322 +1390,347 @@ class Matrix3 { } -Matrix3.prototype.isMatrix3 = true; - -let _canvas; +function arrayNeedsUint32( array ) { -const ImageUtils = { + // assumes larger values usually on last - getDataURL: function ( image ) { + for ( let i = array.length - 1; i >= 0; -- i ) { - if ( /^data:/i.test( image.src ) ) { + if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 - return image.src; + } - } + return false; - if ( typeof HTMLCanvasElement == 'undefined' ) { +} - return image.src; +const TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array +}; - } +function getTypedArray( type, buffer ) { - let canvas; + return new TYPED_ARRAYS[ type ]( buffer ); - if ( image instanceof HTMLCanvasElement ) { +} - canvas = image; +function createElementNS( name ) { - } else { + return document.createElementNS( 'http://www.w3.org/1999/xhtml', name ); - if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); +} - _canvas.width = image.width; - _canvas.height = image.height; +function SRGBToLinear( c ) { - const context = _canvas.getContext( '2d' ); + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); - if ( image instanceof ImageData ) { +} - context.putImageData( image, 0, 0 ); +function LinearToSRGB( c ) { - } else { + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; - context.drawImage( image, 0, 0, image.width, image.height ); +} - } +// JavaScript RGB-to-RGB transforms, defined as +// FN[InputColorSpace][OutputColorSpace] callback functions. +const FN = { + [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear }, + [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB }, +}; - canvas = _canvas; +const ColorManagement = { - } + legacyMode: true, - if ( canvas.width > 2048 || canvas.height > 2048 ) { + get workingColorSpace() { - return canvas.toDataURL( 'image/jpeg', 0.6 ); + return LinearSRGBColorSpace; - } else { + }, - return canvas.toDataURL( 'image/png' ); + set workingColorSpace( colorSpace ) { - } + console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' ); - } + }, -}; + convert: function ( color, sourceColorSpace, targetColorSpace ) { -let textureId = 0; + if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) { -class Texture extends EventDispatcher { + return color; - constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) { + } - super(); + if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) { - Object.defineProperty( this, 'id', { value: textureId ++ } ); + const fn = FN[ sourceColorSpace ][ targetColorSpace ]; - this.uuid = MathUtils.generateUUID(); + color.r = fn( color.r ); + color.g = fn( color.g ); + color.b = fn( color.b ); - this.name = ''; + return color; - this.image = image; - this.mipmaps = []; + } - this.mapping = mapping; + throw new Error( 'Unsupported color space conversion.' ); - this.wrapS = wrapS; - this.wrapT = wrapT; + }, - this.magFilter = magFilter; - this.minFilter = minFilter; + fromWorkingColorSpace: function ( color, targetColorSpace ) { - this.anisotropy = anisotropy; + return this.convert( color, this.workingColorSpace, targetColorSpace ); - this.format = format; - this.internalFormat = null; - this.type = type; + }, - this.offset = new Vector2( 0, 0 ); - this.repeat = new Vector2( 1, 1 ); - this.center = new Vector2( 0, 0 ); - this.rotation = 0; + toWorkingColorSpace: function ( color, sourceColorSpace ) { - this.matrixAutoUpdate = true; - this.matrix = new Matrix3(); + return this.convert( color, sourceColorSpace, this.workingColorSpace ); - 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) + }, - // 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; +}; - this.version = 0; - this.onUpdate = null; +const _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, 'rebeccapurple': 0x663399, '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 }; - } +const _rgb = { r: 0, g: 0, b: 0 }; +const _hslA = { h: 0, s: 0, l: 0 }; +const _hslB = { h: 0, s: 0, l: 0 }; - updateMatrix() { +function hue2rgb( p, q, t ) { - this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + 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; - } +} - clone() { +function toComponents( source, target ) { - return new this.constructor().copy( this ); + target.r = source.r; + target.g = source.g; + target.b = source.b; - } + return target; - copy( source ) { +} - this.name = source.name; +class Color { - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + constructor( r, g, b ) { - this.mapping = source.mapping; + this.isColor = true; - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + this.r = 1; + this.g = 1; + this.b = 1; - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + if ( g === undefined && b === undefined ) { - this.anisotropy = source.anisotropy; + // r is THREE.Color, hex or string + return this.set( r ); - this.format = source.format; - this.internalFormat = source.internalFormat; - this.type = source.type; + } - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); - this.center.copy( source.center ); - this.rotation = source.rotation; + return this.setRGB( r, g, b ); - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrix.copy( source.matrix ); + } - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + set( value ) { - return this; + if ( value && value.isColor ) { - } + this.copy( value ); - toJSON( meta ) { + } else if ( typeof value === 'number' ) { - const isRootObject = ( meta === undefined || typeof meta === 'string' ); + this.setHex( value ); - if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + } else if ( typeof value === 'string' ) { - return meta.textures[ this.uuid ]; + this.setStyle( value ); } - const output = { + return this; - metadata: { - version: 4.5, - type: 'Texture', - generator: 'Texture.toJSON' - }, + } - uuid: this.uuid, - name: this.name, + setScalar( scalar ) { - mapping: this.mapping, + this.r = scalar; + this.g = scalar; + this.b = scalar; - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - center: [ this.center.x, this.center.y ], - rotation: this.rotation, + return this; - wrap: [ this.wrapS, this.wrapT ], + } - format: this.format, - type: this.type, - encoding: this.encoding, + setHex( hex, colorSpace = SRGBColorSpace ) { - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + hex = Math.floor( hex ); - flipY: this.flipY, + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - premultiplyAlpha: this.premultiplyAlpha, - unpackAlignment: this.unpackAlignment + ColorManagement.toWorkingColorSpace( this, colorSpace ); - }; + return this; - if ( this.image !== undefined ) { + } - // TODO: Move to THREE.Image + setRGB( r, g, b, colorSpace = LinearSRGBColorSpace ) { - const image = this.image; + this.r = r; + this.g = g; + this.b = b; - if ( image.uuid === undefined ) { + ColorManagement.toWorkingColorSpace( this, colorSpace ); - image.uuid = MathUtils.generateUUID(); // UGH + return this; - } + } - if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) { + setHSL( h, s, l, colorSpace = LinearSRGBColorSpace ) { - let url; + // h,s,l ranges are in 0.0 - 1.0 + h = euclideanModulo( h, 1 ); + s = clamp( s, 0, 1 ); + l = clamp( l, 0, 1 ); - if ( Array.isArray( image ) ) { + if ( s === 0 ) { - // process array of images e.g. CubeTexture + this.r = this.g = this.b = l; - url = []; + } else { - for ( let i = 0, l = image.length; i < l; i ++ ) { + const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + const q = ( 2 * l ) - p; - // check cube texture with data textures + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - if ( image[ i ].isDataTexture ) { + } - url.push( serializeImage( image[ i ].image ) ); + ColorManagement.toWorkingColorSpace( this, colorSpace ); - } else { + return this; - url.push( serializeImage( image[ i ] ) ); + } - } + setStyle( style, colorSpace = SRGBColorSpace ) { - } + function handleAlpha( string ) { - } else { + if ( string === undefined ) return; - // process single image + if ( parseFloat( string ) < 1 ) { - url = serializeImage( image ); + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - } + } - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: url - }; + } - } - output.image = image.uuid; + let m; - } + if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { - if ( ! isRootObject ) { + // rgb / hsl - meta.textures[ this.uuid ] = output; + let color; + const name = m[ 1 ]; + const components = m[ 2 ]; - } + switch ( name ) { - return output; + case 'rgb': + case 'rgba': - } + if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - dispose() { + // 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; - this.dispatchEvent( { type: 'dispose' } ); + ColorManagement.toWorkingColorSpace( this, colorSpace ); - } + handleAlpha( color[ 4 ] ); - transformUv( uv ) { + return this; - if ( this.mapping !== UVMapping ) return uv; + } - uv.applyMatrix3( this.matrix ); + if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - if ( uv.x < 0 || uv.x > 1 ) { + // 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; - switch ( this.wrapS ) { + ColorManagement.toWorkingColorSpace( this, colorSpace ); - case RepeatWrapping: + handleAlpha( color[ 4 ] ); - uv.x = uv.x - Math.floor( uv.x ); - break; + return this; - case ClampToEdgeWrapping: + } - uv.x = uv.x < 0 ? 0 : 1; break; - case MirroredRepeatWrapping: + case 'hsl': + case 'hsla': - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - uv.x = Math.ceil( uv.x ) - uv.x; + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + const h = parseFloat( color[ 1 ] ) / 360; + const s = parseFloat( color[ 2 ] ) / 100; + const l = parseFloat( color[ 3 ] ) / 100; - } else { + handleAlpha( color[ 4 ] ); - uv.x = uv.x - Math.floor( uv.x ); + return this.setHSL( h, s, l, colorSpace ); } @@ -1654,6918 +1738,6747 @@ class Texture extends EventDispatcher { } - } - - if ( uv.y < 0 || uv.y > 1 ) { - - switch ( this.wrapT ) { - - case RepeatWrapping: + } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { - uv.y = uv.y - Math.floor( uv.y ); - break; + // hex color - case ClampToEdgeWrapping: + const hex = m[ 1 ]; + const size = hex.length; - uv.y = uv.y < 0 ? 0 : 1; - break; + if ( size === 3 ) { - case MirroredRepeatWrapping: + // #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; - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + ColorManagement.toWorkingColorSpace( this, colorSpace ); - uv.y = Math.ceil( uv.y ) - uv.y; + return this; - } else { + } else if ( size === 6 ) { - uv.y = uv.y - Math.floor( uv.y ); + // #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; - } + ColorManagement.toWorkingColorSpace( this, colorSpace ); - break; + return this; } } - if ( this.flipY ) { + if ( style && style.length > 0 ) { - uv.y = 1 - uv.y; + return this.setColorName( style, colorSpace ); } - return uv; + return this; } - set needsUpdate( value ) { + setColorName( style, colorSpace = SRGBColorSpace ) { - if ( value === true ) this.version ++; + // color keywords + const hex = _colorKeywords[ style.toLowerCase() ]; - } + if ( hex !== undefined ) { -} + // red + this.setHex( hex, colorSpace ); -Texture.DEFAULT_IMAGE = undefined; -Texture.DEFAULT_MAPPING = UVMapping; + } else { -Texture.prototype.isTexture = true; + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); -function serializeImage( image ) { + } - if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || - ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + return this; - // default images + } - return ImageUtils.getDataURL( image ); + clone() { - } else { + return new this.constructor( this.r, this.g, this.b ); - if ( image.data ) { + } - // images of DataTexture + copy( color ) { - return { - data: Array.prototype.slice.call( image.data ), - width: image.width, - height: image.height, - type: image.data.constructor.name - }; - - } else { - - console.warn( 'THREE.Texture: Unable to serialize Texture.' ); - return {}; + this.r = color.r; + this.g = color.g; + this.b = color.b; - } + return this; } -} - -class Vector4 { + copySRGBToLinear( color ) { - constructor( x = 0, y = 0, z = 0, w = 1 ) { + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); - this.x = x; - this.y = y; - this.z = z; - this.w = w; + return this; } - get width() { - - return this.z; - - } + copyLinearToSRGB( color ) { - set width( value ) { + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); - this.z = value; + return this; } - get height() { - - return this.w; - - } + convertSRGBToLinear() { - set height( value ) { + this.copySRGBToLinear( this ); - this.w = value; + return this; } - set( x, y, z, w ) { + convertLinearToSRGB() { - this.x = x; - this.y = y; - this.z = z; - this.w = w; + this.copyLinearToSRGB( this ); return this; } - setScalar( scalar ) { + getHex( colorSpace = SRGBColorSpace ) { - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - return this; + return clamp( _rgb.r * 255, 0, 255 ) << 16 ^ clamp( _rgb.g * 255, 0, 255 ) << 8 ^ clamp( _rgb.b * 255, 0, 255 ) << 0; } - setX( x ) { - - this.x = x; + getHexString( colorSpace = SRGBColorSpace ) { - return this; + return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 ); } - setY( y ) { + getHSL( target, colorSpace = LinearSRGBColorSpace ) { - this.y = y; + // h,s,l ranges are in 0.0 - 1.0 - return this; + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - } + const r = _rgb.r, g = _rgb.g, b = _rgb.b; - setZ( z ) { + const max = Math.max( r, g, b ); + const min = Math.min( r, g, b ); - this.z = z; + let hue, saturation; + const lightness = ( min + max ) / 2.0; - return this; + if ( min === max ) { - } + hue = 0; + saturation = 0; - setW( w ) { + } else { - this.w = w; + const delta = max - min; - return this; + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - } + switch ( max ) { - setComponent( index, value ) { + 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; - switch ( index ) { + } - 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 ); + hue /= 6; } - return this; + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; } - getComponent( index ) { + getRGB( target, colorSpace = LinearSRGBColorSpace ) { - switch ( index ) { + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - 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 ); + target.r = _rgb.r; + target.g = _rgb.g; + target.b = _rgb.b; - } + return target; } - clone() { + getStyle( colorSpace = SRGBColorSpace ) { - return new this.constructor( this.x, this.y, this.z, this.w ); + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - } + if ( colorSpace !== SRGBColorSpace ) { - copy( v ) { + // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). + return `color(${ colorSpace } ${ _rgb.r } ${ _rgb.g } ${ _rgb.b })`; - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + } - return this; + return `rgb(${( _rgb.r * 255 ) | 0},${( _rgb.g * 255 ) | 0},${( _rgb.b * 255 ) | 0})`; } - add( v, w ) { - - if ( w !== undefined ) { + offsetHSL( h, s, l ) { - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + this.getHSL( _hslA ); - } + _hslA.h += h; _hslA.s += s; _hslA.l += l; - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + this.setHSL( _hslA.h, _hslA.s, _hslA.l ); return this; } - addScalar( s ) { + add( color ) { - this.x += s; - this.y += s; - this.z += s; - this.w += s; + this.r += color.r; + this.g += color.g; + this.b += color.b; return this; } - addVectors( a, b ) { + addColors( color1, color2 ) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; return this; } - addScaledVector( v, s ) { + addScalar( s ) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + this.r += s; + this.g += s; + this.b += s; return this; } - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } + sub( color ) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + 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 ); return this; } - subScalar( s ) { + multiply( color ) { - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; return this; } - subVectors( a, b ) { + multiplyScalar( s ) { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + this.r *= s; + this.g *= s; + this.b *= s; return this; } - multiply( v ) { + lerp( color, alpha ) { - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - this.w *= v.w; + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; return this; } - multiplyScalar( scalar ) { + lerpColors( color1, color2, alpha ) { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + this.r = color1.r + ( color2.r - color1.r ) * alpha; + this.g = color1.g + ( color2.g - color1.g ) * alpha; + this.b = color1.b + ( color2.b - color1.b ) * alpha; return this; } - applyMatrix4( m ) { + lerpHSL( color, alpha ) { - const x = this.x, y = this.y, z = this.z, w = this.w; - const e = m.elements; + this.getHSL( _hslA ); + color.getHSL( _hslB ); - 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; + const h = lerp( _hslA.h, _hslB.h, alpha ); + const s = lerp( _hslA.s, _hslB.s, alpha ); + const l = lerp( _hslA.l, _hslB.l, alpha ); + + this.setHSL( h, s, l ); return this; } - divideScalar( scalar ) { + equals( c ) { - return this.multiplyScalar( 1 / scalar ); + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); } - setAxisAngleFromQuaternion( q ) { + fromArray( array, offset = 0 ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - // q is assumed to be normalized + return this; - this.w = 2 * Math.acos( q.w ); + } - const s = Math.sqrt( 1 - q.w * q.w ); + toArray( array = [], offset = 0 ) { - if ( s < 0.0001 ) { + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - this.x = 1; - this.y = 0; - this.z = 0; + return array; - } else { + } - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + fromBufferAttribute( attribute, index ) { - } + this.r = attribute.getX( index ); + this.g = attribute.getY( index ); + this.b = attribute.getZ( index ); return this; } - setAxisAngleFromRotationMatrix( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - let angle, x, y, z; // variables for result - const epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - - te = m.elements, + toJSON() { - 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 ]; + return this.getHex(); - 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 + *[ Symbol.iterator ]() { - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + yield this.r; + yield this.g; + yield this.b; - // this singularity is identity matrix so angle = 0 + } - this.set( 1, 0, 0, 0 ); +} - return this; // zero angle, arbitrary axis +Color.NAMES = _colorKeywords; - } +let _canvas; - // otherwise this singularity is angle = 180 +class ImageUtils { - angle = Math.PI; + static getDataURL( image ) { - const xx = ( m11 + 1 ) / 2; - const yy = ( m22 + 1 ) / 2; - const zz = ( m33 + 1 ) / 2; - const xy = ( m12 + m21 ) / 4; - const xz = ( m13 + m31 ) / 4; - const yz = ( m23 + m32 ) / 4; + if ( /^data:/i.test( image.src ) ) { - if ( ( xx > yy ) && ( xx > zz ) ) { + return image.src; - // m11 is the largest diagonal term + } - if ( xx < epsilon ) { + if ( typeof HTMLCanvasElement == 'undefined' ) { - x = 0; - y = 0.707106781; - z = 0.707106781; + return image.src; - } else { + } - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + let canvas; - } + if ( image instanceof HTMLCanvasElement ) { - } else if ( yy > zz ) { + canvas = image; - // m22 is the largest diagonal term + } else { - if ( yy < epsilon ) { + if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' ); - x = 0.707106781; - y = 0; - z = 0.707106781; + _canvas.width = image.width; + _canvas.height = image.height; - } else { + const context = _canvas.getContext( '2d' ); - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + if ( image instanceof ImageData ) { - } + context.putImageData( image, 0, 0 ); } else { - // m33 is the largest diagonal term so base result on this + context.drawImage( image, 0, 0, image.width, image.height ); - if ( zz < epsilon ) { + } - x = 0.707106781; - y = 0.707106781; - z = 0; + canvas = _canvas; - } else { + } - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + if ( canvas.width > 2048 || canvas.height > 2048 ) { - } + console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image ); - } + return canvas.toDataURL( 'image/jpeg', 0.6 ); - this.set( x, y, z, angle ); + } else { - return this; // return 180 deg rotation + return canvas.toDataURL( 'image/png' ); } - // as we have reached here there are no singularities so we can handle normally - - let 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; + static sRGBToLinear( image ) { - // 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 + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + const canvas = createElementNS( 'canvas' ); - return this; + canvas.width = image.width; + canvas.height = image.height; - } + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height ); - min( v ) { + const imageData = context.getImageData( 0, 0, image.width, image.height ); + const data = imageData.data; - 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 ); + for ( let i = 0; i < data.length; i ++ ) { - return this; + data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255; - } + } - max( v ) { + context.putImageData( imageData, 0, 0 ); - 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 ); + return canvas; - return this; + } else if ( image.data ) { - } + const data = image.data.slice( 0 ); - clamp( min, max ) { + for ( let i = 0; i < data.length; i ++ ) { - // assumes min < max, componentwise + if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) { - 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 ) ); + data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 ); - return this; + } else { - } + // assuming float - clampScalar( minVal, maxVal ) { + data[ i ] = SRGBToLinear( data[ i ] ); - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); + } - return this; + } - } + return { + data: data, + width: image.width, + height: image.height + }; - clampLength( min, max ) { + } else { - const length = this.length(); + console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' ); + return image; - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + } } - floor() { +} - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); +class Source { - return this; + constructor( data = null ) { - } + this.isSource = true; - ceil() { + this.uuid = generateUUID(); - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + this.data = data; - return this; + this.version = 0; } - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + set needsUpdate( value ) { - return this; + if ( value === true ) this.version ++; } - roundToZero() { + toJSON( meta ) { - 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 ); + const isRootObject = ( meta === undefined || typeof meta === 'string' ); - return this; + if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) { - } + return meta.images[ this.uuid ]; - negate() { + } - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + const output = { + uuid: this.uuid, + url: '' + }; - return this; + const data = this.data; - } + if ( data !== null ) { - dot( v ) { + let url; - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + if ( Array.isArray( data ) ) { - } + // cube texture - lengthSq() { + url = []; - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + for ( let i = 0, l = data.length; i < l; i ++ ) { - } + if ( data[ i ].isDataTexture ) { - length() { + url.push( serializeImage( data[ i ].image ) ); - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + } else { - } + url.push( serializeImage( data[ i ] ) ); - manhattanLength() { + } - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + } - } + } else { - normalize() { + // texture - return this.divideScalar( this.length() || 1 ); + url = serializeImage( data ); - } + } - setLength( length ) { + output.url = url; - return this.normalize().multiplyScalar( length ); + } - } + if ( ! isRootObject ) { - lerp( v, alpha ) { + meta.images[ this.uuid ] = output; - 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 this; + return output; } - lerpVectors( v1, v2, alpha ) { +} - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; - this.w = v1.w + ( v2.w - v1.w ) * alpha; +function serializeImage( image ) { - return this; + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - } + // default images - equals( v ) { + return ImageUtils.getDataURL( image ); - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + } else { - } + if ( image.data ) { - fromArray( array, offset = 0 ) { + // images of DataTexture - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + return { + data: Array.from( image.data ), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; - return this; + } else { + + console.warn( 'THREE.Texture: Unable to serialize Texture.' ); + return {}; + + } } - toArray( array = [], offset = 0 ) { +} - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; +let textureId = 0; - return array; +class Texture extends EventDispatcher { - } + constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) { - fromBufferAttribute( attribute, index, offset ) { + super(); - if ( offset !== undefined ) { + this.isTexture = true; - console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); + Object.defineProperty( this, 'id', { value: textureId ++ } ); - } + this.uuid = generateUUID(); - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - this.w = attribute.getW( index ); + this.name = ''; - return this; + this.source = new Source( image ); + this.mipmaps = []; - } + this.mapping = mapping; - random() { + this.wrapS = wrapS; + this.wrapT = wrapT; - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - this.w = Math.random(); + this.magFilter = magFilter; + this.minFilter = minFilter; - return this; + this.anisotropy = anisotropy; - } + this.format = format; + this.internalFormat = null; + this.type = type; -} + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); + this.rotation = 0; -Vector4.prototype.isVector4 = true; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); -/* - In options, we can specify: - * Texture parameters for an auto-generated target texture - * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers -*/ -class WebGLRenderTarget extends EventDispatcher { + 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) - constructor( width, height, options ) { + // 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; - super(); + this.userData = {}; - this.width = width; - this.height = height; - this.depth = 1; + this.version = 0; + this.onUpdate = null; - this.scissor = new Vector4( 0, 0, width, height ); - this.scissorTest = false; + this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not + this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures) - this.viewport = new Vector4( 0, 0, width, height ); + } - options = options || {}; + get image() { - this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + return this.source.data; - this.texture.image = {}; - this.texture.image.width = width; - this.texture.image.height = height; - this.texture.image.depth = 1; + } - this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; - this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + set image( value ) { - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; - this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + this.source.data = value; } - setTexture( texture ) { - - texture.image = { - width: this.width, - height: this.height, - depth: this.depth - }; + updateMatrix() { - this.texture = texture; + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); } - setSize( width, height, depth = 1 ) { + clone() { - if ( this.width !== width || this.height !== height || this.depth !== depth ) { + return new this.constructor().copy( this ); - this.width = width; - this.height = height; - this.depth = depth; + } - this.texture.image.width = width; - this.texture.image.height = height; - this.texture.image.depth = depth; + copy( source ) { - this.dispose(); + this.name = source.name; - } + this.source = source.source; + this.mipmaps = source.mipmaps.slice( 0 ); - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); + this.mapping = source.mapping; - } + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - clone() { + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - return new this.constructor().copy( this ); + this.anisotropy = source.anisotropy; - } + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; - copy( source ) { + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; - this.width = source.width; - this.height = source.height; - this.depth = source.depth; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); - this.viewport.copy( source.viewport ); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - this.texture = source.texture.clone(); + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + this.needsUpdate = true; return this; } - dispose() { + toJSON( meta ) { - this.dispatchEvent( { type: 'dispose' } ); + const isRootObject = ( meta === undefined || typeof meta === 'string' ); - } + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { -} + return meta.textures[ this.uuid ]; -WebGLRenderTarget.prototype.isWebGLRenderTarget = true; + } -class WebGLMultisampleRenderTarget extends WebGLRenderTarget { + const output = { - constructor( width, height, options ) { + metadata: { + version: 4.5, + type: 'Texture', + generator: 'Texture.toJSON' + }, - super( width, height, options ); + uuid: this.uuid, + name: this.name, - this.samples = 4; + image: this.source.toJSON( meta ).uuid, - } + mapping: this.mapping, - copy( source ) { + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, - super.copy.call( this, source ); + wrap: [ this.wrapS, this.wrapT ], - this.samples = source.samples; + format: this.format, + type: this.type, + encoding: this.encoding, - return this; + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - } + flipY: this.flipY, -} + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment -WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true; + }; -class Quaternion { + if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData; - constructor( x = 0, y = 0, z = 0, w = 1 ) { + if ( ! isRootObject ) { - this._x = x; - this._y = y; - this._z = z; - this._w = w; + meta.textures[ this.uuid ] = output; + + } + + return output; } - static slerp( qa, qb, qm, t ) { + dispose() { - return qm.copy( qa ).slerp( qb, t ); + this.dispatchEvent( { type: 'dispose' } ); } - static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + transformUv( uv ) { - // fuzz-free, array-based Quaternion SLERP operation + if ( this.mapping !== UVMapping ) return uv; - let x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ]; + uv.applyMatrix3( this.matrix ); - const x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; + if ( uv.x < 0 || uv.x > 1 ) { - if ( t === 0 ) { + switch ( this.wrapS ) { - dst[ dstOffset + 0 ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - return; + case RepeatWrapping: - } + uv.x = uv.x - Math.floor( uv.x ); + break; - if ( t === 1 ) { + case ClampToEdgeWrapping: - dst[ dstOffset + 0 ] = x1; - dst[ dstOffset + 1 ] = y1; - dst[ dstOffset + 2 ] = z1; - dst[ dstOffset + 3 ] = w1; - return; + uv.x = uv.x < 0 ? 0 : 1; + break; - } + case MirroredRepeatWrapping: - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - let s = 1 - t; - const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; + uv.x = Math.ceil( uv.x ) - uv.x; - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { + } else { - const sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); + uv.x = uv.x - Math.floor( uv.x ); - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; + } + + break; } - const tDir = t * dir; + } - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; + if ( uv.y < 0 || uv.y > 1 ) { - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { + switch ( this.wrapT ) { - const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + case RepeatWrapping: - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; + uv.y = uv.y - Math.floor( uv.y ); + break; - } + case ClampToEdgeWrapping: - } + uv.y = uv.y < 0 ? 0 : 1; + break; - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; + case MirroredRepeatWrapping: - } + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { + uv.y = Math.ceil( uv.y ) - uv.y; - const x0 = src0[ srcOffset0 ]; - const y0 = src0[ srcOffset0 + 1 ]; - const z0 = src0[ srcOffset0 + 2 ]; - const w0 = src0[ srcOffset0 + 3 ]; + } else { - const x1 = src1[ srcOffset1 ]; - const y1 = src1[ srcOffset1 + 1 ]; - const z1 = src1[ srcOffset1 + 2 ]; - const w1 = src1[ srcOffset1 + 3 ]; + uv.y = uv.y - Math.floor( uv.y ); - dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; - dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; - dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; - dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + } - return dst; + break; - } + } - get x() { + } - return this._x; + if ( this.flipY ) { - } + uv.y = 1 - uv.y; - set x( value ) { + } - this._x = value; - this._onChangeCallback(); + return uv; } - get y() { + set needsUpdate( value ) { - return this._y; + if ( value === true ) { + + this.version ++; + this.source.needsUpdate = true; + + } } - set y( value ) { +} - this._y = value; - this._onChangeCallback(); +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; + +class Vector4 { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + Vector4.prototype.isVector4 = true; + + this.x = x; + this.y = y; + this.z = z; + this.w = w; } - get z() { + get width() { - return this._z; + return this.z; } - set z( value ) { + set width( value ) { - this._z = value; - this._onChangeCallback(); + this.z = value; } - get w() { + get height() { - return this._w; + return this.w; } - set w( value ) { + set height( value ) { - this._w = value; - this._onChangeCallback(); + this.w = value; } set( x, y, z, w ) { - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - this._onChangeCallback(); + this.x = x; + this.y = y; + this.z = z; + this.w = w; return this; } - clone() { + setScalar( scalar ) { - return new this.constructor( this._x, this._y, this._z, this._w ); + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - } + return this; - copy( quaternion ) { + } - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + setX( x ) { - this._onChangeCallback(); + this.x = x; return this; } - setFromEuler( euler, update ) { - - if ( ! ( euler && euler.isEuler ) ) { - - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + setY( y ) { - } + this.y = y; - const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + return this; - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + } - const cos = Math.cos; - const sin = Math.sin; + setZ( z ) { - const c1 = cos( x / 2 ); - const c2 = cos( y / 2 ); - const c3 = cos( z / 2 ); + this.z = z; - const s1 = sin( x / 2 ); - const s2 = sin( y / 2 ); - const s3 = sin( z / 2 ); + return this; - switch ( order ) { + } - case '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; - break; + setW( w ) { - case 'YXZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; + this.w = w; - case 'ZXY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; + return this; - case '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; - break; + } - case 'YZX': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; + setComponent( index, value ) { - case 'XZY': - 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; - break; + switch ( index ) { - default: - console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); + 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 ( update !== false ) this._onChangeCallback(); - return this; } - setFromAxisAngle( axis, angle ) { + getComponent( index ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + switch ( index ) { - // assumes axis is normalized + 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 ); - const halfAngle = angle / 2, s = Math.sin( halfAngle ); + } - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + } - this._onChangeCallback(); + clone() { - return this; + return new this.constructor( this.x, this.y, this.z, this.w ); } - setFromRotationMatrix( m ) { + copy( v ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + return this; - const 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 ], + add( v ) { - trace = m11 + m22 + m33; + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - if ( trace > 0 ) { + return this; - const 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; - - } else if ( m11 > m22 && m11 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; - - } else if ( m22 > m33 ) { - - const 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 { - - const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; - - } + addScalar( s ) { - this._onChangeCallback(); + this.x += s; + this.y += s; + this.z += s; + this.w += s; return this; } - setFromUnitVectors( vFrom, vTo ) { - - // assumes direction vectors vFrom and vTo are normalized - - const EPS = 0.000001; - - let r = vFrom.dot( vTo ) + 1; - - if ( r < EPS ) { - - r = 0; + addVectors( a, b ) { - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.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; - this._x = - vFrom.y; - this._y = vFrom.x; - this._z = 0; - this._w = r; + return this; - } else { + } - this._x = 0; - this._y = - vFrom.z; - this._z = vFrom.y; - this._w = r; + addScaledVector( v, s ) { - } + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - } else { + return this; - // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 + } - this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; - this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; - this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; - this._w = r; + sub( v ) { - } + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - return this.normalize(); + return this; } - angleTo( q ) { - - return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) ); - - } + subScalar( s ) { - rotateTowards( q, step ) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - const angle = this.angleTo( q ); + return this; - if ( angle === 0 ) return this; + } - const t = Math.min( 1, step / angle ); + subVectors( a, b ) { - this.slerp( q, t ); + 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; } - identity() { + multiply( v ) { - return this.set( 0, 0, 0, 1 ); + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + + return this; } - invert() { + multiplyScalar( scalar ) { - // quaternion is assumed to have unit length + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - return this.conjugate(); + return this; } - conjugate() { + applyMatrix4( m ) { - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; - this._onChangeCallback(); + 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; return this; } - dot( v ) { - - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - - } - - lengthSq() { + divideScalar( scalar ) { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + return this.multiplyScalar( 1 / scalar ); } - length() { + setAxisAngleFromQuaternion( q ) { - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - } + // q is assumed to be normalized - normalize() { + this.w = 2 * Math.acos( q.w ); - let l = this.length(); + const s = Math.sqrt( 1 - q.w * q.w ); - if ( l === 0 ) { + if ( s < 0.0001 ) { - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + this.x = 1; + this.y = 0; + this.z = 0; } else { - l = 1 / l; - - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; } - this._onChangeCallback(); - return this; } - multiply( q, p ) { - - if ( p !== undefined ) { - - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + setAxisAngleFromRotationMatrix( m ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - return this.multiplyQuaternions( this, q ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - } + let angle, x, y, z; // variables for result + const epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - premultiply( q ) { + te = m.elements, - return this.multiplyQuaternions( q, this ); + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - } + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - multiplyQuaternions( a, b ) { + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + // this singularity is identity matrix so angle = 0 - 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.set( 1, 0, 0, 0 ); - this._onChangeCallback(); + return this; // zero angle, arbitrary axis - return this; + } - } + // otherwise this singularity is angle = 180 - slerp( qb, t ) { + angle = Math.PI; - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); + const xx = ( m11 + 1 ) / 2; + const yy = ( m22 + 1 ) / 2; + const zz = ( m33 + 1 ) / 2; + const xy = ( m12 + m21 ) / 4; + const xz = ( m13 + m31 ) / 4; + const yz = ( m23 + m32 ) / 4; - const x = this._x, y = this._y, z = this._z, w = this._w; + if ( ( xx > yy ) && ( xx > zz ) ) { - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + // m11 is the largest diagonal term - let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if ( xx < epsilon ) { - if ( cosHalfTheta < 0 ) { + x = 0; + y = 0.707106781; + z = 0.707106781; - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + } else { - cosHalfTheta = - cosHalfTheta; + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - } else { + } - this.copy( qb ); + } else if ( yy > zz ) { - } + // m22 is the largest diagonal term - if ( cosHalfTheta >= 1.0 ) { + if ( yy < epsilon ) { - this._w = w; - this._x = x; - this._y = y; - this._z = z; + x = 0.707106781; + y = 0; + z = 0.707106781; - return this; + } else { - } + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; + } - if ( sqrSinHalfTheta <= Number.EPSILON ) { + } else { - const s = 1 - t; - this._w = s * w + t * this._w; - this._x = s * x + t * this._x; - this._y = s * y + t * this._y; - this._z = s * z + t * this._z; + // m33 is the largest diagonal term so base result on this - this.normalize(); - this._onChangeCallback(); + if ( zz < epsilon ) { - return this; + x = 0.707106781; + y = 0.707106781; + z = 0; - } + } else { - const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); - const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - 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(); + } - return this; + this.set( x, y, z, angle ); - } + return this; // return 180 deg rotation - equals( quaternion ) { + } - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + // as we have reached here there are no singularities so we can handle normally - } + let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - fromArray( array, offset = 0 ) { + if ( Math.abs( s ) < 0.001 ) s = 1; - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + // 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 - this._onChangeCallback(); + 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; } - toArray( array = [], offset = 0 ) { + min( v ) { - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + 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 array; + return this; } - fromBufferAttribute( attribute, index ) { + max( v ) { - this._x = attribute.getX( index ); - this._y = attribute.getY( index ); - this._z = attribute.getZ( index ); - this._w = attribute.getW( index ); + 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 ); return this; } - _onChange( callback ) { + clamp( min, max ) { - this._onChangeCallback = callback; + // assumes min < max, componentwise + + 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; } - _onChangeCallback() {} + clampScalar( minVal, maxVal ) { -} + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); -Quaternion.prototype.isQuaternion = true; + return this; -class Vector3 { + } - constructor( x = 0, y = 0, z = 0 ) { + clampLength( min, max ) { - this.x = x; - this.y = y; - this.z = z; + const length = this.length(); - } + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - set( x, y, z ) { + } - if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) + floor() { - this.x = x; - this.y = y; - this.z = z; + 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; } - setScalar( scalar ) { + ceil() { - this.x = scalar; - this.y = scalar; - this.z = scalar; + 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; } - setX( x ) { + round() { - this.x = x; + 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; } - setY( y ) { + roundToZero() { - this.y = y; + 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; } - setZ( z ) { + negate() { - this.z = z; + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; return this; } - setComponent( index, value ) { + dot( v ) { - switch ( index ) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - 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 ); + } - } + lengthSq() { - return this; + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; } - getComponent( 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 ); + length() { - } + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); } - clone() { + manhattanLength() { - return new this.constructor( this.x, this.y, this.z ); + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); } - copy( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; + normalize() { - return this; + return this.divideScalar( this.length() || 1 ); } - add( v, w ) { + setLength( length ) { - if ( w !== undefined ) { + return this.normalize().multiplyScalar( length ); - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + } - } + lerp( v, alpha ) { - this.x += v.x; - this.y += v.y; - this.z += v.z; + 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 this; } - addScalar( s ) { + lerpVectors( v1, v2, alpha ) { - this.x += s; - this.y += s; - this.z += s; + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; return this; } - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + equals( v ) { - return this; + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); } - addScaledVector( v, s ) { + fromArray( array, offset = 0 ) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; return this; } - sub( v, w ) { + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - if ( w !== undefined ) { + return array; - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + } - } + fromBufferAttribute( attribute, index ) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); return this; } - subScalar( s ) { + random() { - this.x -= s; - this.y -= s; - this.z -= s; + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); return this; } - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + *[ Symbol.iterator ]() { - return this; + yield this.x; + yield this.y; + yield this.z; + yield this.w; } - multiply( v, w ) { +} - if ( w !== undefined ) { +/* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers +*/ +class WebGLRenderTarget extends EventDispatcher { - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + constructor( width, height, options = {} ) { - } + super(); - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + this.isWebGLRenderTarget = true; - return this; + this.width = width; + this.height = height; + this.depth = 1; - } + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - multiplyScalar( scalar ) { + this.viewport = new Vector4( 0, 0, width, height ); - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + const image = { width: width, height: height, depth: 1 }; - return this; + this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture.isRenderTargetTexture = true; - } + this.texture.flipY = false; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; - multiplyVectors( a, b ) { + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; - return this; + this.samples = options.samples !== undefined ? options.samples : 0; } - applyEuler( euler ) { + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; - if ( ! ( euler && euler.isEuler ) ) { + this.texture.image.width = width; + this.texture.image.height = height; + this.texture.image.depth = depth; - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + this.dispose(); } - return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); } - applyAxisAngle( axis, angle ) { + clone() { - return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); + return new this.constructor().copy( this ); } - applyMatrix3( m ) { + copy( source ) { - const x = this.x, y = this.y, z = this.z; - const e = m.elements; + this.width = source.width; + this.height = source.height; + this.depth = source.depth; - 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; + this.viewport.copy( source.viewport ); - return this; + this.texture = source.texture.clone(); + this.texture.isRenderTargetTexture = true; - } + // ensure image object is not shared, see #20328 - applyNormalMatrix( m ) { + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); - return this.applyMatrix3( m ).normalize(); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; - } + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); - applyMatrix4( m ) { + this.samples = source.samples; - const x = this.x, y = this.y, z = this.z; - const e = m.elements; + return this; - const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + } - 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; + dispose() { - return this; + this.dispatchEvent( { type: 'dispose' } ); } - applyQuaternion( q ) { - - const x = this.x, y = this.y, z = this.z; - const qx = q.x, qy = q.y, qz = q.z, qw = q.w; +} - // calculate quat * vector +class DataArrayTexture extends Texture { - const ix = qw * x + qy * z - qz * y; - const iy = qw * y + qz * x - qx * z; - const iz = qw * z + qx * y - qy * x; - const iw = - qx * x - qy * y - qz * z; + constructor( data = null, width = 1, height = 1, depth = 1 ) { - // calculate result * inverse quat + super( null ); - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; + this.isDataArrayTexture = true; - return this; + this.image = { data, width, height, depth }; - } + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; - project( camera ) { + this.wrapR = ClampToEdgeWrapping; - return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; } - unproject( camera ) { +} - return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); +class WebGLArrayRenderTarget extends WebGLRenderTarget { - } + constructor( width, height, depth ) { - transformDirection( m ) { + super( width, height ); - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + this.isWebGLArrayRenderTarget = true; - const x = this.x, y = this.y, z = this.z; - const e = m.elements; + this.depth = depth; - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + this.texture = new DataArrayTexture( null, width, height, depth ); - return this.normalize(); + this.texture.isRenderTargetTexture = true; } - divide( v ) { +} - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; +class Data3DTexture extends Texture { - return this; + constructor( data = null, width = 1, height = 1, depth = 1 ) { - } + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in DataTexture3D directly. + // + // const texture = new THREE.DataTexture3D( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 - divideScalar( scalar ) { + super( null ); - return this.multiplyScalar( 1 / scalar ); + this.isData3DTexture = true; - } + this.image = { data, width, height, depth }; - min( v ) { + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; - 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.wrapR = ClampToEdgeWrapping; - return this; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; } - max( v ) { +} - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); +class WebGL3DRenderTarget extends WebGLRenderTarget { - return this; + constructor( width, height, depth ) { - } + super( width, height ); - clamp( min, max ) { + this.isWebGL3DRenderTarget = true; - // assumes min < max, componentwise + this.depth = depth; - 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.texture = new Data3DTexture( null, width, height, depth ); - return this; + this.texture.isRenderTargetTexture = true; } - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); +} - return this; +class WebGLMultipleRenderTargets extends WebGLRenderTarget { - } + constructor( width, height, count, options = {} ) { - clampLength( min, max ) { + super( width, height, options ); - const length = this.length(); + this.isWebGLMultipleRenderTargets = true; - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + const texture = this.texture; - } + this.texture = []; - floor() { + for ( let i = 0; i < count; i ++ ) { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + this.texture[ i ] = texture.clone(); + this.texture[ i ].isRenderTargetTexture = true; - return this; + } } - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + setSize( width, height, depth = 1 ) { - return this; + if ( this.width !== width || this.height !== height || this.depth !== depth ) { - } + this.width = width; + this.height = height; + this.depth = depth; - round() { + for ( let i = 0, il = this.texture.length; i < il; i ++ ) { - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + this.texture[ i ].image.width = width; + this.texture[ i ].image.height = height; + this.texture[ i ].image.depth = depth; - return this; + } - } + this.dispose(); - roundToZero() { + } - 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.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); return this; } - negate() { + copy( source ) { - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + this.dispose(); - return this; + this.width = source.width; + this.height = source.height; + this.depth = source.depth; - } + this.viewport.set( 0, 0, this.width, this.height ); + this.scissor.set( 0, 0, this.width, this.height ); - dot( v ) { + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; - return this.x * v.x + this.y * v.y + this.z * v.z; + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); - } + this.texture.length = 0; - // TODO lengthSquared? + for ( let i = 0, il = source.texture.length; i < il; i ++ ) { - lengthSq() { + this.texture[ i ] = source.texture[ i ].clone(); + this.texture[ i ].isRenderTargetTexture = true; - return this.x * this.x + this.y * this.y + this.z * this.z; + } + + return this; } - length() { +} - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); +class Quaternion { - } + constructor( x = 0, y = 0, z = 0, w = 1 ) { - manhattanLength() { + this.isQuaternion = true; - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + this._x = x; + this._y = y; + this._z = z; + this._w = w; } - normalize() { + static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - return this.divideScalar( this.length() || 1 ); + // fuzz-free, array-based Quaternion SLERP operation - } + let x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ]; - setLength( length ) { + const x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - return this.normalize().multiplyScalar( length ); + if ( t === 0 ) { - } + dst[ dstOffset + 0 ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + return; - lerp( v, alpha ) { + } - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + if ( t === 1 ) { - return this; + dst[ dstOffset + 0 ] = x1; + dst[ dstOffset + 1 ] = y1; + dst[ dstOffset + 2 ] = z1; + dst[ dstOffset + 3 ] = w1; + return; - } + } - lerpVectors( v1, v2, alpha ) { + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - return this; + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - } + const sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - cross( v, w ) { + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - if ( w !== undefined ) { + } - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + const tDir = t * dir; - } + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - return this.crossVectors( this, v ); + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { - } + const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - crossVectors( a, b ) { + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; - const ax = a.x, ay = a.y, az = a.z; - const bx = b.x, by = b.y, bz = b.z; + } - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + } - return this; + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; } - projectOnVector( v ) { + static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { - const denominator = v.lengthSq(); + const x0 = src0[ srcOffset0 ]; + const y0 = src0[ srcOffset0 + 1 ]; + const z0 = src0[ srcOffset0 + 2 ]; + const w0 = src0[ srcOffset0 + 3 ]; - if ( denominator === 0 ) return this.set( 0, 0, 0 ); + const x1 = src1[ srcOffset1 ]; + const y1 = src1[ srcOffset1 + 1 ]; + const z1 = src1[ srcOffset1 + 2 ]; + const w1 = src1[ srcOffset1 + 3 ]; - const scalar = v.dot( this ) / denominator; + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; - return this.copy( v ).multiplyScalar( scalar ); + return dst; } - projectOnPlane( planeNormal ) { - - _vector.copy( this ).projectOnVector( planeNormal ); + get x() { - return this.sub( _vector ); + return this._x; } - reflect( normal ) { - - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + set x( value ) { - return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + this._x = value; + this._onChangeCallback(); } - angleTo( v ) { - - const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + get y() { - if ( denominator === 0 ) return Math.PI / 2; + return this._y; - const theta = this.dot( v ) / denominator; + } - // clamp, to handle numerical problems + set y( value ) { - return Math.acos( MathUtils.clamp( theta, - 1, 1 ) ); + this._y = value; + this._onChangeCallback(); } - distanceTo( v ) { + get z() { - return Math.sqrt( this.distanceToSquared( v ) ); + return this._z; } - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + set z( value ) { - return dx * dx + dy * dy + dz * dz; + this._z = value; + this._onChangeCallback(); } - manhattanDistanceTo( v ) { + get w() { - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + return this._w; } - setFromSpherical( s ) { + set w( value ) { - return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + this._w = value; + this._onChangeCallback(); } - setFromSphericalCoords( radius, phi, theta ) { + set( x, y, z, w ) { - const sinPhiRadius = Math.sin( phi ) * radius; + this._x = x; + this._y = y; + this._z = z; + this._w = w; - this.x = sinPhiRadius * Math.sin( theta ); - this.y = Math.cos( phi ) * radius; - this.z = sinPhiRadius * Math.cos( theta ); + this._onChangeCallback(); return this; } - setFromCylindrical( c ) { + clone() { - return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + return new this.constructor( this._x, this._y, this._z, this._w ); } - setFromCylindricalCoords( radius, theta, y ) { + copy( quaternion ) { - this.x = radius * Math.sin( theta ); - this.y = y; - this.z = radius * Math.cos( theta ); + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + + this._onChangeCallback(); return this; } - setFromMatrixPosition( m ) { - - const e = m.elements; + setFromEuler( euler, update ) { - this.x = e[ 12 ]; - this.y = e[ 13 ]; - this.z = e[ 14 ]; + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; - return this; + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - } + const cos = Math.cos; + const sin = Math.sin; - setFromMatrixScale( m ) { + const c1 = cos( x / 2 ); + const c2 = cos( y / 2 ); + const c3 = cos( z / 2 ); - const sx = this.setFromMatrixColumn( m, 0 ).length(); - const sy = this.setFromMatrixColumn( m, 1 ).length(); - const sz = this.setFromMatrixColumn( m, 2 ).length(); + const s1 = sin( x / 2 ); + const s2 = sin( y / 2 ); + const s3 = sin( z / 2 ); - this.x = sx; - this.y = sy; - this.z = sz; + switch ( order ) { - return this; + case '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; + break; - } + case 'YXZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; - setFromMatrixColumn( m, index ) { + case 'ZXY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; - return this.fromArray( m.elements, index * 4 ); + case '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; + break; - } + case 'YZX': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; - setFromMatrix3Column( m, index ) { + case 'XZY': + 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; + break; - return this.fromArray( m.elements, index * 3 ); + default: + console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); - } + } - equals( v ) { + if ( update !== false ) this._onChangeCallback(); - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + return this; } - fromArray( array, offset = 0 ) { + setFromAxisAngle( axis, angle ) { - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - return this; + // assumes axis is normalized - } + const halfAngle = angle / 2, s = Math.sin( halfAngle ); - toArray( array = [], offset = 0 ) { + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + this._onChangeCallback(); - return array; + return this; } - fromBufferAttribute( attribute, index, offset ) { + setFromRotationMatrix( m ) { - if ( offset !== undefined ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - } + const te = m.elements, - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); + 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 ], - return this; + trace = m11 + m22 + m33; - } + if ( trace > 0 ) { - random() { + const s = 0.5 / Math.sqrt( trace + 1.0 ); - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - return this; + } else if ( m11 > m22 && m11 > m33 ) { - } + const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); -} + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; -Vector3.prototype.isVector3 = true; + } else if ( m22 > m33 ) { -const _vector = /*@__PURE__*/ new Vector3(); -const _quaternion = /*@__PURE__*/ new Quaternion(); + const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); -class Box3 { + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + } else { - this.min = min; - this.max = max; + const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - } + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - set( min, max ) { + } - this.min.copy( min ); - this.max.copy( max ); + this._onChangeCallback(); return this; } - setFromArray( array ) { - - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; - - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; + setFromUnitVectors( vFrom, vTo ) { - for ( let i = 0, l = array.length; i < l; i += 3 ) { + // assumes direction vectors vFrom and vTo are normalized - const x = array[ i ]; - const y = array[ i + 1 ]; - const z = array[ i + 2 ]; + let r = vFrom.dot( vTo ) + 1; - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + if ( r < Number.EPSILON ) { - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + // vFrom and vTo point in opposite directions - } + r = 0; - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - return this; + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; - } + } else { - setFromBufferAttribute( attribute ) { + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; + } - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; + } else { - for ( let i = 0, l = attribute.count; i < l; i ++ ) { + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 - const x = attribute.getX( i ); - const y = attribute.getY( i ); - const z = attribute.getZ( i ); + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + } - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + return this.normalize(); - } + } - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + angleTo( q ) { - return this; + return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) ); } - setFromPoints( points ) { + rotateTowards( q, step ) { - this.makeEmpty(); + const angle = this.angleTo( q ); - for ( let i = 0, il = points.length; i < il; i ++ ) { + if ( angle === 0 ) return this; - this.expandByPoint( points[ i ] ); + const t = Math.min( 1, step / angle ); - } + this.slerp( q, t ); return this; } - setFromCenterAndSize( center, size ) { + identity() { + + return this.set( 0, 0, 0, 1 ); - const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 ); + } - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + invert() { - return this; + // quaternion is assumed to have unit length + + return this.conjugate(); } - setFromObject( object ) { + conjugate() { - this.makeEmpty(); + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; + + this._onChangeCallback(); - return this.expandByObject( object ); + return this; } - clone() { + dot( v ) { - return new this.constructor().copy( this ); + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; } - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); + lengthSq() { - return this; + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; } - makeEmpty() { - - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + length() { - return this; + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); } - isEmpty() { + normalize() { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + let l = this.length(); - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + if ( l === 0 ) { - } + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - getCenter( target ) { + } else { - if ( target === undefined ) { + l = 1 / l; - console.warn( 'THREE.Box3: .getCenter() target is now required' ); - target = new Vector3(); + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; } - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + this._onChangeCallback(); + + return this; } - getSize( target ) { + multiply( q ) { - if ( target === undefined ) { + return this.multiplyQuaternions( this, q ); - console.warn( 'THREE.Box3: .getSize() target is now required' ); - target = new Vector3(); + } - } + premultiply( q ) { - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + return this.multiplyQuaternions( q, this ); } - expandByPoint( point ) { - - this.min.min( point ); - this.max.max( point ); + multiplyQuaternions( a, b ) { - return this; + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - } + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - expandByVector( vector ) { + 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.min.sub( vector ); - this.max.add( vector ); + this._onChangeCallback(); return this; } - expandByScalar( scalar ) { + slerp( qb, t ) { - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - return this; + const x = this._x, y = this._y, z = this._z, w = this._w; - } + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - expandByObject( object ) { + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + if ( cosHalfTheta < 0 ) { - object.updateWorldMatrix( false, false ); + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - const geometry = object.geometry; + cosHalfTheta = - cosHalfTheta; - if ( geometry !== undefined ) { + } else { - if ( geometry.boundingBox === null ) { + this.copy( qb ); - geometry.computeBoundingBox(); + } - } + if ( cosHalfTheta >= 1.0 ) { - _box.copy( geometry.boundingBox ); - _box.applyMatrix4( object.matrixWorld ); + this._w = w; + this._x = x; + this._y = y; + this._z = z; - this.union( _box ); + return this; } - const children = object.children; + const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; - for ( let i = 0, l = children.length; i < l; i ++ ) { + if ( sqrSinHalfTheta <= Number.EPSILON ) { + + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + + this.normalize(); + this._onChangeCallback(); - this.expandByObject( children[ i ] ); + return this; } - return this; + const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); + const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - } + 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 ); - containsPoint( point ) { + this._onChangeCallback(); - return 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 ? false : true; + return this; } - containsBox( box ) { + slerpQuaternions( qa, qb, t ) { - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y && - this.min.z <= box.min.z && box.max.z <= this.max.z; + return this.copy( qa ).slerp( qb, t ); } - getParameter( point, target ) { + random() { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + // Derived from http://planning.cs.uiuc.edu/node198.html + // Note, this source uses w, x, y, z ordering, + // so we swap the order below. - if ( target === undefined ) { + const u1 = Math.random(); + const sqrt1u1 = Math.sqrt( 1 - u1 ); + const sqrtu1 = Math.sqrt( u1 ); - console.warn( 'THREE.Box3: .getParameter() target is now required' ); - target = new Vector3(); + const u2 = 2 * Math.PI * Math.random(); - } + const u3 = 2 * Math.PI * Math.random(); - return target.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.set( + sqrt1u1 * Math.cos( u2 ), + sqrtu1 * Math.sin( u3 ), + sqrtu1 * Math.cos( u3 ), + sqrt1u1 * Math.sin( u2 ), ); } - intersectsBox( box ) { + equals( quaternion ) { - // using 6 splitting planes to rule out intersections. - return 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 ? false : true; + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); } - intersectsSphere( sphere ) { + fromArray( array, offset = 0 ) { - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, _vector$1 ); + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - // If that point is inside the sphere, the AABB and sphere intersect. - return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + this._onChangeCallback(); + + return this; } - intersectsPlane( plane ) { + toArray( array = [], offset = 0 ) { - // 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. + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - let min, max; + return array; - if ( plane.normal.x > 0 ) { + } - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + fromBufferAttribute( attribute, index ) { - } else { + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + return this; - } + } - if ( plane.normal.y > 0 ) { + _onChange( callback ) { - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; + this._onChangeCallback = callback; - } else { + return this; - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; + } - } + _onChangeCallback() {} - if ( plane.normal.z > 0 ) { + *[ Symbol.iterator ]() { - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + yield this._x; + yield this._y; + yield this._z; + yield this._w; - } else { + } - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; +} - } +class Vector3 { - return ( min <= - plane.constant && max >= - plane.constant ); + constructor( x = 0, y = 0, z = 0 ) { + + Vector3.prototype.isVector3 = true; + + this.x = x; + this.y = y; + this.z = z; } - intersectsTriangle( triangle ) { + set( x, y, z ) { - if ( this.isEmpty() ) { + if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) - return false; + this.x = x; + this.y = y; + this.z = z; - } + return this; - // compute box center and extents - this.getCenter( _center ); - _extents.subVectors( this.max, _center ); + } - // translate triangle to aabb origin - _v0.subVectors( triangle.a, _center ); - _v1.subVectors( triangle.b, _center ); - _v2.subVectors( triangle.c, _center ); + setScalar( scalar ) { - // compute edge vectors for triangle - _f0.subVectors( _v1, _v0 ); - _f1.subVectors( _v2, _v1 ); - _f2.subVectors( _v0, _v2 ); + this.x = scalar; + this.y = scalar; + this.z = scalar; - // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb - // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation - // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) - let axes = [ - 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, - _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, - - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 - ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { + return this; - return false; + } - } + setX( x ) { - // test 3 face normals from the aabb - axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { + this.x = x; - return false; + return this; - } + } - // finally testing the face normal of the triangle - // use already existing triangle edge vectors here - _triangleNormal.crossVectors( _f0, _f1 ); - axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + setY( y ) { + + this.y = y; - return satForAxes( axes, _v0, _v1, _v2, _extents ); + return this; } - clampPoint( point, target ) { + setZ( z ) { - if ( target === undefined ) { + this.z = z; - console.warn( 'THREE.Box3: .clampPoint() target is now required' ); - target = new Vector3(); + return this; - } + } - return target.copy( point ).clamp( this.min, this.max ); + setComponent( index, value ) { - } + switch ( index ) { - distanceToPoint( point ) { + 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 ); - const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max ); + } - return clampedPoint.sub( point ).length(); + return this; } - getBoundingSphere( target ) { + getComponent( index ) { - if ( target === undefined ) { + switch ( index ) { - console.error( 'THREE.Box3: .getBoundingSphere() target is now required' ); - //target = new Sphere(); // removed to avoid cyclic dependency + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'index is out of range: ' + index ); } - this.getCenter( target.center ); + } - target.radius = this.getSize( _vector$1 ).length() * 0.5; + clone() { - return target; + return new this.constructor( this.x, this.y, this.z ); } - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); + copy( v ) { - // 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(); + this.x = v.x; + this.y = v.y; + this.z = v.z; return this; } - union( box ) { + add( v ) { - this.min.min( box.min ); - this.max.max( box.max ); + this.x += v.x; + this.y += v.y; + this.z += v.z; return this; } - applyMatrix4( matrix ) { - - // 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 + addScalar( s ) { - this.setFromPoints( _points ); + this.x += s; + this.y += s; + this.z += s; return this; } - translate( offset ) { + addVectors( a, b ) { - this.min.add( offset ); - this.max.add( offset ); + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; return this; } - equals( box ) { + addScaledVector( v, s ) { - return box.min.equals( this.min ) && box.max.equals( this.max ); + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + + return this; } -} + sub( v ) { -Box3.prototype.isBox3 = true; + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; -const _points = [ - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3() -]; + return this; -const _vector$1 = /*@__PURE__*/ new Vector3(); + } -const _box = /*@__PURE__*/ new Box3(); + subScalar( s ) { -// triangle centered vertices + this.x -= s; + this.y -= s; + this.z -= s; -const _v0 = /*@__PURE__*/ new Vector3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _v2 = /*@__PURE__*/ new Vector3(); + return this; -// triangle edge vectors + } -const _f0 = /*@__PURE__*/ new Vector3(); -const _f1 = /*@__PURE__*/ new Vector3(); -const _f2 = /*@__PURE__*/ new Vector3(); + subVectors( a, b ) { -const _center = /*@__PURE__*/ new Vector3(); -const _extents = /*@__PURE__*/ new Vector3(); -const _triangleNormal = /*@__PURE__*/ new Vector3(); -const _testAxis = /*@__PURE__*/ new Vector3(); + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; -function satForAxes( axes, v0, v1, v2, extents ) { + return this; - for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { + } - _testAxis.fromArray( axes, i ); - // project the aabb onto the seperating axis - const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); - // project all 3 vertices of the triangle onto the seperating axis - const p0 = v0.dot( _testAxis ); - const p1 = v1.dot( _testAxis ); - const p2 = v2.dot( _testAxis ); - // actual test, basically see if either of the most extreme of the triangle points intersects r - if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + multiply( v ) { - // points of the projected triangle are outside the projected half-length of the aabb - // the axis is seperating and we can exit - return false; + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - } + return this; } - return true; - -} - -const _box$1 = /*@__PURE__*/ new Box3(); - -class Sphere { + multiplyScalar( scalar ) { - constructor( center = new Vector3(), radius = - 1 ) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - this.center = center; - this.radius = radius; + return this; } - set( center, radius ) { + multiplyVectors( a, b ) { - this.center.copy( center ); - this.radius = radius; + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; return this; } - setFromPoints( points, optionalCenter ) { + applyEuler( euler ) { - const center = this.center; + return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) ); - if ( optionalCenter !== undefined ) { + } - center.copy( optionalCenter ); + applyAxisAngle( axis, angle ) { - } else { + return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) ); - _box$1.setFromPoints( points ).getCenter( center ); + } - } + applyMatrix3( m ) { - let maxRadiusSq = 0; + const x = this.x, y = this.y, z = this.z; + const e = m.elements; - for ( let i = 0, il = points.length; i < il; i ++ ) { + 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; - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + return this; - } + } - this.radius = Math.sqrt( maxRadiusSq ); + applyNormalMatrix( m ) { - return this; + return this.applyMatrix3( m ).normalize(); } - copy( sphere ) { + applyMatrix4( m ) { - this.center.copy( sphere.center ); - this.radius = sphere.radius; + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + + 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; return this; } - isEmpty() { + applyQuaternion( q ) { - return ( this.radius < 0 ); + const x = this.x, y = this.y, z = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; - } + // calculate quat * vector - makeEmpty() { + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = - qx * x - qy * y - qz * z; - this.center.set( 0, 0, 0 ); - this.radius = - 1; + // calculate result * inverse quat + + 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; return this; } - containsPoint( point ) { + project( camera ) { - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); } - distanceToPoint( point ) { + unproject( camera ) { - return ( point.distanceTo( this.center ) - this.radius ); + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); } - intersectsSphere( sphere ) { + transformDirection( m ) { - const radiusSum = this.radius + sphere.radius; + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + + return this.normalize(); } - intersectsBox( box ) { + divide( v ) { - return box.intersectsSphere( this ); + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + + return this; } - intersectsPlane( plane ) { + divideScalar( scalar ) { - return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + return this.multiplyScalar( 1 / scalar ); } - clampPoint( point, target ) { + min( v ) { - const deltaLengthSq = this.center.distanceToSquared( point ); + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); - if ( target === undefined ) { + return this; - console.warn( 'THREE.Sphere: .clampPoint() target is now required' ); - target = new Vector3(); + } - } + max( v ) { - target.copy( point ); + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + return this; - target.sub( this.center ).normalize(); - target.multiplyScalar( this.radius ).add( this.center ); + } - } + clamp( min, max ) { - return target; + // assumes min < max, componentwise - } + 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 ) ); - getBoundingBox( target ) { + return this; - if ( target === undefined ) { + } - console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' ); - target = new Box3(); + clampScalar( minVal, maxVal ) { - } + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - if ( this.isEmpty() ) { + return this; - // Empty sphere produces empty bounding box - target.makeEmpty(); - return target; + } - } + clampLength( min, max ) { - target.set( this.center, this.center ); - target.expandByScalar( this.radius ); + const length = this.length(); - return target; + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); } - applyMatrix4( matrix ) { + floor() { - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); return this; } - translate( offset ) { + ceil() { - this.center.add( offset ); + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); return this; } - equals( sphere ) { + round() { - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + + return this; } - clone() { + roundToZero() { - return new this.constructor().copy( 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 ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + + return this; } -} + negate() { -const _vector$2 = /*@__PURE__*/ new Vector3(); -const _segCenter = /*@__PURE__*/ new Vector3(); -const _segDir = /*@__PURE__*/ new Vector3(); -const _diff = /*@__PURE__*/ new Vector3(); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; -const _edge1 = /*@__PURE__*/ new Vector3(); -const _edge2 = /*@__PURE__*/ new Vector3(); -const _normal = /*@__PURE__*/ new Vector3(); + return this; -class Ray { + } - constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { + dot( v ) { - this.origin = origin; - this.direction = direction; + return this.x * v.x + this.y * v.y + this.z * v.z; } - set( origin, direction ) { + // TODO lengthSquared? - this.origin.copy( origin ); - this.direction.copy( direction ); + lengthSq() { - return this; + return this.x * this.x + this.y * this.y + this.z * this.z; } - copy( ray ) { + length() { - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - return this; + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); } - at( t, target ) { + normalize() { - if ( target === undefined ) { + return this.divideScalar( this.length() || 1 ); - console.warn( 'THREE.Ray: .at() target is now required' ); - target = new Vector3(); + } - } + setLength( length ) { - return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + return this.normalize().multiplyScalar( length ); } - lookAt( v ) { + lerp( v, alpha ) { - this.direction.copy( v ).sub( this.origin ).normalize(); + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; return this; } - recast( t ) { + lerpVectors( v1, v2, alpha ) { - this.origin.copy( this.at( t, _vector$2 ) ); + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; return this; } - closestPointToPoint( point, target ) { + cross( v ) { - if ( target === undefined ) { + return this.crossVectors( this, v ); - console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' ); - target = new Vector3(); + } - } + crossVectors( a, b ) { - target.subVectors( point, this.origin ); + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; - const directionDistance = target.dot( this.direction ); + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - if ( directionDistance < 0 ) { + return this; - return target.copy( this.origin ); + } - } + projectOnVector( v ) { - return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + const denominator = v.lengthSq(); - } + if ( denominator === 0 ) return this.set( 0, 0, 0 ); - distanceToPoint( point ) { + const scalar = v.dot( this ) / denominator; - return Math.sqrt( this.distanceSqToPoint( point ) ); + return this.copy( v ).multiplyScalar( scalar ); } - distanceSqToPoint( point ) { - - const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction ); + projectOnPlane( planeNormal ) { - // point behind the ray + _vector$c.copy( this ).projectOnVector( planeNormal ); - if ( directionDistance < 0 ) { + return this.sub( _vector$c ); - return this.origin.distanceToSquared( point ); + } - } + reflect( normal ) { - _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - return _vector$2.distanceToSquared( point ); + return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); } - 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 ); + angleTo( v ) { - const segExtent = v0.distanceTo( v1 ) * 0.5; - const a01 = - this.direction.dot( _segDir ); - const b0 = _diff.dot( this.direction ); - const b1 = - _diff.dot( _segDir ); - const c = _diff.lengthSq(); - const det = Math.abs( 1 - a01 * a01 ); - let s0, s1, sqrDist, extDet; + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); - if ( det > 0 ) { + if ( denominator === 0 ) return Math.PI / 2; - // The ray and segment are not parallel. + const theta = this.dot( v ) / denominator; - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + // clamp, to handle numerical problems - if ( s0 >= 0 ) { + return Math.acos( clamp( theta, - 1, 1 ) ); - if ( s1 >= - extDet ) { + } - if ( s1 <= extDet ) { + distanceTo( v ) { - // region 0 - // Minimum at interior points of ray and segment. + return Math.sqrt( this.distanceToSquared( v ) ); - const invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + } - } else { + distanceToSquared( v ) { - // region 1 + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + return dx * dx + dy * dy + dz * dz; - } + } - } else { + manhattanDistanceTo( v ) { - // region 5 + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + } - } + setFromSpherical( s ) { - } else { + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); - if ( s1 <= - extDet ) { + } - // region 4 + setFromSphericalCoords( radius, phi, theta ) { - 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; + const sinPhiRadius = Math.sin( phi ) * radius; - } else if ( s1 <= extDet ) { + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); - // region 3 + return this; - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + } - } else { + setFromCylindrical( c ) { - // region 2 + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); - 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; + } - } + setFromCylindricalCoords( radius, theta, y ) { - } + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); - } else { + return this; - // Ray and segment are parallel. + } - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + setFromMatrixPosition( m ) { - } + const e = m.elements; - if ( optionalPointOnRay ) { + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + return this; - } + } - if ( optionalPointOnSegment ) { + setFromMatrixScale( m ) { - optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); + const sx = this.setFromMatrixColumn( m, 0 ).length(); + const sy = this.setFromMatrixColumn( m, 1 ).length(); + const sz = this.setFromMatrixColumn( m, 2 ).length(); - } + this.x = sx; + this.y = sy; + this.z = sz; - return sqrDist; + return this; } - intersectSphere( sphere, target ) { + setFromMatrixColumn( m, index ) { - _vector$2.subVectors( sphere.center, this.origin ); - const tca = _vector$2.dot( this.direction ); - const d2 = _vector$2.dot( _vector$2 ) - tca * tca; - const radius2 = sphere.radius * sphere.radius; + return this.fromArray( m.elements, index * 4 ); - if ( d2 > radius2 ) return null; + } - const thc = Math.sqrt( radius2 - d2 ); + setFromMatrix3Column( m, index ) { - // t0 = first intersect point - entrance on front of sphere - const t0 = tca - thc; + return this.fromArray( m.elements, index * 3 ); - // t1 = second intersect point - exit point on back of sphere - const t1 = tca + thc; + } - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + setFromEuler( e ) { - // 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, target ); + this.x = e._x; + this.y = e._y; + this.z = e._z; - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, target ); + return this; } - intersectsSphere( sphere ) { + equals( v ) { - return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); } - distanceToPlane( plane ) { + fromArray( array, offset = 0 ) { - const denominator = plane.normal.dot( this.direction ); + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - if ( denominator === 0 ) { + return this; - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { - - return 0; + } - } + toArray( array = [], offset = 0 ) { - // Null is preferable to undefined since undefined means.... it is undefined + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - return null; + return array; - } + } - const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + fromBufferAttribute( attribute, index ) { - // Return if the ray never intersects the plane + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); - return t >= 0 ? t : null; + return this; } - intersectPlane( plane, target ) { + random() { - const t = this.distanceToPlane( plane ); + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); - if ( t === null ) { + return this; - return null; + } - } + randomDirection() { - return this.at( t, target ); + // Derived from https://mathworld.wolfram.com/SpherePointPicking.html - } + const u = ( Math.random() - 0.5 ) * 2; + const t = Math.random() * Math.PI * 2; + const f = Math.sqrt( 1 - u ** 2 ); - intersectsPlane( plane ) { + this.x = f * Math.cos( t ); + this.y = f * Math.sin( t ); + this.z = u; - // check if the ray lies on the plane first + return this; - const distToPoint = plane.distanceToPoint( this.origin ); + } - if ( distToPoint === 0 ) { + *[ Symbol.iterator ]() { - return true; + yield this.x; + yield this.y; + yield this.z; - } + } - const denominator = plane.normal.dot( this.direction ); +} - if ( denominator * distToPoint < 0 ) { +const _vector$c = /*@__PURE__*/ new Vector3(); +const _quaternion$4 = /*@__PURE__*/ new Quaternion(); - return true; +class Box3 { - } + constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { - // ray origin is behind the plane (and is pointing behind it) + this.isBox3 = true; - return false; + this.min = min; + this.max = max; } - intersectBox( box, target ) { + set( min, max ) { - let tmin, tmax, tymin, tymax, tzmin, tzmax; + this.min.copy( min ); + this.max.copy( max ); - const invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + return this; - const origin = this.origin; + } - if ( invdirx >= 0 ) { + setFromArray( array ) { - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; - } else { + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + for ( let i = 0, l = array.length; i < l; i += 3 ) { - } + const x = array[ i ]; + const y = array[ i + 1 ]; + const z = array[ i + 2 ]; - if ( invdiry >= 0 ) { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - } else { + } - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - } + return this; - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + } - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + setFromBufferAttribute( attribute ) { - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; - if ( invdirz >= 0 ) { + for ( let i = 0, l = attribute.count; i < l; i ++ ) { - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + const x = attribute.getX( i ); + const y = attribute.getY( i ); + const z = attribute.getZ( i ); - } else { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; } - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + return this; - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + } - //return point closest to the ray (positive side) + setFromPoints( points ) { - if ( tmax < 0 ) return null; + this.makeEmpty(); - return this.at( tmin >= 0 ? tmin : tmax, target ); + for ( let i = 0, il = points.length; i < il; i ++ ) { - } + this.expandByPoint( points[ i ] ); - intersectsBox( box ) { + } - return this.intersectBox( box, _vector$2 ) !== null; + return this; } - intersectTriangle( a, b, c, backfaceCulling, target ) { + setFromCenterAndSize( center, size ) { - // Compute the offset origin, edges, and normal. + const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 ); - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - _edge1.subVectors( b, a ); - _edge2.subVectors( c, a ); - _normal.crossVectors( _edge1, _edge2 ); + return this; - // 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) - let DdN = this.direction.dot( _normal ); - let sign; + } - if ( DdN > 0 ) { + setFromObject( object, precise = false ) { - if ( backfaceCulling ) return null; - sign = 1; + this.makeEmpty(); - } else if ( DdN < 0 ) { + return this.expandByObject( object, precise ); - sign = - 1; - DdN = - DdN; + } - } else { + clone() { - return null; + return new this.constructor().copy( this ); - } + } - _diff.subVectors( this.origin, a ); - const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); + copy( box ) { - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + this.min.copy( box.min ); + this.max.copy( box.max ); - return null; + return this; - } + } - const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); + makeEmpty() { - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - return null; + return this; - } + } - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + isEmpty() { - return null; + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - } + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - // Line intersects triangle, check if ray does. - const QdN = - sign * _diff.dot( _normal ); + } - // t < 0, no intersection - if ( QdN < 0 ) { + getCenter( target ) { - return null; + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - } + } - // Ray intersects triangle. - return this.at( QdN / DdN, target ); + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); } - applyMatrix4( matrix4 ) { + expandByPoint( point ) { - this.origin.applyMatrix4( matrix4 ); - this.direction.transformDirection( matrix4 ); + this.min.min( point ); + this.max.max( point ); return this; } - equals( ray ) { + expandByVector( vector ) { - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + this.min.sub( vector ); + this.max.add( vector ); + + return this; } - clone() { + expandByScalar( scalar ) { - return new this.constructor().copy( this ); + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; } -} + expandByObject( object, precise = false ) { -class Matrix4 { + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - constructor() { + object.updateWorldMatrix( false, false ); - this.elements = [ + const geometry = object.geometry; - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + if ( geometry !== undefined ) { - ]; + if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) { - if ( arguments.length > 0 ) { + const position = geometry.attributes.position; + for ( let i = 0, l = position.count; i < l; i ++ ) { - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld ); + this.expandByPoint( _vector$b ); - } + } - } + } else { - set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + if ( geometry.boundingBox === null ) { - const te = this.elements; + geometry.computeBoundingBox(); - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + } - return this; + _box$3.copy( geometry.boundingBox ); + _box$3.applyMatrix4( object.matrixWorld ); - } + this.union( _box$3 ); - identity() { + } - this.set( + } - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + const children = object.children; - ); + for ( let i = 0, l = children.length; i < l; i ++ ) { + + this.expandByObject( children[ i ], precise ); + + } return this; } - clone() { + containsPoint( point ) { - return new Matrix4().fromArray( this.elements ); + return 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 ? false : true; } - copy( m ) { - - const te = this.elements; - const me = m.elements; - - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; - te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; - te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; - te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + containsBox( box ) { - return this; + return 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; } - copyPosition( m ) { - - const te = this.elements, me = m.elements; + getParameter( point, target ) { - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - return this; + return target.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 ) + ); } - setFromMatrix3( m ) { + intersectsBox( box ) { - const me = m.elements; + // using 6 splitting planes to rule out intersections. + return 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 ? false : true; - this.set( + } - me[ 0 ], me[ 3 ], me[ 6 ], 0, - me[ 1 ], me[ 4 ], me[ 7 ], 0, - me[ 2 ], me[ 5 ], me[ 8 ], 0, - 0, 0, 0, 1 + intersectsSphere( sphere ) { - ); + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$b ); - return this; + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); } - extractBasis( xAxis, yAxis, zAxis ) { + intersectsPlane( plane ) { - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + // 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. - return this; + let min, max; - } + if ( plane.normal.x > 0 ) { - makeBasis( xAxis, yAxis, zAxis ) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - 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 - ); + } else { - return this; + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - } + } - extractRotation( m ) { + if ( plane.normal.y > 0 ) { - // this method does not support reflection matrices + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - const te = this.elements; - const me = m.elements; + } else { - const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length(); - const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length(); - const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length(); + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; - te[ 3 ] = 0; + } - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; - te[ 7 ] = 0; + if ( plane.normal.z > 0 ) { - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; - te[ 11 ] = 0; + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + } else { - return this; + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + + } + + return ( min <= - plane.constant && max >= - plane.constant ); } - makeRotationFromEuler( euler ) { + intersectsTriangle( triangle ) { - if ( ! ( euler && euler.isEuler ) ) { + if ( this.isEmpty() ) { - console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + return false; } - const te = this.elements; + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); - const x = euler.x, y = euler.y, z = euler.z; - const a = Math.cos( x ), b = Math.sin( x ); - const c = Math.cos( y ), d = Math.sin( y ); - const e = Math.cos( z ), f = Math.sin( z ); + // translate triangle to aabb origin + _v0$2.subVectors( triangle.a, _center ); + _v1$7.subVectors( triangle.b, _center ); + _v2$3.subVectors( triangle.c, _center ); - if ( euler.order === 'XYZ' ) { + // compute edge vectors for triangle + _f0.subVectors( _v1$7, _v0$2 ); + _f1.subVectors( _v2$3, _v1$7 ); + _f2.subVectors( _v0$2, _v2$3 ); - const ae = a * e, af = a * f, be = b * e, bf = b * f; + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + let axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) { - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + return false; - 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; + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) { - } else if ( euler.order === 'YXZ' ) { + return false; - const ce = c * e, cf = c * f, de = d * e, df = d * f; + } - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ); - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + } - } else if ( euler.order === 'ZXY' ) { + clampPoint( point, target ) { - const ce = c * e, cf = c * f, de = d * e, df = d * f; + return target.copy( point ).clamp( this.min, this.max ); - 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; + distanceToPoint( point ) { - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max ); - } else if ( euler.order === 'ZYX' ) { + return clampedPoint.sub( point ).length(); - const 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; + getBoundingSphere( target ) { - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + this.getCenter( target.center ); - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + target.radius = this.getSize( _vector$b ).length() * 0.5; - } else if ( euler.order === 'YZX' ) { + return target; - const 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; + intersect( box ) { - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + this.min.max( box.min ); + this.max.min( box.max ); - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + // 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(); - } else if ( euler.order === 'XZY' ) { + return this; - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + } - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + union( box ) { - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + this.min.min( box.min ); + this.max.max( box.max ); - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + return this; - } + } - // bottom row - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + applyMatrix4( matrix ) { - // last column - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + // 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 + + this.setFromPoints( _points ); return this; } - makeRotationFromQuaternion( q ) { + translate( offset ) { - return this.compose( _zero, q, _one ); + this.min.add( offset ); + this.max.add( offset ); + + return this; } - lookAt( eye, target, up ) { + equals( box ) { - const te = this.elements; + return box.min.equals( this.min ) && box.max.equals( this.max ); - _z.subVectors( eye, target ); + } - if ( _z.lengthSq() === 0 ) { +} - // eye and target are in the same position +const _points = [ + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3() +]; - _z.z = 1; +const _vector$b = /*@__PURE__*/ new Vector3(); - } +const _box$3 = /*@__PURE__*/ new Box3(); - _z.normalize(); - _x.crossVectors( up, _z ); +// triangle centered vertices - if ( _x.lengthSq() === 0 ) { +const _v0$2 = /*@__PURE__*/ new Vector3(); +const _v1$7 = /*@__PURE__*/ new Vector3(); +const _v2$3 = /*@__PURE__*/ new Vector3(); - // up and z are parallel +// triangle edge vectors - if ( Math.abs( up.z ) === 1 ) { +const _f0 = /*@__PURE__*/ new Vector3(); +const _f1 = /*@__PURE__*/ new Vector3(); +const _f2 = /*@__PURE__*/ new Vector3(); - _z.x += 0.0001; +const _center = /*@__PURE__*/ new Vector3(); +const _extents = /*@__PURE__*/ new Vector3(); +const _triangleNormal = /*@__PURE__*/ new Vector3(); +const _testAxis = /*@__PURE__*/ new Vector3(); - } else { +function satForAxes( axes, v0, v1, v2, extents ) { - _z.z += 0.0001; + for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { - } + _testAxis.fromArray( axes, i ); + // project the aabb onto the separating axis + const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the separating axis + const p0 = v0.dot( _testAxis ); + const p1 = v1.dot( _testAxis ); + const p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { - _z.normalize(); - _x.crossVectors( up, _z ); + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is separating and we can exit + return false; } - _x.normalize(); - _y.crossVectors( _z, _x ); + } - 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 true; - return this; +} - } +const _box$2 = /*@__PURE__*/ new Box3(); +const _v1$6 = /*@__PURE__*/ new Vector3(); +const _toFarthestPoint = /*@__PURE__*/ new Vector3(); +const _toPoint = /*@__PURE__*/ new Vector3(); - multiply( m, n ) { +class Sphere { - if ( n !== undefined ) { + constructor( center = new Vector3(), radius = - 1 ) { - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + this.center = center; + this.radius = radius; - } + } - return this.multiplyMatrices( this, m ); + set( center, radius ) { + + this.center.copy( center ); + this.radius = radius; + + return this; } - premultiply( m ) { + setFromPoints( points, optionalCenter ) { - return this.multiplyMatrices( m, this ); + const center = this.center; - } + if ( optionalCenter !== undefined ) { - multiplyMatrices( a, b ) { + center.copy( optionalCenter ); - const ae = a.elements; - const be = b.elements; - const te = this.elements; + } else { - const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + _box$2.setFromPoints( points ).getCenter( center ); - const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + } - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + let maxRadiusSq = 0; - 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; + for ( let i = 0, il = points.length; i < il; i ++ ) { - 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; + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + } + + this.radius = Math.sqrt( maxRadiusSq ); return this; } - multiplyScalar( s ) { - - const te = this.elements; + copy( sphere ) { - 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; + this.center.copy( sphere.center ); + this.radius = sphere.radius; return this; } - determinant() { + isEmpty() { - const te = this.elements; + return ( this.radius < 0 ); - const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + } - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + makeEmpty() { - 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 - ) + this.center.set( 0, 0, 0 ); + this.radius = - 1; - ); + return this; } - transpose() { + containsPoint( point ) { - const te = this.elements; - let tmp; + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - 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; + distanceToPoint( point ) { - return this; + return ( point.distanceTo( this.center ) - this.radius ); } - setPosition( x, y, z ) { + intersectsSphere( sphere ) { - const te = this.elements; + const radiusSum = this.radius + sphere.radius; - if ( x.isVector3 ) { + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - te[ 12 ] = x.x; - te[ 13 ] = x.y; - te[ 14 ] = x.z; + } - } else { + intersectsBox( box ) { - te[ 12 ] = x; - te[ 13 ] = y; - te[ 14 ] = z; + return box.intersectsSphere( this ); - } + } - return this; + intersectsPlane( plane ) { + + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; } - invert() { + clampPoint( point, target ) { - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - const te = this.elements, + const deltaLengthSq = this.center.distanceToSquared( point ); - n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], - n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], - n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], - n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], + target.copy( point ); - 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; + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); - if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + } - const detInv = 1 / det; + return target; - 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; + getBoundingBox( target ) { - 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; + if ( this.isEmpty() ) { - 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; + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; - return this; + } - } + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); - scale( v ) { + return target; - const te = this.elements; - const x = v.x, y = v.y, z = v.z; + } - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + applyMatrix4( matrix ) { + + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); return this; } - getMaxScaleOnAxis() { - - const te = this.elements; + translate( offset ) { - const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + this.center.add( offset ); - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + return this; } - makeTranslation( x, y, z ) { - - this.set( - - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + expandByPoint( point ) { - ); + // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671 - return this; + _toPoint.subVectors( point, this.center ); - } + const lengthSq = _toPoint.lengthSq(); - makeRotationX( theta ) { + if ( lengthSq > ( this.radius * this.radius ) ) { - const c = Math.cos( theta ), s = Math.sin( theta ); + const length = Math.sqrt( lengthSq ); + const missingRadiusHalf = ( length - this.radius ) * 0.5; - this.set( + // Nudge this sphere towards the target point. Add half the missing distance to radius, + // and the other half to position. This gives a tighter enclosure, instead of if + // the whole missing distance were just added to radius. - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) ); + this.radius += missingRadiusHalf; - ); + } return this; } - makeRotationY( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( + union( sphere ) { - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769 - ); + // To enclose another sphere into this sphere, we only need to enclose two points: + // 1) Enclose the farthest point on the other sphere into this sphere. + // 2) Enclose the opposite point of the farthest point into this sphere. - return this; + if ( this.center.equals( sphere.center ) === true ) { - } + _toFarthestPoint.set( 0, 0, 1 ).multiplyScalar( sphere.radius ); - makeRotationZ( theta ) { - const c = Math.cos( theta ), s = Math.sin( theta ); + } else { - this.set( + _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius ); - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + } - ); + this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) ); + this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) ); return this; } - makeRotationAxis( axis, angle ) { - - // Based on http://www.gamedev.net/reference/articles/article1199.asp - - const c = Math.cos( angle ); - const s = Math.sin( angle ); - const t = 1 - c; - const x = axis.x, y = axis.y, z = axis.z; - const tx = t * x, ty = t * y; + equals( sphere ) { - this.set( + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - 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 + } - ); + clone() { - return this; + return new this.constructor().copy( this ); } - makeScale( x, y, z ) { - - this.set( +} - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 +const _vector$a = /*@__PURE__*/ new Vector3(); +const _segCenter = /*@__PURE__*/ new Vector3(); +const _segDir = /*@__PURE__*/ new Vector3(); +const _diff = /*@__PURE__*/ new Vector3(); - ); +const _edge1 = /*@__PURE__*/ new Vector3(); +const _edge2 = /*@__PURE__*/ new Vector3(); +const _normal$1 = /*@__PURE__*/ new Vector3(); - return this; +class Ray { - } + constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { - makeShear( x, y, z ) { + this.origin = origin; + this.direction = direction; - this.set( + } - 1, y, z, 0, - x, 1, z, 0, - x, y, 1, 0, - 0, 0, 0, 1 + set( origin, direction ) { - ); + this.origin.copy( origin ); + this.direction.copy( direction ); return this; } - compose( position, quaternion, scale ) { + copy( ray ) { - const te = this.elements; + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; - const x2 = x + x, y2 = y + y, z2 = z + z; - const xx = x * x2, xy = x * y2, xz = x * z2; - const yy = y * y2, yz = y * z2, zz = z * z2; - const wx = w * x2, wy = w * y2, wz = w * z2; + return this; - const sx = scale.x, sy = scale.y, sz = scale.z; + } - te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; - te[ 1 ] = ( xy + wz ) * sx; - te[ 2 ] = ( xz - wy ) * sx; - te[ 3 ] = 0; + at( t, target ) { - te[ 4 ] = ( xy - wz ) * sy; - te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; - te[ 6 ] = ( yz + wx ) * sy; - te[ 7 ] = 0; + return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - te[ 8 ] = ( xz + wy ) * sz; - te[ 9 ] = ( yz - wx ) * sz; - te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; - te[ 11 ] = 0; + } - te[ 12 ] = position.x; - te[ 13 ] = position.y; - te[ 14 ] = position.z; - te[ 15 ] = 1; + lookAt( v ) { + + this.direction.copy( v ).sub( this.origin ).normalize(); return this; } - decompose( position, quaternion, scale ) { + recast( t ) { - const te = this.elements; + this.origin.copy( this.at( t, _vector$a ) ); - let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + return this; - // if determine is negative, we need to invert one scale - const det = this.determinant(); - if ( det < 0 ) sx = - sx; + } - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + closestPointToPoint( point, target ) { - // scale the rotation part - _m1.copy( this ); + target.subVectors( point, this.origin ); - const invSX = 1 / sx; - const invSY = 1 / sy; - const invSZ = 1 / sz; + const directionDistance = target.dot( this.direction ); - _m1.elements[ 0 ] *= invSX; - _m1.elements[ 1 ] *= invSX; - _m1.elements[ 2 ] *= invSX; + if ( directionDistance < 0 ) { - _m1.elements[ 4 ] *= invSY; - _m1.elements[ 5 ] *= invSY; - _m1.elements[ 6 ] *= invSY; + return target.copy( this.origin ); - _m1.elements[ 8 ] *= invSZ; - _m1.elements[ 9 ] *= invSZ; - _m1.elements[ 10 ] *= invSZ; + } - quaternion.setFromRotationMatrix( _m1 ); + return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - scale.x = sx; - scale.y = sy; - scale.z = sz; + } - return this; + distanceToPoint( point ) { + + return Math.sqrt( this.distanceSqToPoint( point ) ); } - makePerspective( left, right, top, bottom, near, far ) { + distanceSqToPoint( point ) { - if ( far === undefined ) { + const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction ); - console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); + // point behind the ray - } + if ( directionDistance < 0 ) { - const te = this.elements; - const x = 2 * near / ( right - left ); - const y = 2 * near / ( top - bottom ); + return this.origin.distanceToSquared( point ); - const a = ( right + left ) / ( right - left ); - const b = ( top + bottom ) / ( top - bottom ); - const c = - ( far + near ) / ( far - near ); - const 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; + _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - return this; + return _vector$a.distanceToSquared( point ); } - makeOrthographic( left, right, top, bottom, near, far ) { - - const te = this.elements; - const w = 1.0 / ( right - left ); - const h = 1.0 / ( top - bottom ); - const p = 1.0 / ( far - near ); + distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - const x = ( right + left ) * w; - const y = ( top + bottom ) * h; - const z = ( far + near ) * p; - - 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; - - return this; + // from https://github.com/pmjoniak/GeometricTools/blob/master/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 ); - equals( matrix ) { + const segExtent = v0.distanceTo( v1 ) * 0.5; + const a01 = - this.direction.dot( _segDir ); + const b0 = _diff.dot( this.direction ); + const b1 = - _diff.dot( _segDir ); + const c = _diff.lengthSq(); + const det = Math.abs( 1 - a01 * a01 ); + let s0, s1, sqrDist, extDet; - const te = this.elements; - const me = matrix.elements; + if ( det > 0 ) { - for ( let i = 0; i < 16; i ++ ) { + // The ray and segment are not parallel. - if ( te[ i ] !== me[ i ] ) return false; + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - } + if ( s0 >= 0 ) { - return true; + if ( s1 >= - extDet ) { - } + if ( s1 <= extDet ) { - fromArray( array, offset = 0 ) { + // region 0 + // Minimum at interior points of ray and segment. - for ( let i = 0; i < 16; i ++ ) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - this.elements[ i ] = array[ i + offset ]; + } else { - } + // region 1 - return this; + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } + } - toArray( array = [], offset = 0 ) { + } else { - const te = this.elements; + // region 5 - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + } - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + } else { - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + if ( s1 <= - extDet ) { - return array; + // region 4 - } + 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; -} + } else if ( s1 <= extDet ) { -Matrix4.prototype.isMatrix4 = true; + // region 3 -const _v1$1 = /*@__PURE__*/ new Vector3(); -const _m1 = /*@__PURE__*/ new Matrix4(); -const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); -const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); -const _x = /*@__PURE__*/ new Vector3(); -const _y = /*@__PURE__*/ new Vector3(); -const _z = /*@__PURE__*/ new Vector3(); + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; -const _matrix = /*@__PURE__*/ new Matrix4(); -const _quaternion$1 = /*@__PURE__*/ new Quaternion(); + } else { -class Euler { + // region 2 - constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { + 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._x = x; - this._y = y; - this._z = z; - this._order = order; + } - } + } - get x() { + } else { - return this._x; + // Ray and segment are parallel. - } + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - set x( value ) { + } - this._x = value; - this._onChangeCallback(); + if ( optionalPointOnRay ) { - } + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - get y() { + } - return this._y; + if ( optionalPointOnSegment ) { - } + optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); - set y( value ) { + } - this._y = value; - this._onChangeCallback(); + return sqrDist; } - get z() { + intersectSphere( sphere, target ) { - return this._z; + _vector$a.subVectors( sphere.center, this.origin ); + const tca = _vector$a.dot( this.direction ); + const d2 = _vector$a.dot( _vector$a ) - tca * tca; + const radius2 = sphere.radius * sphere.radius; - } + if ( d2 > radius2 ) return null; - set z( value ) { + const thc = Math.sqrt( radius2 - d2 ); - this._z = value; - this._onChangeCallback(); + // t0 = first intersect point - entrance on front of sphere + const t0 = tca - thc; - } + // t1 = second intersect point - exit point on back of sphere + const t1 = tca + thc; - get order() { + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - return this._order; + // 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, target ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); } - set order( value ) { + intersectsSphere( sphere ) { - this._order = value; - this._onChangeCallback(); + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); } - set( x, y, z, order ) { + distanceToPlane( plane ) { - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + const denominator = plane.normal.dot( this.direction ); - this._onChangeCallback(); + if ( denominator === 0 ) { - return this; + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - } + return 0; - clone() { + } - return new this.constructor( this._x, this._y, this._z, this._order ); + // Null is preferable to undefined since undefined means.... it is undefined - } + return null; - copy( euler ) { + } - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - this._onChangeCallback(); + // Return if the ray never intersects the plane - return this; + return t >= 0 ? t : null; } - setFromRotationMatrix( m, order, update ) { - - const clamp = MathUtils.clamp; - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - const te = m.elements; - const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + intersectPlane( plane, target ) { - order = order || this._order; + const t = this.distanceToPlane( plane ); - switch ( order ) { + if ( t === null ) { - case 'XYZ': + return null; - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + } - if ( Math.abs( m13 ) < 0.9999999 ) { + return this.at( t, target ); - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + } - } else { + intersectsPlane( plane ) { - this._x = Math.atan2( m32, m22 ); - this._z = 0; + // check if the ray lies on the plane first - } + const distToPoint = plane.distanceToPoint( this.origin ); - break; + if ( distToPoint === 0 ) { - case 'YXZ': + return true; - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + } - if ( Math.abs( m23 ) < 0.9999999 ) { + const denominator = plane.normal.dot( this.direction ); - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + if ( denominator * distToPoint < 0 ) { - } else { + return true; - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + } - } + // ray origin is behind the plane (and is pointing behind it) - break; + return false; - case 'ZXY': + } - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + intersectBox( box, target ) { - if ( Math.abs( m32 ) < 0.9999999 ) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + const invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - } else { + const origin = this.origin; - this._y = 0; - this._z = Math.atan2( m21, m11 ); + if ( invdirx >= 0 ) { - } + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - break; + } else { - case 'ZYX': + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + } - if ( Math.abs( m31 ) < 0.9999999 ) { + if ( invdiry >= 0 ) { - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - } else { + } else { - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - } + } - break; + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - case 'YZX': + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - if ( Math.abs( m21 ) < 0.9999999 ) { + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + if ( invdirz >= 0 ) { - } else { + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - this._x = 0; - this._y = Math.atan2( m13, m33 ); + } else { - } + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - break; + } - case 'XZY': + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - if ( Math.abs( m12 ) < 0.9999999 ) { + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + //return point closest to the ray (positive side) - } else { + if ( tmax < 0 ) return null; - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + return this.at( tmin >= 0 ? tmin : tmax, target ); - } + } - break; + intersectsBox( box ) { - default: + return this.intersectBox( box, _vector$a ) !== null; - console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); + } - } + intersectTriangle( a, b, c, backfaceCulling, target ) { - this._order = order; + // Compute the offset origin, edges, and normal. - if ( update !== false ) this._onChangeCallback(); + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - return this; + _edge1.subVectors( b, a ); + _edge2.subVectors( c, a ); + _normal$1.crossVectors( _edge1, _edge2 ); - } + // 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) + let DdN = this.direction.dot( _normal$1 ); + let sign; - setFromQuaternion( q, order, update ) { + if ( DdN > 0 ) { - _matrix.makeRotationFromQuaternion( q ); + if ( backfaceCulling ) return null; + sign = 1; - return this.setFromRotationMatrix( _matrix, order, update ); + } else if ( DdN < 0 ) { - } + sign = - 1; + DdN = - DdN; - setFromVector3( v, order ) { + } else { - return this.set( v.x, v.y, v.z, order || this._order ); + return null; - } + } - reorder( newOrder ) { + _diff.subVectors( this.origin, a ); + const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); - // WARNING: this discards revolution information -bhouston + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - _quaternion$1.setFromEuler( this ); + return null; - return this.setFromQuaternion( _quaternion$1, newOrder ); + } - } + const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); - equals( euler ) { + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + return null; - } + } - fromArray( array ) { + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + return null; - this._onChangeCallback(); + } - return this; + // Line intersects triangle, check if ray does. + const QdN = - sign * _diff.dot( _normal$1 ); - } + // t < 0, no intersection + if ( QdN < 0 ) { - toArray( array = [], offset = 0 ) { + return null; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + } - return array; + // Ray intersects triangle. + return this.at( QdN / DdN, target ); } - toVector3( optionalResult ) { + applyMatrix4( matrix4 ) { - if ( optionalResult ) { + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); - return optionalResult.set( this._x, this._y, this._z ); + return this; - } else { + } - return new Vector3( this._x, this._y, this._z ); + equals( ray ) { - } + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); } - _onChange( callback ) { - - this._onChangeCallback = callback; + clone() { - return this; + return new this.constructor().copy( this ); } - _onChangeCallback() {} - } -Euler.prototype.isEuler = true; - -Euler.DefaultOrder = 'XYZ'; -Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - -class Layers { +class Matrix4 { constructor() { - this.mask = 1 | 0; + Matrix4.prototype.isMatrix4 = true; - } + this.elements = [ - set( channel ) { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - this.mask = 1 << channel | 0; + ]; } - enable( channel ) { - - this.mask |= 1 << channel | 0; + set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - } + const te = this.elements; - enableAll() { + 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; - this.mask = 0xffffffff | 0; + return this; } - toggle( channel ) { + identity() { - this.mask ^= 1 << channel | 0; + this.set( - } + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - disable( channel ) { + ); - this.mask &= ~ ( 1 << channel | 0 ); + return this; } - disableAll() { + clone() { - this.mask = 0; + return new Matrix4().fromArray( this.elements ); } - test( layers ) { - - return ( this.mask & layers.mask ) !== 0; - - } + copy( m ) { -} + const te = this.elements; + const me = m.elements; -let _object3DId = 0; + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; -const _v1$2 = new Vector3(); -const _q1 = new Quaternion(); -const _m1$1 = new Matrix4(); -const _target = new Vector3(); + return this; -const _position = new Vector3(); -const _scale = new Vector3(); -const _quaternion$2 = new Quaternion(); + } -const _xAxis = new Vector3( 1, 0, 0 ); -const _yAxis = new Vector3( 0, 1, 0 ); -const _zAxis = new Vector3( 0, 0, 1 ); + copyPosition( m ) { -const _addedEvent = { type: 'added' }; -const _removedEvent = { type: 'removed' }; + const te = this.elements, me = m.elements; -function Object3D() { + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - Object.defineProperty( this, 'id', { value: _object3DId ++ } ); + return this; - this.uuid = MathUtils.generateUUID(); + } - this.name = ''; - this.type = 'Object3D'; + setFromMatrix3( m ) { - this.parent = null; - this.children = []; + const me = m.elements; - this.up = Object3D.DefaultUp.clone(); + this.set( - const position = new Vector3(); - const rotation = new Euler(); - const quaternion = new Quaternion(); - const scale = new Vector3( 1, 1, 1 ); + me[ 0 ], me[ 3 ], me[ 6 ], 0, + me[ 1 ], me[ 4 ], me[ 7 ], 0, + me[ 2 ], me[ 5 ], me[ 8 ], 0, + 0, 0, 0, 1 - function onRotationChange() { + ); - quaternion.setFromEuler( rotation, false ); + return this; } - function onQuaternionChange() { + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - rotation.setFromQuaternion( quaternion, undefined, false ); + return this; } - rotation._onChange( onRotationChange ); - quaternion._onChange( onQuaternionChange ); + makeBasis( xAxis, yAxis, zAxis ) { - Object.defineProperties( this, { - position: { - configurable: true, - enumerable: true, - value: position - }, - rotation: { - configurable: true, - enumerable: true, - value: rotation - }, - quaternion: { - configurable: true, - enumerable: true, - value: quaternion - }, - scale: { - configurable: true, - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new Matrix4() - }, - normalMatrix: { - value: new Matrix3() - } - } ); - - this.matrix = new Matrix4(); - this.matrixWorld = new Matrix4(); - - this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; - - this.layers = new Layers(); - this.visible = true; + 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 + ); - this.castShadow = false; - this.receiveShadow = false; + return this; - this.frustumCulled = true; - this.renderOrder = 0; + } - this.animations = []; + extractRotation( m ) { - this.userData = {}; + // this method does not support reflection matrices -} + const te = this.elements; + const me = m.elements; -Object3D.DefaultUp = new Vector3( 0, 1, 0 ); -Object3D.DefaultMatrixAutoUpdate = true; + const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length(); -Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; - constructor: Object3D, + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; - isObject3D: true, + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; - onBeforeRender: function () {}, - onAfterRender: function () {}, + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - applyMatrix4: function ( matrix ) { + return this; - if ( this.matrixAutoUpdate ) this.updateMatrix(); + } - this.matrix.premultiply( matrix ); + makeRotationFromEuler( euler ) { - this.matrix.decompose( this.position, this.quaternion, this.scale ); + const te = this.elements; - }, + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos( x ), b = Math.sin( x ); + const c = Math.cos( y ), d = Math.sin( y ); + const e = Math.cos( z ), f = Math.sin( z ); - applyQuaternion: function ( q ) { + if ( euler.order === 'XYZ' ) { - this.quaternion.premultiply( q ); + const ae = a * e, af = a * f, be = b * e, bf = b * f; - return this; + 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; - setRotationFromAxisAngle: function ( axis, angle ) { + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - // assumes axis is normalized + } else if ( euler.order === 'YXZ' ) { - this.quaternion.setFromAxisAngle( axis, angle ); + const ce = c * e, cf = c * f, de = d * e, df = d * f; - }, + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - setRotationFromEuler: function ( euler ) { + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - this.quaternion.setFromEuler( euler, true ); + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - }, + } else if ( euler.order === 'ZXY' ) { - setRotationFromMatrix: function ( m ) { + const ce = c * e, cf = c * f, de = d * e, df = d * f; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - this.quaternion.setFromRotationMatrix( m ); + 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; - setRotationFromQuaternion: function ( q ) { + } else if ( euler.order === 'ZYX' ) { - // assumes q is normalized + const ae = a * e, af = a * f, be = b * e, bf = b * f; - this.quaternion.copy( q ); + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - }, + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - rotateOnAxis: function ( axis, angle ) { + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - // rotate object on axis in object space - // axis is assumed to be normalized + } else if ( euler.order === 'YZX' ) { - _q1.setFromAxisAngle( axis, angle ); + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - this.quaternion.multiply( _q1 ); + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - return this; + 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; - rotateOnWorldAxis: function ( axis, angle ) { + } else if ( euler.order === 'XZY' ) { - // rotate object on axis in world space - // axis is assumed to be normalized - // method assumes no rotated parent + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - _q1.setFromAxisAngle( axis, angle ); + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - this.quaternion.premultiply( _q1 ); + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - return this; + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - }, + } - rotateX: function ( angle ) { + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - return this.rotateOnAxis( _xAxis, angle ); + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - }, + return this; - rotateY: function ( angle ) { + } - return this.rotateOnAxis( _yAxis, angle ); + makeRotationFromQuaternion( q ) { - }, + return this.compose( _zero, q, _one ); - rotateZ: function ( angle ) { + } - return this.rotateOnAxis( _zAxis, angle ); + lookAt( eye, target, up ) { - }, + const te = this.elements; - translateOnAxis: function ( axis, distance ) { + _z.subVectors( eye, target ); - // translate object by distance along axis in object space - // axis is assumed to be normalized + if ( _z.lengthSq() === 0 ) { - _v1$2.copy( axis ).applyQuaternion( this.quaternion ); + // eye and target are in the same position - this.position.add( _v1$2.multiplyScalar( distance ) ); + _z.z = 1; - return this; + } - }, + _z.normalize(); + _x.crossVectors( up, _z ); - translateX: function ( distance ) { + if ( _x.lengthSq() === 0 ) { - return this.translateOnAxis( _xAxis, distance ); + // up and z are parallel - }, + if ( Math.abs( up.z ) === 1 ) { - translateY: function ( distance ) { + _z.x += 0.0001; - return this.translateOnAxis( _yAxis, distance ); + } else { - }, + _z.z += 0.0001; - translateZ: function ( distance ) { + } - return this.translateOnAxis( _zAxis, distance ); + _z.normalize(); + _x.crossVectors( up, _z ); - }, + } - localToWorld: function ( vector ) { + _x.normalize(); + _y.crossVectors( _z, _x ); - return vector.applyMatrix4( this.matrixWorld ); + 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; - worldToLocal: function ( vector ) { + } - return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + multiply( m ) { - }, + return this.multiplyMatrices( this, m ); - lookAt: function ( x, y, z ) { + } - // This method does not support objects having non-uniformly-scaled parent(s) + premultiply( m ) { - if ( x.isVector3 ) { + return this.multiplyMatrices( m, this ); - _target.copy( x ); + } - } else { + multiplyMatrices( a, b ) { - _target.set( x, y, z ); + const ae = a.elements; + const be = b.elements; + const te = this.elements; - } + const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - const parent = this.parent; + const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - this.updateWorldMatrix( true, 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; - _position.setFromMatrixPosition( this.matrixWorld ); + 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; - if ( this.isCamera || this.isLight ) { + 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; - _m1$1.lookAt( _position, _target, this.up ); + 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; - } else { + return this; - _m1$1.lookAt( _target, _position, this.up ); + } - } + multiplyScalar( s ) { - this.quaternion.setFromRotationMatrix( _m1$1 ); + const te = this.elements; - if ( parent ) { + 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; - _m1$1.extractRotation( parent.matrixWorld ); - _q1.setFromRotationMatrix( _m1$1 ); - this.quaternion.premultiply( _q1.invert() ); + return this; - } + } - }, + determinant() { - add: function ( object ) { + const te = this.elements; - if ( arguments.length > 1 ) { + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - for ( let i = 0; i < arguments.length; i ++ ) { + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - this.add( arguments[ i ] ); + 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 + ) - } + ); - return this; + } - } + transpose() { - if ( object === this ) { + const te = this.elements; + let tmp; - console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); - return this; + 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; - if ( object && object.isObject3D ) { + return this; - if ( object.parent !== null ) { + } - object.parent.remove( object ); + setPosition( x, y, z ) { - } + const te = this.elements; - object.parent = this; - this.children.push( object ); + if ( x.isVector3 ) { - object.dispatchEvent( _addedEvent ); + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; } else { - console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; } return this; - }, - - remove: function ( object ) { + } - if ( arguments.length > 1 ) { + invert() { - for ( let i = 0; i < arguments.length; i ++ ) { + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + const te = this.elements, - this.remove( arguments[ i ] ); + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], + n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], + n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], + n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], - } + 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; - return this; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - } + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - const index = this.children.indexOf( object ); + const detInv = 1 / det; - if ( index !== - 1 ) { + 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; - object.parent = null; - this.children.splice( index, 1 ); + 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; - object.dispatchEvent( _removedEvent ); + 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; - } + 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; - }, + } - clear: function () { + scale( v ) { - for ( let i = 0; i < this.children.length; i ++ ) { + const te = this.elements; + const x = v.x, y = v.y, z = v.z; - const object = this.children[ i ]; + 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; - object.parent = null; + return this; - object.dispatchEvent( _removedEvent ); + } - } + getMaxScaleOnAxis() { - this.children.length = 0; + const te = this.elements; - return this; + const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - }, + } - attach: function ( object ) { + makeTranslation( x, y, z ) { - // adds object as a child of this, while maintaining the object's world transform + this.set( - this.updateWorldMatrix( true, false ); + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - _m1$1.copy( this.matrixWorld ).invert(); + ); - if ( object.parent !== null ) { + return this; - object.parent.updateWorldMatrix( true, false ); + } - _m1$1.multiply( object.parent.matrixWorld ); + makeRotationX( theta ) { - } + const c = Math.cos( theta ), s = Math.sin( theta ); - object.applyMatrix4( _m1$1 ); + this.set( - this.add( object ); + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - object.updateWorldMatrix( false, true ); + ); return this; - }, + } - getObjectById: function ( id ) { + makeRotationY( theta ) { - return this.getObjectByProperty( 'id', id ); + const c = Math.cos( theta ), s = Math.sin( theta ); - }, + this.set( - getObjectByName: function ( name ) { + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - return this.getObjectByProperty( 'name', name ); + ); - }, + return this; - getObjectByProperty: function ( name, value ) { + } - if ( this[ name ] === value ) return this; + makeRotationZ( theta ) { - for ( let i = 0, l = this.children.length; i < l; i ++ ) { + const c = Math.cos( theta ), s = Math.sin( theta ); - const child = this.children[ i ]; - const object = child.getObjectByProperty( name, value ); + this.set( - if ( object !== undefined ) { + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - return object; + ); - } + return this; - } + } - return undefined; + makeRotationAxis( axis, angle ) { - }, + // Based on http://www.gamedev.net/reference/articles/article1199.asp - getWorldPosition: function ( target ) { + const c = Math.cos( angle ); + const s = Math.sin( angle ); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; - if ( target === undefined ) { + this.set( - console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' ); - target = new Vector3(); + 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 - } + ); - this.updateWorldMatrix( true, false ); + return this; - return target.setFromMatrixPosition( this.matrixWorld ); + } - }, + makeScale( x, y, z ) { - getWorldQuaternion: function ( target ) { + this.set( - if ( target === undefined ) { + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' ); - target = new Quaternion(); + ); - } + return this; - this.updateWorldMatrix( true, false ); + } - this.matrixWorld.decompose( _position, target, _scale ); + makeShear( xy, xz, yx, yz, zx, zy ) { - return target; + this.set( - }, + 1, yx, zx, 0, + xy, 1, zy, 0, + xz, yz, 1, 0, + 0, 0, 0, 1 - getWorldScale: function ( target ) { + ); - if ( target === undefined ) { + return this; - console.warn( 'THREE.Object3D: .getWorldScale() target is now required' ); - target = new Vector3(); + } - } + compose( position, quaternion, scale ) { - this.updateWorldMatrix( true, false ); + const te = this.elements; - this.matrixWorld.decompose( _position, _quaternion$2, target ); + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; - return target; + const sx = scale.x, sy = scale.y, sz = scale.z; - }, + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; - getWorldDirection: function ( target ) { + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; - if ( target === undefined ) { + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; - console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' ); - target = new Vector3(); + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; - } + return this; - this.updateWorldMatrix( true, false ); + } - const e = this.matrixWorld.elements; + decompose( position, quaternion, scale ) { - return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + const te = this.elements; - }, + let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - raycast: function () {}, + // if determine is negative, we need to invert one scale + const det = this.determinant(); + if ( det < 0 ) sx = - sx; - traverse: function ( callback ) { + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - callback( this ); + // scale the rotation part + _m1$2.copy( this ); - const children = this.children; + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; - for ( let i = 0, l = children.length; i < l; i ++ ) { + _m1$2.elements[ 0 ] *= invSX; + _m1$2.elements[ 1 ] *= invSX; + _m1$2.elements[ 2 ] *= invSX; - children[ i ].traverse( callback ); + _m1$2.elements[ 4 ] *= invSY; + _m1$2.elements[ 5 ] *= invSY; + _m1$2.elements[ 6 ] *= invSY; - } + _m1$2.elements[ 8 ] *= invSZ; + _m1$2.elements[ 9 ] *= invSZ; + _m1$2.elements[ 10 ] *= invSZ; - }, + quaternion.setFromRotationMatrix( _m1$2 ); - traverseVisible: function ( callback ) { + scale.x = sx; + scale.y = sy; + scale.z = sz; - if ( this.visible === false ) return; + return this; - callback( this ); + } - const children = this.children; + makePerspective( left, right, top, bottom, near, far ) { - for ( let i = 0, l = children.length; i < l; i ++ ) { + const te = this.elements; + const x = 2 * near / ( right - left ); + const y = 2 * near / ( top - bottom ); - children[ i ].traverseVisible( callback ); + const a = ( right + left ) / ( right - left ); + const b = ( top + bottom ) / ( top - bottom ); + const c = - ( far + near ) / ( far - near ); + const 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; - }, + return this; - traverseAncestors: function ( callback ) { + } - const parent = this.parent; + makeOrthographic( left, right, top, bottom, near, far ) { - if ( parent !== null ) { + const te = this.elements; + const w = 1.0 / ( right - left ); + const h = 1.0 / ( top - bottom ); + const p = 1.0 / ( far - near ); - callback( parent ); + const x = ( right + left ) * w; + const y = ( top + bottom ) * h; + const z = ( far + near ) * p; - parent.traverseAncestors( callback ); + 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; - } + return this; - }, + } - updateMatrix: function () { + equals( matrix ) { - this.matrix.compose( this.position, this.quaternion, this.scale ); + const te = this.elements; + const me = matrix.elements; - this.matrixWorldNeedsUpdate = true; + for ( let i = 0; i < 16; i ++ ) { - }, + if ( te[ i ] !== me[ i ] ) return false; - updateMatrixWorld: function ( force ) { + } - if ( this.matrixAutoUpdate ) this.updateMatrix(); + return true; - if ( this.matrixWorldNeedsUpdate || force ) { + } - if ( this.parent === null ) { + fromArray( array, offset = 0 ) { - this.matrixWorld.copy( this.matrix ); + for ( let i = 0; i < 16; i ++ ) { - } else { + this.elements[ i ] = array[ i + offset ]; - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + } - } + return this; - this.matrixWorldNeedsUpdate = false; + } - force = true; + toArray( array = [], offset = 0 ) { - } + const te = this.elements; - // update children + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - const children = this.children; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - for ( let i = 0, l = children.length; i < l; i ++ ) { + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - children[ i ].updateMatrixWorld( force ); + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - } + return array; - }, + } - updateWorldMatrix: function ( updateParents, updateChildren ) { +} - const parent = this.parent; +const _v1$5 = /*@__PURE__*/ new Vector3(); +const _m1$2 = /*@__PURE__*/ new Matrix4(); +const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); +const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); +const _x = /*@__PURE__*/ new Vector3(); +const _y = /*@__PURE__*/ new Vector3(); +const _z = /*@__PURE__*/ new Vector3(); - if ( updateParents === true && parent !== null ) { +const _matrix$1 = /*@__PURE__*/ new Matrix4(); +const _quaternion$3 = /*@__PURE__*/ new Quaternion(); - parent.updateWorldMatrix( true, false ); +class Euler { - } + constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { - if ( this.matrixAutoUpdate ) this.updateMatrix(); + this.isEuler = true; - if ( this.parent === null ) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; - this.matrixWorld.copy( this.matrix ); + } - } else { + get x() { - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + return this._x; - } + } - // update children + set x( value ) { - if ( updateChildren === true ) { + this._x = value; + this._onChangeCallback(); - const children = this.children; + } - for ( let i = 0, l = children.length; i < l; i ++ ) { + get y() { - children[ i ].updateWorldMatrix( false, true ); + return this._y; - } + } - } + set y( value ) { - }, + this._y = value; + this._onChangeCallback(); - toJSON: function ( meta ) { + } - // meta is a string when called from JSON.stringify - const isRootObject = ( meta === undefined || typeof meta === 'string' ); + get z() { - const output = {}; + return this._z; - // 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: {}, - shapes: {}, - skeletons: {}, - animations: {} - }; + set z( value ) { - output.metadata = { - version: 4.5, - type: 'Object', - generator: 'Object3D.toJSON' - }; + this._z = value; + this._onChangeCallback(); - } + } - // standard Object3D serialization + get order() { - const object = {}; + return this._order; - object.uuid = this.uuid; - object.type = this.type; + } - if ( this.name !== '' ) object.name = this.name; - if ( this.castShadow === true ) object.castShadow = true; - if ( this.receiveShadow === true ) object.receiveShadow = true; - if ( this.visible === false ) object.visible = false; - if ( this.frustumCulled === false ) object.frustumCulled = false; - if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; - if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; + set order( value ) { - object.layers = this.layers.mask; - object.matrix = this.matrix.toArray(); + this._order = value; + this._onChangeCallback(); - if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; + } - // object specific properties + set( x, y, z, order = this._order ) { - if ( this.isInstancedMesh ) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; - object.type = 'InstancedMesh'; - object.count = this.count; - object.instanceMatrix = this.instanceMatrix.toJSON(); + this._onChangeCallback(); - } + return this; - // + } - function serialize( library, element ) { + clone() { - if ( library[ element.uuid ] === undefined ) { + return new this.constructor( this._x, this._y, this._z, this._order ); - library[ element.uuid ] = element.toJSON( meta ); + } - } + copy( euler ) { - return element.uuid; + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - } + this._onChangeCallback(); - if ( this.isMesh || this.isLine || this.isPoints ) { + return this; - object.geometry = serialize( meta.geometries, this.geometry ); + } - const parameters = this.geometry.parameters; + setFromRotationMatrix( m, order = this._order, update = true ) { - if ( parameters !== undefined && parameters.shapes !== undefined ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - const shapes = parameters.shapes; + const te = m.elements; + const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - if ( Array.isArray( shapes ) ) { + switch ( order ) { - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + case 'XYZ': - const shape = shapes[ i ]; + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - serialize( meta.shapes, shape ); + if ( Math.abs( m13 ) < 0.9999999 ) { - } + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); } else { - serialize( meta.shapes, shapes ); + this._x = Math.atan2( m32, m22 ); + this._z = 0; } - } + break; - } + case 'YXZ': - if ( this.isSkinnedMesh ) { + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - object.bindMode = this.bindMode; - object.bindMatrix = this.bindMatrix.toArray(); + if ( Math.abs( m23 ) < 0.9999999 ) { - if ( this.skeleton !== undefined ) { + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - serialize( meta.skeletons, this.skeleton ); + } else { - object.skeleton = this.skeleton.uuid; + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - } + } - } + break; - if ( this.material !== undefined ) { + case 'ZXY': - if ( Array.isArray( this.material ) ) { + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - const uuids = []; + if ( Math.abs( m32 ) < 0.9999999 ) { - for ( let i = 0, l = this.material.length; i < l; i ++ ) { + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - uuids.push( serialize( meta.materials, this.material[ i ] ) ); + } else { - } + this._y = 0; + this._z = Math.atan2( m21, m11 ); - object.material = uuids; + } - } else { + break; - object.material = serialize( meta.materials, this.material ); + case 'ZYX': - } + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - } + if ( Math.abs( m31 ) < 0.9999999 ) { - // + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - if ( this.children.length > 0 ) { + } else { - object.children = []; + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - for ( let i = 0; i < this.children.length; i ++ ) { + } - object.children.push( this.children[ i ].toJSON( meta ).object ); + break; - } + case 'YZX': - } + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - // + if ( Math.abs( m21 ) < 0.9999999 ) { - if ( this.animations.length > 0 ) { + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - object.animations = []; + } else { - for ( let i = 0; i < this.animations.length; i ++ ) { + this._x = 0; + this._y = Math.atan2( m13, m33 ); - const animation = this.animations[ i ]; + } - object.animations.push( serialize( meta.animations, animation ) ); + break; - } + case 'XZY': - } + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - if ( isRootObject ) { + if ( Math.abs( m12 ) < 0.9999999 ) { - const geometries = extractFromCache( meta.geometries ); - const materials = extractFromCache( meta.materials ); - const textures = extractFromCache( meta.textures ); - const images = extractFromCache( meta.images ); - const shapes = extractFromCache( meta.shapes ); - const skeletons = extractFromCache( meta.skeletons ); - const animations = extractFromCache( meta.animations ); + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - 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; - if ( shapes.length > 0 ) output.shapes = shapes; - if ( skeletons.length > 0 ) output.skeletons = skeletons; - if ( animations.length > 0 ) output.animations = animations; + } else { - } + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - output.object = object; + } - return output; + break; - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache( cache ) { + default: - const values = []; - for ( const key in cache ) { + console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); - const data = cache[ key ]; - delete data.metadata; - values.push( data ); + } - } + this._order = order; - return values; + if ( update === true ) this._onChangeCallback(); - } + return this; - }, + } - clone: function ( recursive ) { + setFromQuaternion( q, order, update ) { - return new this.constructor().copy( this, recursive ); + _matrix$1.makeRotationFromQuaternion( q ); - }, + return this.setFromRotationMatrix( _matrix$1, order, update ); - copy: function ( source, recursive = true ) { + } - this.name = source.name; + setFromVector3( v, order = this._order ) { - this.up.copy( source.up ); + return this.set( v.x, v.y, v.z, order ); - this.position.copy( source.position ); - this.rotation.order = source.rotation.order; - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + } - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + reorder( newOrder ) { - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + // WARNING: this discards revolution information -bhouston - this.layers.mask = source.layers.mask; - this.visible = source.visible; + _quaternion$3.setFromEuler( this ); - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + return this.setFromQuaternion( _quaternion$3, newOrder ); - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + } - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + equals( euler ) { - if ( recursive === true ) { + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - for ( let i = 0; i < source.children.length; i ++ ) { + } - const child = source.children[ i ]; - this.add( child.clone() ); + fromArray( array ) { - } + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - } + this._onChangeCallback(); return this; } -} ); - -const _vector1 = /*@__PURE__*/ new Vector3(); -const _vector2 = /*@__PURE__*/ new Vector3(); -const _normalMatrix = /*@__PURE__*/ new Matrix3(); - -class Plane { - - constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + toArray( array = [], offset = 0 ) { - // normal is assumed to be normalized + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - this.normal = normal; - this.constant = constant; + return array; } - set( normal, constant ) { + _onChange( callback ) { - this.normal.copy( normal ); - this.constant = constant; + this._onChangeCallback = callback; return this; } - setComponents( x, y, z, w ) { + _onChangeCallback() {} - this.normal.set( x, y, z ); - this.constant = w; + *[ Symbol.iterator ]() { - return this; + yield this._x; + yield this._y; + yield this._z; + yield this._order; } - setFromNormalAndCoplanarPoint( normal, point ) { + // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53 - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); + toVector3() { - return this; + console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' ); } - setFromCoplanarPoints( a, b, c ) { +} - const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); +Euler.DefaultOrder = 'XYZ'; +Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? +class Layers { - this.setFromNormalAndCoplanarPoint( normal, a ); + constructor() { - return this; + this.mask = 1 | 0; } - copy( plane ) { - - this.normal.copy( plane.normal ); - this.constant = plane.constant; + set( channel ) { - return this; + this.mask = ( 1 << channel | 0 ) >>> 0; } - normalize() { - - // Note: will lead to a divide by zero if the plane is invalid. - - const inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + enable( channel ) { - return this; + this.mask |= 1 << channel | 0; } - negate() { - - this.constant *= - 1; - this.normal.negate(); + enableAll() { - return this; + this.mask = 0xffffffff | 0; } - distanceToPoint( point ) { + toggle( channel ) { - return this.normal.dot( point ) + this.constant; + this.mask ^= 1 << channel | 0; } - distanceToSphere( sphere ) { + disable( channel ) { - return this.distanceToPoint( sphere.center ) - sphere.radius; + this.mask &= ~ ( 1 << channel | 0 ); } - projectPoint( point, target ) { + disableAll() { - if ( target === undefined ) { + this.mask = 0; - console.warn( 'THREE.Plane: .projectPoint() target is now required' ); - target = new Vector3(); + } - } + test( layers ) { - return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + return ( this.mask & layers.mask ) !== 0; } - intersectLine( line, target ) { + isEnabled( channel ) { - if ( target === undefined ) { + return ( this.mask & ( 1 << channel | 0 ) ) !== 0; - console.warn( 'THREE.Plane: .intersectLine() target is now required' ); - target = new Vector3(); + } - } +} - const direction = line.delta( _vector1 ); +let _object3DId = 0; - const denominator = this.normal.dot( direction ); +const _v1$4 = /*@__PURE__*/ new Vector3(); +const _q1 = /*@__PURE__*/ new Quaternion(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); +const _target = /*@__PURE__*/ new Vector3(); - if ( denominator === 0 ) { +const _position$3 = /*@__PURE__*/ new Vector3(); +const _scale$2 = /*@__PURE__*/ new Vector3(); +const _quaternion$2 = /*@__PURE__*/ new Quaternion(); - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { +const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 ); +const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); - return target.copy( line.start ); +const _addedEvent = { type: 'added' }; +const _removedEvent = { type: 'removed' }; - } +class Object3D extends EventDispatcher { - // Unsure if this is the correct method to handle this case. - return undefined; + constructor() { - } + super(); - const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + this.isObject3D = true; - if ( t < 0 || t > 1 ) { + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); - return undefined; + this.uuid = generateUUID(); - } + this.name = ''; + this.type = 'Object3D'; - return target.copy( direction ).multiplyScalar( t ).add( line.start ); + this.parent = null; + this.children = []; - } + this.up = Object3D.DefaultUp.clone(); - intersectsLine( line ) { + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3( 1, 1, 1 ); - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + function onRotationChange() { - const startSign = this.distanceToPoint( line.start ); - const endSign = this.distanceToPoint( line.end ); + quaternion.setFromEuler( rotation, false ); - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + } - } + function onQuaternionChange() { - intersectsBox( box ) { + rotation.setFromQuaternion( quaternion, undefined, false ); - return box.intersectsPlane( this ); + } - } + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); - intersectsSphere( sphere ) { + Object.defineProperties( this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - return sphere.intersectsPlane( this ); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - } + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - coplanarPoint( target ) { + this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer - if ( target === undefined ) { + this.layers = new Layers(); + this.visible = true; - console.warn( 'THREE.Plane: .coplanarPoint() target is now required' ); - target = new Vector3(); + this.castShadow = false; + this.receiveShadow = false; - } + this.frustumCulled = true; + this.renderOrder = 0; - return target.copy( this.normal ).multiplyScalar( - this.constant ); + this.animations = []; + + this.userData = {}; } - applyMatrix4( matrix, optionalNormalMatrix ) { + onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {} - const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {} - const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + applyMatrix4( matrix ) { - const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + if ( this.matrixAutoUpdate ) this.updateMatrix(); - this.constant = - referencePoint.dot( normal ); + this.matrix.premultiply( matrix ); - return this; + this.matrix.decompose( this.position, this.quaternion, this.scale ); } - translate( offset ) { + applyQuaternion( q ) { - this.constant -= offset.dot( this.normal ); + this.quaternion.premultiply( q ); return this; } - equals( plane ) { + setRotationFromAxisAngle( axis, angle ) { - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + // assumes axis is normalized + + this.quaternion.setFromAxisAngle( axis, angle ); } - clone() { + setRotationFromEuler( euler ) { - return new this.constructor().copy( this ); + this.quaternion.setFromEuler( euler, true ); } -} + setRotationFromMatrix( m ) { -Plane.prototype.isPlane = true; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) -const _v0$1 = /*@__PURE__*/ new Vector3(); -const _v1$3 = /*@__PURE__*/ new Vector3(); -const _v2$1 = /*@__PURE__*/ new Vector3(); -const _v3 = /*@__PURE__*/ new Vector3(); + this.quaternion.setFromRotationMatrix( m ); -const _vab = /*@__PURE__*/ new Vector3(); -const _vac = /*@__PURE__*/ new Vector3(); -const _vbc = /*@__PURE__*/ new Vector3(); -const _vap = /*@__PURE__*/ new Vector3(); -const _vbp = /*@__PURE__*/ new Vector3(); -const _vcp = /*@__PURE__*/ new Vector3(); + } -class Triangle { + setRotationFromQuaternion( q ) { - constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { + // assumes q is normalized - this.a = a; - this.b = b; - this.c = c; + this.quaternion.copy( q ); } - static getNormal( a, b, c, target ) { + rotateOnAxis( axis, angle ) { - if ( target === undefined ) { + // rotate object on axis in object space + // axis is assumed to be normalized - console.warn( 'THREE.Triangle: .getNormal() target is now required' ); - target = new Vector3(); + _q1.setFromAxisAngle( axis, angle ); - } + this.quaternion.multiply( _q1 ); - target.subVectors( c, b ); - _v0$1.subVectors( a, b ); - target.cross( _v0$1 ); + return this; - const targetLengthSq = target.lengthSq(); - if ( targetLengthSq > 0 ) { + } - return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + rotateOnWorldAxis( axis, angle ) { - } + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent - return target.set( 0, 0, 0 ); + _q1.setFromAxisAngle( axis, angle ); - } + this.quaternion.premultiply( _q1 ); - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - static getBarycoord( point, a, b, c, target ) { + return this; - _v0$1.subVectors( c, a ); - _v1$3.subVectors( b, a ); - _v2$1.subVectors( point, a ); + } - const dot00 = _v0$1.dot( _v0$1 ); - const dot01 = _v0$1.dot( _v1$3 ); - const dot02 = _v0$1.dot( _v2$1 ); - const dot11 = _v1$3.dot( _v1$3 ); - const dot12 = _v1$3.dot( _v2$1 ); + rotateX( angle ) { - const denom = ( dot00 * dot11 - dot01 * dot01 ); + return this.rotateOnAxis( _xAxis, angle ); - if ( target === undefined ) { + } - console.warn( 'THREE.Triangle: .getBarycoord() target is now required' ); - target = new Vector3(); + rotateY( angle ) { - } + return this.rotateOnAxis( _yAxis, angle ); - // collinear or singular triangle - if ( denom === 0 ) { + } - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return target.set( - 2, - 1, - 1 ); + rotateZ( angle ) { - } + return this.rotateOnAxis( _zAxis, angle ); - const invDenom = 1 / denom; - const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + } - // barycentric coordinates must always sum to 1 - return target.set( 1 - u - v, v, u ); + translateOnAxis( axis, distance ) { - } + // translate object by distance along axis in object space + // axis is assumed to be normalized - static containsPoint( point, a, b, c ) { + _v1$4.copy( axis ).applyQuaternion( this.quaternion ); - this.getBarycoord( point, a, b, c, _v3 ); + this.position.add( _v1$4.multiplyScalar( distance ) ); - return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); + return this; } - static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { + translateX( distance ) { - this.getBarycoord( point, p1, p2, p3, _v3 ); + return this.translateOnAxis( _xAxis, distance ); - target.set( 0, 0 ); - target.addScaledVector( uv1, _v3.x ); - target.addScaledVector( uv2, _v3.y ); - target.addScaledVector( uv3, _v3.z ); + } - return target; + translateY( distance ) { - } + return this.translateOnAxis( _yAxis, distance ); - static isFrontFacing( a, b, c, direction ) { + } - _v0$1.subVectors( c, b ); - _v1$3.subVectors( a, b ); + translateZ( distance ) { - // strictly front facing - return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; + return this.translateOnAxis( _zAxis, distance ); } - set( a, b, c ) { - - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + localToWorld( vector ) { - return this; + return vector.applyMatrix4( this.matrixWorld ); } - setFromPointsAndIndices( points, i0, i1, i2 ) { - - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + worldToLocal( vector ) { - return this; + return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); } - clone() { + lookAt( x, y, z ) { - return new this.constructor().copy( this ); + // This method does not support objects having non-uniformly-scaled parent(s) - } + if ( x.isVector3 ) { - copy( triangle ) { + _target.copy( x ); - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + } else { - return this; + _target.set( x, y, z ); - } + } - getArea() { + const parent = this.parent; - _v0$1.subVectors( this.c, this.b ); - _v1$3.subVectors( this.a, this.b ); + this.updateWorldMatrix( true, false ); - return _v0$1.cross( _v1$3 ).length() * 0.5; + _position$3.setFromMatrixPosition( this.matrixWorld ); - } + if ( this.isCamera || this.isLight ) { - getMidpoint( target ) { + _m1$1.lookAt( _position$3, _target, this.up ); - if ( target === undefined ) { + } else { - console.warn( 'THREE.Triangle: .getMidpoint() target is now required' ); - target = new Vector3(); + _m1$1.lookAt( _target, _position$3, this.up ); } - return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + this.quaternion.setFromRotationMatrix( _m1$1 ); - } + if ( parent ) { - getNormal( target ) { + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.invert() ); - return Triangle.getNormal( this.a, this.b, this.c, target ); + } } - getPlane( target ) { + add( object ) { - if ( target === undefined ) { + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.add( arguments[ i ] ); + + } - console.warn( 'THREE.Triangle: .getPlane() target is now required' ); - target = new Plane(); + return this; } - return target.setFromCoplanarPoints( this.a, this.b, this.c ); + if ( object === this ) { - } + console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); + return this; - getBarycoord( point, target ) { + } - return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + if ( object && object.isObject3D ) { - } + if ( object.parent !== null ) { - getUV( point, uv1, uv2, uv3, target ) { + object.parent.remove( object ); - return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); + } - } + object.parent = this; + this.children.push( object ); - containsPoint( point ) { + object.dispatchEvent( _addedEvent ); - return Triangle.containsPoint( point, this.a, this.b, this.c ); + } else { - } + console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); - isFrontFacing( direction ) { + } - return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + return this; } - intersectsBox( box ) { + remove( object ) { - return box.intersectsTriangle( this ); + if ( arguments.length > 1 ) { - } + for ( let i = 0; i < arguments.length; i ++ ) { - closestPointToPoint( p, target ) { + this.remove( arguments[ i ] ); - if ( target === undefined ) { + } - console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' ); - target = new Vector3(); + return this; } - const a = this.a, b = this.b, c = this.c; - let v, w; + const index = this.children.indexOf( object ); - // algorithm thanks to Real-Time Collision Detection by Christer Ericson, - // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., - // under the accompanying license; see chapter 5.1.5 for detailed explanation. - // basically, we're distinguishing which of the voronoi regions of the triangle - // the point lies in with the minimum amount of redundant computation. + if ( index !== - 1 ) { - _vab.subVectors( b, a ); - _vac.subVectors( c, a ); - _vap.subVectors( p, a ); - const d1 = _vab.dot( _vap ); - const d2 = _vac.dot( _vap ); - if ( d1 <= 0 && d2 <= 0 ) { + object.parent = null; + this.children.splice( index, 1 ); - // vertex region of A; barycentric coords (1, 0, 0) - return target.copy( a ); + object.dispatchEvent( _removedEvent ); } - _vbp.subVectors( p, b ); - const d3 = _vab.dot( _vbp ); - const d4 = _vac.dot( _vbp ); - if ( d3 >= 0 && d4 <= d3 ) { + return this; - // vertex region of B; barycentric coords (0, 1, 0) - return target.copy( b ); + } - } + removeFromParent() { - const vc = d1 * d4 - d3 * d2; - if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + const parent = this.parent; - v = d1 / ( d1 - d3 ); - // edge region of AB; barycentric coords (1-v, v, 0) - return target.copy( a ).addScaledVector( _vab, v ); + if ( parent !== null ) { - } + parent.remove( this ); - _vcp.subVectors( p, c ); - const d5 = _vab.dot( _vcp ); - const d6 = _vac.dot( _vcp ); - if ( d6 >= 0 && d5 <= d6 ) { + } - // vertex region of C; barycentric coords (0, 0, 1) - return target.copy( c ); + return this; - } + } - const vb = d5 * d2 - d1 * d6; - if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + clear() { - w = d2 / ( d2 - d6 ); - // edge region of AC; barycentric coords (1-w, 0, w) - return target.copy( a ).addScaledVector( _vac, w ); + for ( let i = 0; i < this.children.length; i ++ ) { - } + const object = this.children[ i ]; - const va = d3 * d6 - d5 * d4; - if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + object.parent = null; - _vbc.subVectors( c, b ); - w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); - // edge region of BC; barycentric coords (0, 1-w, w) - return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + object.dispatchEvent( _removedEvent ); } - // face region - const denom = 1 / ( va + vb + vc ); - // u = va * denom - v = vb * denom; - w = vc * denom; + this.children.length = 0; + + return this; - return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); } - equals( triangle ) { + attach( object ) { - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + // adds object as a child of this, while maintaining the object's world transform - } + // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) -} + this.updateWorldMatrix( true, false ); -let materialId = 0; + _m1$1.copy( this.matrixWorld ).invert(); -function Material() { + if ( object.parent !== null ) { - Object.defineProperty( this, 'id', { value: materialId ++ } ); + object.parent.updateWorldMatrix( true, false ); - this.uuid = MathUtils.generateUUID(); + _m1$1.multiply( object.parent.matrixWorld ); - this.name = ''; - this.type = 'Material'; + } - this.fog = true; + object.applyMatrix4( _m1$1 ); - this.blending = NormalBlending; - this.side = FrontSide; - this.vertexColors = false; + this.add( object ); - this.opacity = 1; - this.transparent = false; + object.updateWorldMatrix( false, true ); - this.blendSrc = SrcAlphaFactor; - this.blendDst = OneMinusSrcAlphaFactor; - this.blendEquation = AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + return this; - this.depthFunc = LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + } - this.stencilWriteMask = 0xff; - this.stencilFunc = AlwaysStencilFunc; - this.stencilRef = 0; - this.stencilFuncMask = 0xff; - this.stencilFail = KeepStencilOp; - this.stencilZFail = KeepStencilOp; - this.stencilZPass = KeepStencilOp; - this.stencilWrite = false; + getObjectById( id ) { - this.clippingPlanes = null; - this.clipIntersection = false; - this.clipShadows = false; + return this.getObjectByProperty( 'id', id ); - this.shadowSide = null; + } - this.colorWrite = true; + getObjectByName( name ) { - this.precision = null; // override the renderer's default precision for this material + return this.getObjectByProperty( 'name', name ); - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + } - this.dithering = false; + getObjectByProperty( name, value ) { - this.alphaTest = 0; - this.premultipliedAlpha = false; + if ( this[ name ] === value ) return this; - this.visible = true; + for ( let i = 0, l = this.children.length; i < l; i ++ ) { - this.toneMapped = true; + const child = this.children[ i ]; + const object = child.getObjectByProperty( name, value ); - this.userData = {}; + if ( object !== undefined ) { - this.version = 0; + return object; -} + } -Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + } - constructor: Material, + return undefined; - isMaterial: true, + } - onBeforeCompile: function ( /* shaderobject, renderer */ ) {}, + getWorldPosition( target ) { - customProgramCacheKey: function () { + this.updateWorldMatrix( true, false ); - return this.onBeforeCompile.toString(); + return target.setFromMatrixPosition( this.matrixWorld ); - }, + } - setValues: function ( values ) { + getWorldQuaternion( target ) { - if ( values === undefined ) return; + this.updateWorldMatrix( true, false ); - for ( const key in values ) { + this.matrixWorld.decompose( _position$3, target, _scale$2 ); - const newValue = values[ key ]; + return target; - if ( newValue === undefined ) { + } - console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); - continue; + getWorldScale( target ) { - } + this.updateWorldMatrix( true, false ); - // for backward compatability if shading is set in the constructor - if ( key === 'shading' ) { + this.matrixWorld.decompose( _position$3, _quaternion$2, target ); - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( newValue === FlatShading ) ? true : false; - continue; + return target; - } + } - const currentValue = this[ key ]; + getWorldDirection( target ) { - if ( currentValue === undefined ) { + this.updateWorldMatrix( true, false ); - console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' ); - continue; + const e = this.matrixWorld.elements; - } + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); - if ( currentValue && currentValue.isColor ) { + } - currentValue.set( newValue ); + raycast( /* raycaster, intersects */ ) {} - } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + traverse( callback ) { - currentValue.copy( newValue ); + callback( this ); - } else { + const children = this.children; - this[ key ] = newValue; + for ( let i = 0, l = children.length; i < l; i ++ ) { - } + children[ i ].traverse( callback ); } - }, - - toJSON: function ( meta ) { + } - const isRoot = ( meta === undefined || typeof meta === 'string' ); + traverseVisible( callback ) { - if ( isRoot ) { + if ( this.visible === false ) return; - meta = { - textures: {}, - images: {} - }; + callback( this ); - } + const children = this.children; - const data = { - metadata: { - version: 4.5, - type: 'Material', - generator: 'Material.toJSON' - } - }; + for ( let i = 0, l = children.length; i < l; i ++ ) { - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + children[ i ].traverseVisible( callback ); - if ( this.name !== '' ) data.name = this.name; + } - 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; + traverseAncestors( callback ) { - if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex(); - if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); - if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + const parent = this.parent; - if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); - if ( this.shininess !== undefined ) data.shininess = this.shininess; - if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; - if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; + if ( parent !== null ) { - if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { + callback( parent ); - data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; + parent.traverseAncestors( callback ); } - if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { + } - data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; + updateMatrix() { - } + this.matrix.compose( this.position, this.quaternion, this.scale ); - if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + this.matrixWorldNeedsUpdate = true; - data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; - data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } - } + updateMatrixWorld( force ) { - if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid; - if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( this.matrixAutoUpdate ) this.updateMatrix(); - if ( this.lightMap && this.lightMap.isTexture ) { + if ( this.matrixWorldNeedsUpdate || force ) { - data.lightMap = this.lightMap.toJSON( meta ).uuid; - data.lightMapIntensity = this.lightMapIntensity; + if ( this.parent === null ) { - } + this.matrixWorld.copy( this.matrix ); - if ( this.aoMap && this.aoMap.isTexture ) { + } else { - data.aoMap = this.aoMap.toJSON( meta ).uuid; - data.aoMapIntensity = this.aoMapIntensity; + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - } + } - if ( this.bumpMap && this.bumpMap.isTexture ) { + this.matrixWorldNeedsUpdate = false; - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + force = true; } - if ( this.normalMap && this.normalMap.isTexture ) { + // update children - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalMapType = this.normalMapType; - data.normalScale = this.normalScale.toArray(); + const children = this.children; - } + for ( let i = 0, l = children.length; i < l; i ++ ) { - if ( this.displacementMap && this.displacementMap.isTexture ) { + const child = children[ i ]; - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + if ( child.matrixWorldAutoUpdate === true || force === true ) { + + child.updateMatrixWorld( force ); + + } } - 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; + updateWorldMatrix( updateParents, updateChildren ) { - if ( this.envMap && this.envMap.isTexture ) { + const parent = this.parent; - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap - data.refractionRatio = this.refractionRatio; + if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) { - if ( this.combine !== undefined ) data.combine = this.combine; - if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + parent.updateWorldMatrix( true, false ); } - if ( this.gradientMap && this.gradientMap.isTexture ) { + if ( this.matrixAutoUpdate ) this.updateMatrix(); - data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); } - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + // update children - if ( this.blending !== NormalBlending ) data.blending = this.blending; - if ( this.side !== FrontSide ) data.side = this.side; - if ( this.vertexColors ) data.vertexColors = true; + if ( updateChildren === true ) { - if ( this.opacity < 1 ) data.opacity = this.opacity; - if ( this.transparent === true ) data.transparent = this.transparent; + const children = this.children; - data.depthFunc = this.depthFunc; - data.depthTest = this.depthTest; - data.depthWrite = this.depthWrite; + for ( let i = 0, l = children.length; i < l; i ++ ) { - data.stencilWrite = this.stencilWrite; - data.stencilWriteMask = this.stencilWriteMask; - data.stencilFunc = this.stencilFunc; - data.stencilRef = this.stencilRef; - data.stencilFuncMask = this.stencilFuncMask; - data.stencilFail = this.stencilFail; - data.stencilZFail = this.stencilZFail; - data.stencilZPass = this.stencilZPass; + const child = children[ i ]; - // rotation (SpriteMaterial) - if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation; + if ( child.matrixWorldAutoUpdate === true ) { - if ( this.polygonOffset === true ) data.polygonOffset = true; - if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; - if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; + child.updateWorldMatrix( false, true ); - if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth; - if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; - if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; - if ( this.scale !== undefined ) data.scale = this.scale; + } - if ( this.dithering === true ) data.dithering = true; + } - 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; - if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; - if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; + } - if ( this.morphTargets === true ) data.morphTargets = true; - if ( this.morphNormals === true ) data.morphNormals = true; - if ( this.skinning === true ) data.skinning = true; + toJSON( meta ) { - if ( this.flatShading === true ) data.flatShading = this.flatShading; + // meta is a string when called from JSON.stringify + const isRootObject = ( meta === undefined || typeof meta === 'string' ); - if ( this.visible === false ) data.visible = false; + const output = {}; - if ( this.toneMapped === false ) data.toneMapped = false; + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; - // TODO: Copied from Object3D.toJSON + output.metadata = { + version: 4.5, + type: 'Object', + generator: 'Object3D.toJSON' + }; - function extractFromCache( cache ) { + } - const values = []; + // standard Object3D serialization - for ( const key in cache ) { + const object = {}; - const data = cache[ key ]; - delete data.metadata; - values.push( data ); + object.uuid = this.uuid; + object.type = this.type; - } + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - return values; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); - } + if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; - if ( isRoot ) { + // object specific properties - const textures = extractFromCache( meta.textures ); - const images = extractFromCache( meta.images ); + if ( this.isInstancedMesh ) { - if ( textures.length > 0 ) data.textures = textures; - if ( images.length > 0 ) data.images = images; + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON(); } - return data; - - }, + // - clone: function () { + function serialize( library, element ) { - return new this.constructor().copy( this ); + if ( library[ element.uuid ] === undefined ) { - }, + library[ element.uuid ] = element.toJSON( meta ); - copy: function ( source ) { + } - this.name = source.name; + return element.uuid; - this.fog = source.fog; + } - this.blending = source.blending; - this.side = source.side; - this.vertexColors = source.vertexColors; + if ( this.isScene ) { - this.opacity = source.opacity; - this.transparent = source.transparent; + if ( this.background ) { - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + if ( this.background.isColor ) { - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + object.background = this.background.toJSON(); - this.stencilWriteMask = source.stencilWriteMask; - this.stencilFunc = source.stencilFunc; - this.stencilRef = source.stencilRef; - this.stencilFuncMask = source.stencilFuncMask; - this.stencilFail = source.stencilFail; - this.stencilZFail = source.stencilZFail; - this.stencilZPass = source.stencilZPass; - this.stencilWrite = source.stencilWrite; + } else if ( this.background.isTexture ) { - const srcPlanes = source.clippingPlanes; - let dstPlanes = null; + object.background = this.background.toJSON( meta ).uuid; - if ( srcPlanes !== null ) { + } - const n = srcPlanes.length; - dstPlanes = new Array( n ); + } - for ( let i = 0; i !== n; ++ i ) { + if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) { - dstPlanes[ i ] = srcPlanes[ i ].clone(); + object.environment = this.environment.toJSON( meta ).uuid; } - } + } else if ( this.isMesh || this.isLine || this.isPoints ) { - this.clippingPlanes = dstPlanes; - this.clipIntersection = source.clipIntersection; - this.clipShadows = source.clipShadows; + object.geometry = serialize( meta.geometries, this.geometry ); - this.shadowSide = source.shadowSide; + const parameters = this.geometry.parameters; - this.colorWrite = source.colorWrite; + if ( parameters !== undefined && parameters.shapes !== undefined ) { - this.precision = source.precision; + const shapes = parameters.shapes; - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + if ( Array.isArray( shapes ) ) { - this.dithering = source.dithering; + for ( let i = 0, l = shapes.length; i < l; i ++ ) { - this.alphaTest = source.alphaTest; - this.premultipliedAlpha = source.premultipliedAlpha; + const shape = shapes[ i ]; - this.visible = source.visible; + serialize( meta.shapes, shape ); - this.toneMapped = source.toneMapped; + } - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + } else { - return this; + serialize( meta.shapes, shapes ); - }, + } - dispose: function () { + } - this.dispatchEvent( { type: 'dispose' } ); + } - } + if ( this.isSkinnedMesh ) { -} ); + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); -Object.defineProperty( Material.prototype, 'needsUpdate', { + if ( this.skeleton !== undefined ) { - set: function ( value ) { + serialize( meta.skeletons, this.skeleton ); - if ( value === true ) this.version ++; + object.skeleton = this.skeleton.uuid; - } + } -} ); + } -const _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, 'rebeccapurple': 0x663399, '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 }; + if ( this.material !== undefined ) { -const _hslA = { h: 0, s: 0, l: 0 }; -const _hslB = { h: 0, s: 0, l: 0 }; + if ( Array.isArray( this.material ) ) { -function hue2rgb( p, q, t ) { + const uuids = []; - 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; + for ( let i = 0, l = this.material.length; i < l; i ++ ) { -} + uuids.push( serialize( meta.materials, this.material[ i ] ) ); -function SRGBToLinear( c ) { + } - return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + object.material = uuids; -} + } else { -function LinearToSRGB( c ) { + object.material = serialize( meta.materials, this.material ); - return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; + } -} + } -class Color { + // - constructor( r, g, b ) { + if ( this.children.length > 0 ) { - if ( g === undefined && b === undefined ) { + object.children = []; - // r is THREE.Color, hex or string - return this.set( r ); + for ( let i = 0; i < this.children.length; i ++ ) { - } + object.children.push( this.children[ i ].toJSON( meta ).object ); - return this.setRGB( r, g, b ); + } - } + } - set( value ) { + // - if ( value && value.isColor ) { + if ( this.animations.length > 0 ) { - this.copy( value ); + object.animations = []; - } else if ( typeof value === 'number' ) { + for ( let i = 0; i < this.animations.length; i ++ ) { - this.setHex( value ); + const animation = this.animations[ i ]; - } else if ( typeof value === 'string' ) { + object.animations.push( serialize( meta.animations, animation ) ); - this.setStyle( value ); + } } - return this; + if ( isRootObject ) { - } + const geometries = extractFromCache( meta.geometries ); + const materials = extractFromCache( meta.materials ); + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + const shapes = extractFromCache( meta.shapes ); + const skeletons = extractFromCache( meta.skeletons ); + const animations = extractFromCache( meta.animations ); + const nodes = extractFromCache( meta.nodes ); - setScalar( scalar ) { + 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; + if ( shapes.length > 0 ) output.shapes = shapes; + if ( skeletons.length > 0 ) output.skeletons = skeletons; + if ( animations.length > 0 ) output.animations = animations; + if ( nodes.length > 0 ) output.nodes = nodes; - this.r = scalar; - this.g = scalar; - this.b = scalar; + } - return this; + output.object = object; - } + return output; + + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { - setHex( hex ) { + const values = []; + for ( const key in cache ) { - hex = Math.floor( hex ); + const data = cache[ key ]; + delete data.metadata; + values.push( data ); - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + } - return this; + return values; - } + } - setRGB( r, g, b ) { + } - this.r = r; - this.g = g; - this.b = b; + clone( recursive ) { - return this; + return new this.constructor().copy( this, recursive ); } - setHSL( h, s, l ) { - - // h,s,l ranges are in 0.0 - 1.0 - h = MathUtils.euclideanModulo( h, 1 ); - s = MathUtils.clamp( s, 0, 1 ); - l = MathUtils.clamp( l, 0, 1 ); + copy( source, recursive = true ) { - if ( s === 0 ) { + this.name = source.name; - this.r = this.g = this.b = l; + this.up.copy( source.up ); - } else { + this.position.copy( source.position ); + this.rotation.order = source.rotation.order; + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - const q = ( 2 * l ) - p; + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - } + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; - return this; + this.layers.mask = source.layers.mask; + this.visible = source.visible; - } + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - setStyle( style ) { + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - function handleAlpha( string ) { + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - if ( string === undefined ) return; + if ( recursive === true ) { - if ( parseFloat( string ) < 1 ) { + for ( let i = 0; i < source.children.length; i ++ ) { - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + const child = source.children[ i ]; + this.add( child.clone() ); } } + return this; - let m; + } - if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { +} - // rgb / hsl +Object3D.DefaultUp = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +Object3D.DefaultMatrixAutoUpdate = true; +Object3D.DefaultMatrixWorldAutoUpdate = true; - let color; - const name = m[ 1 ]; - const components = m[ 2 ]; +const _v0$1 = /*@__PURE__*/ new Vector3(); +const _v1$3 = /*@__PURE__*/ new Vector3(); +const _v2$2 = /*@__PURE__*/ new Vector3(); +const _v3$1 = /*@__PURE__*/ new Vector3(); - switch ( name ) { +const _vab = /*@__PURE__*/ new Vector3(); +const _vac = /*@__PURE__*/ new Vector3(); +const _vbc = /*@__PURE__*/ new Vector3(); +const _vap = /*@__PURE__*/ new Vector3(); +const _vbp = /*@__PURE__*/ new Vector3(); +const _vcp = /*@__PURE__*/ new Vector3(); - case 'rgb': - case 'rgba': +class Triangle { - if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { - // 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; + this.a = a; + this.b = b; + this.c = c; - handleAlpha( color[ 4 ] ); + } - return this; + static getNormal( a, b, c, target ) { - } + target.subVectors( c, b ); + _v0$1.subVectors( a, b ); + target.cross( _v0$1 ); - if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + const targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { - // 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; + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); - handleAlpha( color[ 4 ] ); + } - return this; + return target.set( 0, 0, 0 ); - } + } - break; + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + static getBarycoord( point, a, b, c, target ) { - case 'hsl': - case 'hsla': + _v0$1.subVectors( c, a ); + _v1$3.subVectors( b, a ); + _v2$2.subVectors( point, a ); - if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + const dot00 = _v0$1.dot( _v0$1 ); + const dot01 = _v0$1.dot( _v1$3 ); + const dot02 = _v0$1.dot( _v2$2 ); + const dot11 = _v1$3.dot( _v1$3 ); + const dot12 = _v1$3.dot( _v2$2 ); - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - const h = parseFloat( color[ 1 ] ) / 360; - const s = parseInt( color[ 2 ], 10 ) / 100; - const l = parseInt( color[ 3 ], 10 ) / 100; + const denom = ( dot00 * dot11 - dot01 * dot01 ); - handleAlpha( color[ 4 ] ); + // collinear or singular triangle + if ( denom === 0 ) { - return this.setHSL( h, s, l ); + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return target.set( - 2, - 1, - 1 ); - } + } - break; + const invDenom = 1 / denom; + const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - } + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); - } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { + } - // hex color + static containsPoint( point, a, b, c ) { - const hex = m[ 1 ]; - const size = hex.length; + this.getBarycoord( point, a, b, c, _v3$1 ); - if ( size === 3 ) { + return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); - // #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; + } - return this; + static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { - } else if ( size === 6 ) { + this.getBarycoord( point, p1, p2, p3, _v3$1 ); - // #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; + target.set( 0, 0 ); + target.addScaledVector( uv1, _v3$1.x ); + target.addScaledVector( uv2, _v3$1.y ); + target.addScaledVector( uv3, _v3$1.z ); - return this; + return target; - } + } - } + static isFrontFacing( a, b, c, direction ) { - if ( style && style.length > 0 ) { + _v0$1.subVectors( c, b ); + _v1$3.subVectors( a, b ); - return this.setColorName( style ); + // strictly front facing + return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; - } + } + + set( a, b, c ) { + + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); return this; } - setColorName( style ) { - - // color keywords - const hex = _colorKeywords[ style ]; + setFromPointsAndIndices( points, i0, i1, i2 ) { - if ( hex !== undefined ) { + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); - // red - this.setHex( hex ); + return this; - } else { + } - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + setFromAttributeAndIndices( attribute, i0, i1, i2 ) { - } + this.a.fromBufferAttribute( attribute, i0 ); + this.b.fromBufferAttribute( attribute, i1 ); + this.c.fromBufferAttribute( attribute, i2 ); return this; @@ -8573,631 +8486,813 @@ class Color { clone() { - return new this.constructor( this.r, this.g, this.b ); + return new this.constructor().copy( this ); } - copy( color ) { + copy( triangle ) { - this.r = color.r; - this.g = color.g; - this.b = color.b; + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); return this; } - copyGammaToLinear( color, gammaFactor = 2.0 ) { + getArea() { - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + _v0$1.subVectors( this.c, this.b ); + _v1$3.subVectors( this.a, this.b ); - return this; + return _v0$1.cross( _v1$3 ).length() * 0.5; } - copyLinearToGamma( color, gammaFactor = 2.0 ) { - - const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + getMidpoint( target ) { - return this; + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); } - convertGammaToLinear( gammaFactor ) { - - this.copyGammaToLinear( this, gammaFactor ); + getNormal( target ) { - return this; + return Triangle.getNormal( this.a, this.b, this.c, target ); } - convertLinearToGamma( gammaFactor ) { - - this.copyLinearToGamma( this, gammaFactor ); + getPlane( target ) { - return this; + return target.setFromCoplanarPoints( this.a, this.b, this.c ); } - copySRGBToLinear( color ) { - - this.r = SRGBToLinear( color.r ); - this.g = SRGBToLinear( color.g ); - this.b = SRGBToLinear( color.b ); + getBarycoord( point, target ) { - return this; + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); } - copyLinearToSRGB( color ) { - - this.r = LinearToSRGB( color.r ); - this.g = LinearToSRGB( color.g ); - this.b = LinearToSRGB( color.b ); + getUV( point, uv1, uv2, uv3, target ) { - return this; + return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); } - convertSRGBToLinear() { - - this.copySRGBToLinear( this ); + containsPoint( point ) { - return this; + return Triangle.containsPoint( point, this.a, this.b, this.c ); } - convertLinearToSRGB() { - - this.copyLinearToSRGB( this ); + isFrontFacing( direction ) { - return this; + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); } - getHex() { + intersectsBox( box ) { - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + return box.intersectsTriangle( this ); } - getHexString() { + closestPointToPoint( p, target ) { + + const a = this.a, b = this.b, c = this.c; + let v, w; - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. - } + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + const d1 = _vab.dot( _vap ); + const d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { - getHSL( target ) { + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); - // h,s,l ranges are in 0.0 - 1.0 + } - if ( target === undefined ) { + _vbp.subVectors( p, b ); + const d3 = _vab.dot( _vbp ); + const d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { - console.warn( 'THREE.Color: .getHSL() target is now required' ); - target = { h: 0, s: 0, l: 0 }; + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); } - const r = this.r, g = this.g, b = this.b; - - const max = Math.max( r, g, b ); - const min = Math.min( r, g, b ); + const vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { - let hue, saturation; - const lightness = ( min + max ) / 2.0; + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); - if ( min === max ) { + } - hue = 0; - saturation = 0; + _vcp.subVectors( p, c ); + const d5 = _vab.dot( _vcp ); + const d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { - } else { + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); - const delta = max - min; + } - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + const vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { - switch ( max ) { + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); - 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; + } - } + const va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { - hue /= 6; + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC } - target.h = hue; - target.s = saturation; - target.l = lightness; + // face region + const denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; - return target; + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); } - getStyle() { + equals( triangle ) { - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); } - offsetHSL( h, s, l ) { +} - this.getHSL( _hslA ); +let materialId = 0; - _hslA.h += h; _hslA.s += s; _hslA.l += l; +class Material extends EventDispatcher { - this.setHSL( _hslA.h, _hslA.s, _hslA.l ); + constructor() { - return this; + super(); - } + this.isMaterial = true; - add( color ) { + Object.defineProperty( this, 'id', { value: materialId ++ } ); - this.r += color.r; - this.g += color.g; - this.b += color.b; + this.uuid = generateUUID(); - return this; + this.name = ''; + this.type = 'Material'; - } + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; - addColors( color1, color2 ) { + this.opacity = 1; + this.transparent = false; - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - return this; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - } + this.stencilWriteMask = 0xff; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 0xff; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; - addScalar( s ) { + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; - this.r += s; - this.g += s; - this.b += s; + this.shadowSide = null; - return this; + this.colorWrite = true; - } + this.precision = null; // override the renderer's default precision for this material - sub( color ) { + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - 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 ); + this.dithering = false; - return this; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; - } + this.visible = true; - multiply( color ) { + this.toneMapped = true; - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + this.userData = {}; - return this; + this.version = 0; - } + this._alphaTest = 0; - multiplyScalar( s ) { + } - this.r *= s; - this.g *= s; - this.b *= s; + get alphaTest() { - return this; + return this._alphaTest; } - lerp( color, alpha ) { - - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; - - return this; + set alphaTest( value ) { - } + if ( this._alphaTest > 0 !== value > 0 ) { - lerpColors( color1, color2, alpha ) { + this.version ++; - this.r = color1.r + ( color2.r - color1.r ) * alpha; - this.g = color1.g + ( color2.g - color1.g ) * alpha; - this.b = color1.b + ( color2.b - color1.b ) * alpha; + } - return this; + this._alphaTest = value; } - lerpHSL( color, alpha ) { + onBuild( /* shaderobject, renderer */ ) {} - this.getHSL( _hslA ); - color.getHSL( _hslB ); + onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {} - const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha ); - const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha ); - const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha ); + onBeforeCompile( /* shaderobject, renderer */ ) {} - this.setHSL( h, s, l ); + customProgramCacheKey() { - return this; + return this.onBeforeCompile.toString(); } - equals( c ) { - - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - - } + setValues( values ) { - fromArray( array, offset = 0 ) { + if ( values === undefined ) return; - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + for ( const key in values ) { - return this; + const newValue = values[ key ]; - } + if ( newValue === undefined ) { - toArray( array = [], offset = 0 ) { + console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); + continue; - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + } - return array; + const currentValue = this[ key ]; - } + if ( currentValue === undefined ) { - fromBufferAttribute( attribute, index ) { + console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' ); + continue; - this.r = attribute.getX( index ); - this.g = attribute.getY( index ); - this.b = attribute.getZ( index ); + } - if ( attribute.normalized === true ) { + if ( currentValue && currentValue.isColor ) { - // assuming Uint8Array + currentValue.set( newValue ); - this.r /= 255; - this.g /= 255; - this.b /= 255; + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { - } + currentValue.copy( newValue ); - return this; + } else { - } + this[ key ] = newValue; - toJSON() { + } - return this.getHex(); + } } -} - -Color.NAMES = _colorKeywords; - -Color.prototype.isColor = true; -Color.prototype.r = 1; -Color.prototype.g = 1; -Color.prototype.b = 1; + toJSON( meta ) { -/** - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: - * } - */ + const isRootObject = ( meta === undefined || typeof meta === 'string' ); -class MeshBasicMaterial extends Material { + if ( isRootObject ) { - constructor( parameters ) { + meta = { + textures: {}, + images: {} + }; - super(); + } - this.type = 'MeshBasicMaterial'; + const data = { + metadata: { + version: 4.5, + type: 'Material', + generator: 'Material.toJSON' + } + }; - this.color = new Color( 0xffffff ); // emissive + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - this.map = null; + if ( this.name !== '' ) data.name = this.name; - this.lightMap = null; - this.lightMapIntensity = 1.0; + if ( this.color && this.color.isColor ) data.color = this.color.getHex(); - this.aoMap = null; - this.aoMapIntensity = 1.0; + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - this.specularMap = null; + if ( this.sheen !== undefined ) data.sheen = this.sheen; + if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); + if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; - this.alphaMap = null; + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; + if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; - this.skinning = false; - this.morphTargets = false; + } - this.setValues( parameters ); + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { - } + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; - copy( source ) { + } - super.copy( source ); + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { - this.color.copy( source.color ); + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); - this.map = source.map; + } - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { - this.specularMap = source.specularMap; + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; - this.alphaMap = source.alphaMap; + } - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + } - return this; + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.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; + data.lightMapIntensity = this.lightMapIntensity; -MeshBasicMaterial.prototype.isMeshBasicMaterial = true; + } -const _vector$3 = new Vector3(); -const _vector2$1 = new Vector2(); + if ( this.aoMap && this.aoMap.isTexture ) { -function BufferAttribute( array, itemSize, normalized ) { + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; - if ( Array.isArray( array ) ) { + } - throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + if ( this.bumpMap && this.bumpMap.isTexture ) { - } + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - this.name = ''; + } - this.array = array; - this.itemSize = itemSize; - this.count = array !== undefined ? array.length / itemSize : 0; - this.normalized = normalized === true; + if ( this.normalMap && this.normalMap.isTexture ) { - this.usage = StaticDrawUsage; - this.updateRange = { offset: 0, count: - 1 }; + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); - this.version = 0; + } -} + if ( this.displacementMap && this.displacementMap.isTexture ) { -Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', { + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; - set: function ( value ) { + } - if ( value === true ) this.version ++; + 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; + if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid; + if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid; -} ); + if ( this.envMap && this.envMap.isTexture ) { -Object.assign( BufferAttribute.prototype, { + data.envMap = this.envMap.toJSON( meta ).uuid; - isBufferAttribute: true, + if ( this.combine !== undefined ) data.combine = this.combine; - onUploadCallback: function () {}, + } - setUsage: function ( value ) { + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; + if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; - this.usage = value; + if ( this.gradientMap && this.gradientMap.isTexture ) { - return this; + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; - }, + } - copy: function ( source ) { + if ( this.transmission !== undefined ) data.transmission = this.transmission; + if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid; + if ( this.thickness !== undefined ) data.thickness = this.thickness; + if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid; + if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance; + if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex(); - this.name = source.name; - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; - this.count = source.count; - this.normalized = source.normalized; + if ( this.size !== undefined ) data.size = this.size; + if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - this.usage = source.usage; + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors ) data.vertexColors = true; - return this; + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; - }, + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; + data.colorWrite = this.colorWrite; - copyAt: function ( index1, attribute, index2 ) { + data.stencilWrite = this.stencilWrite; + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; - index1 *= this.itemSize; - index2 *= attribute.itemSize; + // rotation (SpriteMaterial) + if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation; - for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + if ( this.polygonOffset === true ) data.polygonOffset = true; + if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; + if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; - } + if ( this.dithering === true ) data.dithering = true; - return this; + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - }, + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; - copyArray: function ( array ) { + if ( this.flatShading === true ) data.flatShading = this.flatShading; - this.array.set( array ); + if ( this.visible === false ) data.visible = false; - return this; + if ( this.toneMapped === false ) data.toneMapped = false; - }, + if ( this.fog === false ) data.fog = false; - copyColorsArray: function ( colors ) { + if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; - const array = this.array; - let offset = 0; + // TODO: Copied from Object3D.toJSON - for ( let i = 0, l = colors.length; i < l; i ++ ) { + function extractFromCache( cache ) { - let color = colors[ i ]; + const values = []; - if ( color === undefined ) { + for ( const key in cache ) { - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new Color(); + const data = cache[ key ]; + delete data.metadata; + values.push( data ); } - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + return values; } - return this; - - }, + if ( isRootObject ) { - copyVector2sArray: function ( vectors ) { + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); - const array = this.array; - let offset = 0; + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - for ( let i = 0, l = vectors.length; i < l; i ++ ) { + } - let vector = vectors[ i ]; + return data; - if ( vector === undefined ) { + } - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new Vector2(); + clone() { - } + return new this.constructor().copy( this ); - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + } - } + copy( source ) { - return this; + this.name = source.name; - }, + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + + this.opacity = source.opacity; + this.transparent = source.transparent; + + 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; - copyVector3sArray: function ( vectors ) { + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; - const array = this.array; - let offset = 0; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; - for ( let i = 0, l = vectors.length; i < l; i ++ ) { + if ( srcPlanes !== null ) { - let vector = vectors[ i ]; + const n = srcPlanes.length; + dstPlanes = new Array( n ); - if ( vector === undefined ) { + for ( let i = 0; i !== n; ++ i ) { - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new Vector3(); + dstPlanes[ i ] = srcPlanes[ i ].clone(); } - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + } + + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + + this.shadowSide = source.shadowSide; + + this.colorWrite = source.colorWrite; + + this.precision = source.precision; + + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + + this.dithering = source.dithering; + + this.alphaTest = source.alphaTest; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + + this.visible = source.visible; + + this.toneMapped = source.toneMapped; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +class MeshBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshBasicMaterial = true; + + this.type = 'MeshBasicMaterial'; + + this.color = new Color( 0xffffff ); // emissive + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + 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.fog = source.fog; + + return this; + + } + +} + +const _vector$9 = /*@__PURE__*/ new Vector3(); +const _vector2$1 = /*@__PURE__*/ new Vector2(); + +class BufferAttribute { + + constructor( array, itemSize, normalized ) { + + if ( Array.isArray( array ) ) { + + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); } + this.isBufferAttribute = true; + + this.name = ''; + + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized === true; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + return this; - }, + } - copyVector4sArray: function ( vectors ) { + copy( source ) { - const array = this.array; - let offset = 0; + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; - for ( let i = 0, l = vectors.length; i < l; i ++ ) { + this.usage = source.usage; - let vector = vectors[ i ]; + return this; - if ( vector === undefined ) { + } - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new Vector4(); + copyAt( index1, attribute, index2 ) { - } + index1 *= this.itemSize; + index2 *= attribute.itemSize; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; } return this; - }, + } + + copyArray( array ) { + + this.array.set( array ); - applyMatrix3: function ( m ) { + return this; + + } + + applyMatrix3( m ) { if ( this.itemSize === 2 ) { @@ -9214,10 +9309,10 @@ Object.assign( BufferAttribute.prototype, { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.fromBufferAttribute( this, i ); - _vector$3.applyMatrix3( m ); + _vector$9.fromBufferAttribute( this, i ); + _vector$9.applyMatrix3( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } @@ -9225,153 +9320,196 @@ Object.assign( BufferAttribute.prototype, { return this; - }, + } - applyMatrix4: function ( m ) { + applyMatrix4( m ) { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.x = this.getX( i ); - _vector$3.y = this.getY( i ); - _vector$3.z = this.getZ( i ); + _vector$9.fromBufferAttribute( this, i ); - _vector$3.applyMatrix4( m ); + _vector$9.applyMatrix4( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } return this; - }, + } - applyNormalMatrix: function ( m ) { + applyNormalMatrix( m ) { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.x = this.getX( i ); - _vector$3.y = this.getY( i ); - _vector$3.z = this.getZ( i ); + _vector$9.fromBufferAttribute( this, i ); - _vector$3.applyNormalMatrix( m ); + _vector$9.applyNormalMatrix( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } return this; - }, + } - transformDirection: function ( m ) { + transformDirection( m ) { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.x = this.getX( i ); - _vector$3.y = this.getY( i ); - _vector$3.z = this.getZ( i ); + _vector$9.fromBufferAttribute( this, i ); - _vector$3.transformDirection( m ); + _vector$9.transformDirection( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } return this; - }, + } - set: function ( value, offset = 0 ) { + set( value, offset = 0 ) { + // Matching BufferAttribute constructor, do not normalize the array. this.array.set( value, offset ); return this; - }, + } - getX: function ( index ) { + getX( index ) { - return this.array[ index * this.itemSize ]; + let x = this.array[ index * this.itemSize ]; - }, + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + setX( index, x ) { - setX: function ( index, x ) { + if ( this.normalized ) x = normalize( x, this.array ); this.array[ index * this.itemSize ] = x; return this; - }, + } - getY: function ( index ) { + getY( index ) { - return this.array[ index * this.itemSize + 1 ]; + let y = this.array[ index * this.itemSize + 1 ]; - }, + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + setY( index, y ) { - setY: function ( index, y ) { + if ( this.normalized ) y = normalize( y, this.array ); this.array[ index * this.itemSize + 1 ] = y; return this; - }, + } - getZ: function ( index ) { + getZ( index ) { - return this.array[ index * this.itemSize + 2 ]; + let z = this.array[ index * this.itemSize + 2 ]; - }, + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } - setZ: function ( index, z ) { + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); this.array[ index * this.itemSize + 2 ] = z; return this; - }, + } - getW: function ( index ) { + getW( index ) { - return this.array[ index * this.itemSize + 3 ]; + let w = this.array[ index * this.itemSize + 3 ]; - }, + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setW( index, w ) { - setW: function ( index, w ) { + if ( this.normalized ) w = normalize( w, this.array ); this.array[ index * this.itemSize + 3 ] = w; return this; - }, + } - setXY: function ( index, x, y ) { + setXY( index, x, y ) { index *= this.itemSize; + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; return this; - }, + } - setXYZ: function ( index, x, y, z ) { + setXYZ( index, x, y, z ) { index *= this.itemSize; + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; return this; - }, + } - setXYZW: function ( index, x, y, z, w ) { + setXYZW( index, x, y, z, w ) { index *= this.itemSize; + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; @@ -9379,221 +9517,224 @@ Object.assign( BufferAttribute.prototype, { return this; - }, + } - onUpload: function ( callback ) { + onUpload( callback ) { this.onUploadCallback = callback; return this; - }, + } - clone: function () { + clone() { return new this.constructor( this.array, this.itemSize ).copy( this ); - }, + } - toJSON: function () { + toJSON() { - return { + const data = { itemSize: this.itemSize, type: this.array.constructor.name, - array: Array.prototype.slice.call( this.array ), + array: Array.from( this.array ), normalized: this.normalized }; - } + if ( this.name !== '' ) data.name = this.name; + if ( this.usage !== StaticDrawUsage ) data.usage = this.usage; + if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange; -} ); + return data; -// + } -function Int8BufferAttribute( array, itemSize, normalized ) { + // @deprecated - BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized ); + copyColorsArray() { -} + console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' ); -Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Int8BufferAttribute.prototype.constructor = Int8BufferAttribute; + } + copyVector2sArray() { -function Uint8BufferAttribute( array, itemSize, normalized ) { + console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' ); - BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized ); + } -} + copyVector3sArray() { -Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute; + console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' ); + } + + copyVector4sArray() { -function Uint8ClampedBufferAttribute( array, itemSize, normalized ) { + console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' ); - BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized ); + } } -Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute; +// + +class Int8BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Int16BufferAttribute( array, itemSize, normalized ) { + super( new Int8Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized ); + } } -Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Int16BufferAttribute.prototype.constructor = Int16BufferAttribute; +class Uint8BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Uint16BufferAttribute( array, itemSize, normalized ) { + super( new Uint8Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); + } } -Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute; +class Uint8ClampedBufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Int32BufferAttribute( array, itemSize, normalized ) { + super( new Uint8ClampedArray( array ), itemSize, normalized ); - BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized ); + } } -Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Int32BufferAttribute.prototype.constructor = Int32BufferAttribute; +class Int16BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Uint32BufferAttribute( array, itemSize, normalized ) { + super( new Int16Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized ); + } } -Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute; +class Uint16BufferAttribute extends BufferAttribute { -function Float16BufferAttribute( array, itemSize, normalized ) { + constructor( array, itemSize, normalized ) { - BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); + super( new Uint16Array( array ), itemSize, normalized ); + + } } -Float16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Float16BufferAttribute.prototype.constructor = Float16BufferAttribute; -Float16BufferAttribute.prototype.isFloat16BufferAttribute = true; +class Int32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { -function Float32BufferAttribute( array, itemSize, normalized ) { + super( new Int32Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized ); + } } -Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; +class Uint32BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Float64BufferAttribute( array, itemSize, normalized ) { + super( new Uint32Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized ); + } } -Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; +class Float16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { -function arrayMax( array ) { + super( new Uint16Array( array ), itemSize, normalized ); - if ( array.length === 0 ) return - Infinity; + this.isFloat16BufferAttribute = true; - let max = array[ 0 ]; + } - for ( let i = 1, l = array.length; i < l; ++ i ) { +} - if ( array[ i ] > max ) max = array[ i ]; - } +class Float32BufferAttribute extends BufferAttribute { - return max; + constructor( array, itemSize, normalized ) { + + super( new Float32Array( array ), itemSize, normalized ); + + } } -const TYPED_ARRAYS = { - Int8Array: Int8Array, - Uint8Array: Uint8Array, - Uint8ClampedArray: Uint8ClampedArray, - Int16Array: Int16Array, - Uint16Array: Uint16Array, - Int32Array: Int32Array, - Uint32Array: Uint32Array, - Float32Array: Float32Array, - Float64Array: Float64Array -}; +class Float64BufferAttribute extends BufferAttribute { -function getTypedArray( type, buffer ) { + constructor( array, itemSize, normalized ) { - return new TYPED_ARRAYS[ type ]( buffer ); + super( new Float64Array( array ), itemSize, normalized ); + + } } -let _id = 0; +let _id$1 = 0; -const _m1$2 = new Matrix4(); -const _obj = new Object3D(); -const _offset = new Vector3(); -const _box$2 = new Box3(); -const _boxMorphTargets = new Box3(); -const _vector$4 = new Vector3(); +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); +const _box$1 = /*@__PURE__*/ new Box3(); +const _boxMorphTargets = /*@__PURE__*/ new Box3(); +const _vector$8 = /*@__PURE__*/ new Vector3(); -function BufferGeometry() { +class BufferGeometry extends EventDispatcher { - Object.defineProperty( this, 'id', { value: _id ++ } ); + constructor() { - this.uuid = MathUtils.generateUUID(); + super(); - this.name = ''; - this.type = 'BufferGeometry'; + this.isBufferGeometry = true; - this.index = null; - this.attributes = {}; + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); - this.morphAttributes = {}; - this.morphTargetsRelative = false; + this.uuid = generateUUID(); - this.groups = []; + this.name = ''; + this.type = 'BufferGeometry'; - this.boundingBox = null; - this.boundingSphere = null; + this.index = null; + this.attributes = {}; - this.drawRange = { start: 0, count: Infinity }; + this.morphAttributes = {}; + this.morphTargetsRelative = false; - this.userData = {}; + this.groups = []; -} + this.boundingBox = null; + this.boundingSphere = null; -BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + this.drawRange = { start: 0, count: Infinity }; - constructor: BufferGeometry, + this.userData = {}; - isBufferGeometry: true, + } - getIndex: function () { + getIndex() { return this.index; - }, + } - setIndex: function ( index ) { + setIndex( index ) { if ( Array.isArray( index ) ) { - this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); } else { @@ -9603,37 +9744,37 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - getAttribute: function ( name ) { + getAttribute( name ) { return this.attributes[ name ]; - }, + } - setAttribute: function ( name, attribute ) { + setAttribute( name, attribute ) { this.attributes[ name ] = attribute; return this; - }, + } - deleteAttribute: function ( name ) { + deleteAttribute( name ) { delete this.attributes[ name ]; return this; - }, + } - hasAttribute: function ( name ) { + hasAttribute( name ) { return this.attributes[ name ] !== undefined; - }, + } - addGroup: function ( start, count, materialIndex = 0 ) { + addGroup( start, count, materialIndex = 0 ) { this.groups.push( { @@ -9643,22 +9784,22 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } ); - }, + } - clearGroups: function () { + clearGroups() { this.groups = []; - }, + } - setDrawRange: function ( start, count ) { + setDrawRange( start, count ) { this.drawRange.start = start; this.drawRange.count = count; - }, + } - applyMatrix4: function ( matrix ) { + applyMatrix4( matrix ) { const position = this.attributes.position; @@ -9706,69 +9847,79 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } + + applyQuaternion( q ) { + + _m1.makeRotationFromQuaternion( q ); + + this.applyMatrix4( _m1 ); - rotateX: function ( angle ) { + return this; + + } + + rotateX( angle ) { // rotate geometry around world x-axis - _m1$2.makeRotationX( angle ); + _m1.makeRotationX( angle ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - rotateY: function ( angle ) { + rotateY( angle ) { // rotate geometry around world y-axis - _m1$2.makeRotationY( angle ); + _m1.makeRotationY( angle ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - rotateZ: function ( angle ) { + rotateZ( angle ) { // rotate geometry around world z-axis - _m1$2.makeRotationZ( angle ); + _m1.makeRotationZ( angle ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - translate: function ( x, y, z ) { + translate( x, y, z ) { // translate geometry - _m1$2.makeTranslation( x, y, z ); + _m1.makeTranslation( x, y, z ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - scale: function ( x, y, z ) { + scale( x, y, z ) { // scale geometry - _m1$2.makeScale( x, y, z ); + _m1.makeScale( x, y, z ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - lookAt: function ( vector ) { + lookAt( vector ) { _obj.lookAt( vector ); @@ -9778,9 +9929,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - center: function () { + center() { this.computeBoundingBox(); @@ -9790,9 +9941,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - setFromPoints: function ( points ) { + setFromPoints( points ) { const position = []; @@ -9807,9 +9958,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - computeBoundingBox: function () { + computeBoundingBox() { if ( this.boundingBox === null ) { @@ -9844,20 +9995,20 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { const morphAttribute = morphAttributesPosition[ i ]; - _box$2.setFromBufferAttribute( morphAttribute ); + _box$1.setFromBufferAttribute( morphAttribute ); if ( this.morphTargetsRelative ) { - _vector$4.addVectors( this.boundingBox.min, _box$2.min ); - this.boundingBox.expandByPoint( _vector$4 ); + _vector$8.addVectors( this.boundingBox.min, _box$1.min ); + this.boundingBox.expandByPoint( _vector$8 ); - _vector$4.addVectors( this.boundingBox.max, _box$2.max ); - this.boundingBox.expandByPoint( _vector$4 ); + _vector$8.addVectors( this.boundingBox.max, _box$1.max ); + this.boundingBox.expandByPoint( _vector$8 ); } else { - this.boundingBox.expandByPoint( _box$2.min ); - this.boundingBox.expandByPoint( _box$2.max ); + this.boundingBox.expandByPoint( _box$1.min ); + this.boundingBox.expandByPoint( _box$1.max ); } @@ -9877,9 +10028,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, + } - computeBoundingSphere: function () { + computeBoundingSphere() { if ( this.boundingSphere === null ) { @@ -9906,7 +10057,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const center = this.boundingSphere.center; - _box$2.setFromBufferAttribute( position ); + _box$1.setFromBufferAttribute( position ); // process morph attributes if present @@ -9919,16 +10070,16 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy if ( this.morphTargetsRelative ) { - _vector$4.addVectors( _box$2.min, _boxMorphTargets.min ); - _box$2.expandByPoint( _vector$4 ); + _vector$8.addVectors( _box$1.min, _boxMorphTargets.min ); + _box$1.expandByPoint( _vector$8 ); - _vector$4.addVectors( _box$2.max, _boxMorphTargets.max ); - _box$2.expandByPoint( _vector$4 ); + _vector$8.addVectors( _box$1.max, _boxMorphTargets.max ); + _box$1.expandByPoint( _vector$8 ); } else { - _box$2.expandByPoint( _boxMorphTargets.min ); - _box$2.expandByPoint( _boxMorphTargets.max ); + _box$1.expandByPoint( _boxMorphTargets.min ); + _box$1.expandByPoint( _boxMorphTargets.max ); } @@ -9936,7 +10087,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - _box$2.getCenter( center ); + _box$1.getCenter( center ); // second, try to find a boundingSphere with a radius smaller than the // boundingSphere of the boundingBox: sqrt(3) smaller in the best case @@ -9945,9 +10096,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let i = 0, il = position.count; i < il; i ++ ) { - _vector$4.fromBufferAttribute( position, i ); + _vector$8.fromBufferAttribute( position, i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); } @@ -9962,16 +10113,16 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) { - _vector$4.fromBufferAttribute( morphAttribute, j ); + _vector$8.fromBufferAttribute( morphAttribute, j ); if ( morphTargetsRelative ) { _offset.fromBufferAttribute( position, j ); - _vector$4.add( _offset ); + _vector$8.add( _offset ); } - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); } @@ -9989,15 +10140,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, - - computeFaceNormals: function () { - - // backwards compatibility - - }, + } - computeTangents: function () { + computeTangents() { const index = this.index; const attributes = this.attributes; @@ -10022,13 +10167,13 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const nVertices = positions.length / 3; - if ( attributes.tangent === undefined ) { + if ( this.hasAttribute( 'tangent' ) === false ) { this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); } - const tangents = attributes.tangent.array; + const tangents = this.getAttribute( 'tangent' ).array; const tan1 = [], tan2 = []; @@ -10160,9 +10305,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, + } - computeVertexNormals: function () { + computeVertexNormals() { const index = this.index; const positionAttribute = this.getAttribute( 'position' ); @@ -10252,72 +10397,34 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, - - merge: function ( geometry, offset ) { - - if ( ! ( geometry && geometry.isBufferGeometry ) ) { - - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; - - } - - if ( offset === undefined ) { - - offset = 0; - - console.warn( - 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' - + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.' - ); - - } - - const attributes = this.attributes; - - for ( const key in attributes ) { - - if ( geometry.attributes[ key ] === undefined ) continue; - - const attribute1 = attributes[ key ]; - const attributeArray1 = attribute1.array; - - const attribute2 = geometry.attributes[ key ]; - const attributeArray2 = attribute2.array; - - const attributeOffset = attribute2.itemSize * offset; - const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset ); - - for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) { - - attributeArray1[ j ] = attributeArray2[ i ]; + } - } + // @deprecated since r144 - } + merge() { + console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' ); return this; - }, + } - normalizeNormals: function () { + normalizeNormals() { const normals = this.attributes.normal; for ( let i = 0, il = normals.count; i < il; i ++ ) { - _vector$4.fromBufferAttribute( normals, i ); + _vector$8.fromBufferAttribute( normals, i ); - _vector$4.normalize(); + _vector$8.normalize(); - normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); + normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); } - }, + } - toNonIndexed: function () { + toNonIndexed() { function convertBufferAttribute( attribute, indices ) { @@ -10331,7 +10438,15 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let i = 0, l = indices.length; i < l; i ++ ) { - index = indices[ i ] * itemSize; + if ( attribute.isInterleavedBufferAttribute ) { + + index = indices[ i ] * attribute.data.stride + attribute.offset; + + } else { + + index = indices[ i ] * itemSize; + + } for ( let j = 0; j < itemSize; j ++ ) { @@ -10409,9 +10524,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return geometry2; - }, + } - toJSON: function () { + toJSON() { const data = { metadata: { @@ -10442,6 +10557,8 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } + // for simplicity the code assumes attributes are not shared across geometries, see #15811 + data.data = { attributes: {} }; const index = this.index; @@ -10461,11 +10578,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const attribute = attributes[ key ]; - const attributeData = attribute.toJSON( data.data ); - - if ( attribute.name !== '' ) attributeData.name = attribute.name; - - data.data.attributes[ key ] = attributeData; + data.data.attributes[ key ] = attribute.toJSON( data.data ); } @@ -10482,11 +10595,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const attribute = attributeArray[ i ]; - const attributeData = attribute.toJSON( data.data ); - - if ( attribute.name !== '' ) attributeData.name = attribute.name; - - array.push( attributeData ); + array.push( attribute.toJSON( data.data ) ); } @@ -10528,39 +10637,15 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return data; - }, - - clone: function () { - - /* - // Handle primitives - - const parameters = this.parameters; - - if ( parameters !== undefined ) { - - const values = []; - - for ( const key in parameters ) { - - values.push( parameters[ key ] ); - - } - - const geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + } - } + clone() { return new this.constructor().copy( this ); - */ - return new BufferGeometry().copy( this ); - - }, + } - copy: function ( source ) { + copy( source ) { // reset @@ -10661,63 +10746,65 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy this.userData = source.userData; + // geometry generator parameters + + if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters ); + return this; - }, + } - dispose: function () { + dispose() { this.dispatchEvent( { type: 'dispose' } ); } -} ); - -const _inverseMatrix = new Matrix4(); -const _ray = new Ray(); -const _sphere = new Sphere(); +} -const _vA = new Vector3(); -const _vB = new Vector3(); -const _vC = new Vector3(); +const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); +const _ray$2 = /*@__PURE__*/ new Ray(); +const _sphere$3 = /*@__PURE__*/ new Sphere(); -const _tempA = new Vector3(); -const _tempB = new Vector3(); -const _tempC = new Vector3(); +const _vA$1 = /*@__PURE__*/ new Vector3(); +const _vB$1 = /*@__PURE__*/ new Vector3(); +const _vC$1 = /*@__PURE__*/ new Vector3(); -const _morphA = new Vector3(); -const _morphB = new Vector3(); -const _morphC = new Vector3(); +const _tempA = /*@__PURE__*/ new Vector3(); +const _tempB = /*@__PURE__*/ new Vector3(); +const _tempC = /*@__PURE__*/ new Vector3(); -const _uvA = new Vector2(); -const _uvB = new Vector2(); -const _uvC = new Vector2(); +const _morphA = /*@__PURE__*/ new Vector3(); +const _morphB = /*@__PURE__*/ new Vector3(); +const _morphC = /*@__PURE__*/ new Vector3(); -const _intersectionPoint = new Vector3(); -const _intersectionPointWorld = new Vector3(); +const _uvA$1 = /*@__PURE__*/ new Vector2(); +const _uvB$1 = /*@__PURE__*/ new Vector2(); +const _uvC$1 = /*@__PURE__*/ new Vector2(); -function Mesh( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { +const _intersectionPoint = /*@__PURE__*/ new Vector3(); +const _intersectionPointWorld = /*@__PURE__*/ new Vector3(); - Object3D.call( this ); +class Mesh extends Object3D { - this.type = 'Mesh'; + constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { - this.geometry = geometry; - this.material = material; + super(); - this.updateMorphTargets(); + this.isMesh = true; -} + this.type = 'Mesh'; -Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.geometry = geometry; + this.material = material; - constructor: Mesh, + this.updateMorphTargets(); - isMesh: true, + } - copy: function ( source ) { + copy( source, recursive ) { - Object3D.prototype.copy.call( this, source ); + super.copy( source, recursive ); if ( source.morphTargetInfluences !== undefined ) { @@ -10736,54 +10823,40 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { return this; - }, + } - updateMorphTargets: function () { + updateMorphTargets() { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } - }, + } - raycast: function ( raycaster, intersects ) { + raycast( raycaster, intersects ) { const geometry = this.geometry; const material = this.material; @@ -10795,148 +10868,144 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - _sphere.copy( geometry.boundingSphere ); - _sphere.applyMatrix4( matrixWorld ); + _sphere$3.copy( geometry.boundingSphere ); + _sphere$3.applyMatrix4( matrixWorld ); - if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; + if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; // - _inverseMatrix.copy( matrixWorld ).invert(); - _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); + _inverseMatrix$2.copy( matrixWorld ).invert(); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); // Check boundingBox before continuing if ( geometry.boundingBox !== null ) { - if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return; + if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return; } let intersection; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const position = geometry.attributes.position; - const morphPosition = geometry.morphAttributes.position; - const morphTargetsRelative = geometry.morphTargetsRelative; - const uv = geometry.attributes.uv; - const uv2 = geometry.attributes.uv2; - const groups = geometry.groups; - const drawRange = geometry.drawRange; - - if ( index !== null ) { + const index = geometry.index; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + const uv = geometry.attributes.uv; + const uv2 = geometry.attributes.uv2; + const groups = geometry.groups; + const drawRange = geometry.drawRange; - // indexed buffer geometry + if ( index !== null ) { - if ( Array.isArray( material ) ) { + // indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = index.getX( j ); - const b = index.getX( j + 1 ); - const c = index.getX( j + 2 ); + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); - const b = index.getX( i + 1 ); - const c = index.getX( i + 2 ); + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); } } - } else if ( position !== undefined ) { + } - // non-indexed buffer geometry + } else if ( position !== undefined ) { - if ( Array.isArray( material ) ) { + // non-indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = j; - const b = j + 1; - const c = j + 2; + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = j; + const b = j + 1; + const c = j + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); - const a = i; - const b = i + 1; - const c = i + 2; + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = i; + const b = i + 1; + const c = i + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); } @@ -10944,15 +11013,11 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { } - } else if ( geometry.isGeometry ) { - - console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } -} ); +} function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { @@ -10987,13 +11052,13 @@ function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) { - _vA.fromBufferAttribute( position, a ); - _vB.fromBufferAttribute( position, b ); - _vC.fromBufferAttribute( position, c ); + _vA$1.fromBufferAttribute( position, a ); + _vB$1.fromBufferAttribute( position, b ); + _vC$1.fromBufferAttribute( position, c ); const morphInfluences = object.morphTargetInfluences; - if ( material.morphTargets && morphPosition && morphInfluences ) { + if ( morphPosition && morphInfluences ) { _morphA.set( 0, 0, 0 ); _morphB.set( 0, 0, 0 ); @@ -11018,49 +11083,49 @@ function checkBufferGeometryIntersection( object, material, raycaster, ray, posi } else { - _morphA.addScaledVector( _tempA.sub( _vA ), influence ); - _morphB.addScaledVector( _tempB.sub( _vB ), influence ); - _morphC.addScaledVector( _tempC.sub( _vC ), influence ); + _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence ); + _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence ); + _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence ); } } - _vA.add( _morphA ); - _vB.add( _morphB ); - _vC.add( _morphC ); + _vA$1.add( _morphA ); + _vB$1.add( _morphB ); + _vC$1.add( _morphC ); } - if ( object.isSkinnedMesh && material.skinning ) { + if ( object.isSkinnedMesh ) { - object.boneTransform( a, _vA ); - object.boneTransform( b, _vB ); - object.boneTransform( c, _vC ); + object.boneTransform( a, _vA$1 ); + object.boneTransform( b, _vB$1 ); + object.boneTransform( c, _vC$1 ); } - const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint ); + const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint ); if ( intersection ) { if ( uv ) { - _uvA.fromBufferAttribute( uv, a ); - _uvB.fromBufferAttribute( uv, b ); - _uvC.fromBufferAttribute( uv, c ); + _uvA$1.fromBufferAttribute( uv, a ); + _uvB$1.fromBufferAttribute( uv, b ); + _uvC$1.fromBufferAttribute( uv, c ); - intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); + intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); } if ( uv2 ) { - _uvA.fromBufferAttribute( uv2, a ); - _uvB.fromBufferAttribute( uv2, b ); - _uvC.fromBufferAttribute( uv2, c ); + _uvA$1.fromBufferAttribute( uv2, a ); + _uvB$1.fromBufferAttribute( uv2, b ); + _uvC$1.fromBufferAttribute( uv2, c ); - intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); + intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); } @@ -11072,7 +11137,7 @@ function checkBufferGeometryIntersection( object, material, raycaster, ray, posi materialIndex: 0 }; - Triangle.getNormal( _vA, _vB, _vC, face.normal ); + Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal ); intersection.face = face; @@ -11239,6 +11304,12 @@ class BoxGeometry extends BufferGeometry { } + static fromJSON( data ) { + + return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); + + } + } /** @@ -11302,241 +11373,223 @@ function mergeUniforms( uniforms ) { } -// Legacy +function cloneUniformsGroups( src ) { -const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + const dst = []; -var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + for ( let u = 0; u < src.length; u ++ ) { -var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + dst.push( src[ u ].clone() ); -/** - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + } -function ShaderMaterial( parameters ) { + return dst; - Material.call( this ); +} - this.type = 'ShaderMaterial'; +// Legacy - this.defines = {}; - this.uniforms = {}; +const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; - this.vertexShader = default_vertex; - this.fragmentShader = default_fragment; +var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; - this.linewidth = 1; +var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; - this.wireframe = false; - this.wireframeLinewidth = 1; +class ShaderMaterial extends Material { - 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 + constructor( parameters ) { - 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 + super(); - 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 - }; + this.isShaderMaterial = true; - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [ 1, 1, 1 ], - 'uv': [ 0, 0 ], - 'uv2': [ 0, 0 ] - }; + this.type = 'ShaderMaterial'; - this.index0AttributeName = undefined; - this.uniformsNeedUpdate = false; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; - this.glslVersion = null; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; - if ( parameters !== undefined ) { + this.linewidth = 1; - if ( parameters.attributes !== undefined ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + 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 - } + 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 + }; - this.setValues( parameters ); + // 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; + this.uniformsNeedUpdate = false; -} + this.glslVersion = null; -ShaderMaterial.prototype = Object.create( Material.prototype ); -ShaderMaterial.prototype.constructor = ShaderMaterial; + if ( parameters !== undefined ) { -ShaderMaterial.prototype.isShaderMaterial = true; + this.setValues( parameters ); -ShaderMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + } - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + copy( source ) { - this.uniforms = cloneUniforms( source.uniforms ); + super.copy( source ); - this.defines = Object.assign( {}, source.defines ); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + this.uniforms = cloneUniforms( source.uniforms ); + this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups ); - this.lights = source.lights; - this.clipping = source.clipping; + this.defines = Object.assign( {}, source.defines ); - this.skinning = source.skinning; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; - this.extensions = Object.assign( {}, source.extensions ); + this.extensions = Object.assign( {}, source.extensions ); - this.glslVersion = source.glslVersion; + this.glslVersion = source.glslVersion; - return this; + return this; -}; + } -ShaderMaterial.prototype.toJSON = function ( meta ) { + toJSON( meta ) { - const data = Material.prototype.toJSON.call( this, meta ); + const data = super.toJSON( meta ); - data.glslVersion = this.glslVersion; - data.uniforms = {}; + data.glslVersion = this.glslVersion; + data.uniforms = {}; - for ( const name in this.uniforms ) { + for ( const name in this.uniforms ) { - const uniform = this.uniforms[ name ]; - const value = uniform.value; + const uniform = this.uniforms[ name ]; + const value = uniform.value; - if ( value && value.isTexture ) { + if ( value && value.isTexture ) { - data.uniforms[ name ] = { - type: 't', - value: value.toJSON( meta ).uuid - }; + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; - } else if ( value && value.isColor ) { + } else if ( value && value.isColor ) { - data.uniforms[ name ] = { - type: 'c', - value: value.getHex() - }; + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; - } else if ( value && value.isVector2 ) { + } else if ( value && value.isVector2 ) { - data.uniforms[ name ] = { - type: 'v2', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; - } else if ( value && value.isVector3 ) { + } else if ( value && value.isVector3 ) { - data.uniforms[ name ] = { - type: 'v3', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; - } else if ( value && value.isVector4 ) { + } else if ( value && value.isVector4 ) { - data.uniforms[ name ] = { - type: 'v4', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; - } else if ( value && value.isMatrix3 ) { + } else if ( value && value.isMatrix3 ) { - data.uniforms[ name ] = { - type: 'm3', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; - } else if ( value && value.isMatrix4 ) { + } else if ( value && value.isMatrix4 ) { - data.uniforms[ name ] = { - type: 'm4', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; - } else { + } else { - data.uniforms[ name ] = { - value: value - }; + data.uniforms[ name ] = { + value: value + }; - // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far - } + } - } + } - if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - const extensions = {}; + const extensions = {}; - for ( const key in this.extensions ) { + for ( const key in this.extensions ) { - if ( this.extensions[ key ] === true ) extensions[ key ] = true; + if ( this.extensions[ key ] === true ) extensions[ key ] = true; - } + } - if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; - return data; + return data; -}; + } -function Camera() { +} - Object3D.call( this ); +class Camera extends Object3D { - this.type = 'Camera'; + constructor() { - this.matrixWorldInverse = new Matrix4(); + super(); - this.projectionMatrix = new Matrix4(); - this.projectionMatrixInverse = new Matrix4(); + this.isCamera = true; -} + this.type = 'Camera'; -Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.matrixWorldInverse = new Matrix4(); - constructor: Camera, + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); - isCamera: true, + } - copy: function ( source, recursive ) { + copy( source, recursive ) { - Object3D.prototype.copy.call( this, source, recursive ); + super.copy( source, recursive ); this.matrixWorldInverse.copy( source.matrixWorldInverse ); @@ -11545,16 +11598,9 @@ Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { return this; - }, - - getWorldDirection: function ( target ) { - - if ( target === undefined ) { - - console.warn( 'THREE.Camera: .getWorldDirection() target is now required' ); - target = new Vector3(); + } - } + getWorldDirection( target ) { this.updateWorldMatrix( true, false ); @@ -11562,64 +11608,62 @@ Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); - }, + } - updateMatrixWorld: function ( force ) { + updateMatrixWorld( force ) { - Object3D.prototype.updateMatrixWorld.call( this, force ); + super.updateMatrixWorld( force ); this.matrixWorldInverse.copy( this.matrixWorld ).invert(); - }, + } - updateWorldMatrix: function ( updateParents, updateChildren ) { + updateWorldMatrix( updateParents, updateChildren ) { - Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren ); + super.updateWorldMatrix( updateParents, updateChildren ); this.matrixWorldInverse.copy( this.matrixWorld ).invert(); - }, + } - clone: function () { + clone() { return new this.constructor().copy( this ); } -} ); - -function PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { +} - Camera.call( this ); +class PerspectiveCamera extends Camera { - this.type = 'PerspectiveCamera'; + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { - this.fov = fov; - this.zoom = 1; + super(); - this.near = near; - this.far = far; - this.focus = 10; + this.isPerspectiveCamera = true; - this.aspect = aspect; - this.view = null; + this.type = 'PerspectiveCamera'; - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + this.fov = fov; + this.zoom = 1; - this.updateProjectionMatrix(); + this.near = near; + this.far = far; + this.focus = 10; -} + this.aspect = aspect; + this.view = null; -PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - constructor: PerspectiveCamera, + this.updateProjectionMatrix(); - isPerspectiveCamera: true, + } - copy: function ( source, recursive ) { + copy( source, recursive ) { - Camera.prototype.copy.call( this, source, recursive ); + super.copy( source, recursive ); this.fov = source.fov; this.zoom = source.zoom; @@ -11636,7 +11680,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), return this; - }, + } /** * Sets the FOV by focal length in respect to the current .filmGauge. @@ -11646,47 +11690,47 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), * * Values for focal length and film gauge must have the same unit. */ - setFocalLength: function ( focalLength ) { + setFocalLength( focalLength ) { /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); this.updateProjectionMatrix(); - }, + } /** * Calculates the focal length from the current .fov and .filmGauge. */ - getFocalLength: function () { + getFocalLength() { - const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ); + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); return 0.5 * this.getFilmHeight() / vExtentSlope; - }, + } - getEffectiveFOV: function () { + getEffectiveFOV() { - return MathUtils.RAD2DEG * 2 * Math.atan( - Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); - }, + } - getFilmWidth: function () { + getFilmWidth() { // film not completely covered in portrait format (aspect < 1) return this.filmGauge * Math.min( this.aspect, 1 ); - }, + } - getFilmHeight: function () { + getFilmHeight() { // film not completely covered in landscape format (aspect > 1) return this.filmGauge / Math.max( this.aspect, 1 ); - }, + } /** * Sets an offset in a larger frustum. This is useful for multi-window or @@ -11723,7 +11767,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), * * Note there is no reason monitors have to be the same size or in a grid. */ - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { this.aspect = fullWidth / fullHeight; @@ -11751,9 +11795,9 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), this.updateProjectionMatrix(); - }, + } - clearViewOffset: function () { + clearViewOffset() { if ( this.view !== null ) { @@ -11763,12 +11807,12 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), this.updateProjectionMatrix(); - }, + } - updateProjectionMatrix: function () { + updateProjectionMatrix() { const near = this.near; - let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom; + let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom; let height = 2 * top; let width = this.aspect * height; let left = - 0.5 * width; @@ -11793,11 +11837,11 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); - }, + } - toJSON: function ( meta ) { + toJSON( meta ) { - const data = Object3D.prototype.toJSON.call( this, meta ); + const data = super.toJSON( meta ); data.object.fov = this.fov; data.object.zoom = this.zoom; @@ -11817,7 +11861,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), } -} ); +} const fov = 90, aspect = 1; @@ -11829,13 +11873,6 @@ class CubeCamera extends Object3D { this.type = 'CubeCamera'; - if ( renderTarget.isWebGLCubeRenderTarget !== true ) { - - console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' ); - return; - - } - this.renderTarget = renderTarget; const cameraPX = new PerspectiveCamera( fov, aspect, near, far ); @@ -11884,9 +11921,12 @@ class CubeCamera extends Object3D { const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children; - const currentXrEnabled = renderer.xr.enabled; const currentRenderTarget = renderer.getRenderTarget(); + const currentToneMapping = renderer.toneMapping; + const currentXrEnabled = renderer.xr.enabled; + + renderer.toneMapping = NoToneMapping; renderer.xr.enabled = false; const generateMipmaps = renderTarget.texture.generateMipmaps; @@ -11915,8 +11955,11 @@ class CubeCamera extends Object3D { renderer.setRenderTarget( currentRenderTarget ); + renderer.toneMapping = currentToneMapping; renderer.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } } @@ -11927,21 +11970,10 @@ class CubeTexture extends Texture { images = images !== undefined ? images : []; mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - format = format !== undefined ? format : RGBFormat; super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - // Why CubeTexture._needsFlipEnvMap is necessary: - // - // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) - // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, - // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. - - // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped - // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false) - // when using WebGLCubeRenderTarget.texture as a cube texture. - - this._needsFlipEnvMap = true; + this.isCubeTexture = true; this.flipY = false; @@ -11961,37 +11993,37 @@ class CubeTexture extends Texture { } -CubeTexture.prototype.isCubeTexture = true; - class WebGLCubeRenderTarget extends WebGLRenderTarget { - constructor( size, options, dummy ) { + constructor( size, options = {} ) { - if ( Number.isInteger( options ) ) { + super( size, size, options ); - console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' ); + this.isWebGLCubeRenderTarget = true; - options = dummy; + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; - } + this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - super( size, size, options ); + // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) + // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, + // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. - options = options || {}; + // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped + // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture + // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). - this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture.isRenderTargetTexture = true; this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; - this.texture._needsFlipEnvMap = false; - } fromEquirectangularTexture( renderer, texture ) { this.texture.type = texture.type; - this.texture.format = RGBAFormat; // see #18859 this.texture.encoding = texture.encoding; this.texture.generateMipmaps = texture.generateMipmaps; @@ -12097,33 +12129,209 @@ class WebGLCubeRenderTarget extends WebGLRenderTarget { } -WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true; +const _vector1 = /*@__PURE__*/ new Vector3(); +const _vector2 = /*@__PURE__*/ new Vector3(); +const _normalMatrix = /*@__PURE__*/ new Matrix3(); -class DataTexture extends Texture { +class Plane { - constructor( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { - super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isPlane = true; - this.image = { data: data || null, width: width || 1, height: height || 1 }; + // normal is assumed to be normalized - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + this.normal = normal; + this.constant = constant; - this.generateMipmaps = false; - this.flipY = false; - this.unpackAlignment = 1; + } - this.needsUpdate = true; + set( normal, constant ) { + + this.normal.copy( normal ); + this.constant = constant; + + return this; } -} + setComponents( x, y, z, w ) { + + this.normal.set( x, y, z ); + this.constant = w; -DataTexture.prototype.isDataTexture = true; + return this; -const _sphere$1 = /*@__PURE__*/ new Sphere(); -const _vector$5 = /*@__PURE__*/ new Vector3(); + } + + setFromNormalAndCoplanarPoint( normal, point ) { + + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); + + return this; + + } + + setFromCoplanarPoints( a, b, c ) { + + const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); + + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + + this.setFromNormalAndCoplanarPoint( normal, a ); + + return this; + + } + + copy( plane ) { + + this.normal.copy( plane.normal ); + this.constant = plane.constant; + + return this; + + } + + normalize() { + + // Note: will lead to a divide by zero if the plane is invalid. + + const inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; + + return this; + + } + + negate() { + + this.constant *= - 1; + this.normal.negate(); + + return this; + + } + + distanceToPoint( point ) { + + return this.normal.dot( point ) + this.constant; + + } + + distanceToSphere( sphere ) { + + return this.distanceToPoint( sphere.center ) - sphere.radius; + + } + + projectPoint( point, target ) { + + return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + + } + + intersectLine( line, target ) { + + const direction = line.delta( _vector1 ); + + const denominator = this.normal.dot( direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { + + return target.copy( line.start ); + + } + + // Unsure if this is the correct method to handle this case. + return null; + + } + + const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + + if ( t < 0 || t > 1 ) { + + return null; + + } + + return target.copy( direction ).multiplyScalar( t ).add( line.start ); + + } + + intersectsLine( line ) { + + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + + const startSign = this.distanceToPoint( line.start ); + const endSign = this.distanceToPoint( line.end ); + + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + + } + + intersectsBox( box ) { + + return box.intersectsPlane( this ); + + } + + intersectsSphere( sphere ) { + + return sphere.intersectsPlane( this ); + + } + + coplanarPoint( target ) { + + return target.copy( this.normal ).multiplyScalar( - this.constant ); + + } + + applyMatrix4( matrix, optionalNormalMatrix ) { + + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + + const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + + const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + + this.constant = - referencePoint.dot( normal ); + + return this; + + } + + translate( offset ) { + + this.constant -= offset.dot( this.normal ); + + return this; + + } + + equals( plane ) { + + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _sphere$2 = /*@__PURE__*/ new Sphere(); +const _vector$7 = /*@__PURE__*/ new Vector3(); class Frustum { @@ -12188,19 +12396,19 @@ class Frustum { if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); + _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); - return this.intersectsSphere( _sphere$1 ); + return this.intersectsSphere( _sphere$2 ); } intersectsSprite( sprite ) { - _sphere$1.center.set( 0, 0, 0 ); - _sphere$1.radius = 0.7071067811865476; - _sphere$1.applyMatrix4( sprite.matrixWorld ); + _sphere$2.center.set( 0, 0, 0 ); + _sphere$2.radius = 0.7071067811865476; + _sphere$2.applyMatrix4( sprite.matrixWorld ); - return this.intersectsSphere( _sphere$1 ); + return this.intersectsSphere( _sphere$2 ); } @@ -12236,11 +12444,11 @@ class Frustum { // corner at max distance - _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x; - _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y; - _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z; + _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z; - if ( plane.distanceToPoint( _vector$5 ) < 0 ) { + if ( plane.distanceToPoint( _vector$7 ) < 0 ) { return false; @@ -12348,16 +12556,12 @@ function WebGLAttributes( gl, capabilities ) { attribute.onUploadCallback(); - let type = 5126; + let type; if ( array instanceof Float32Array ) { type = 5126; - } else if ( array instanceof Float64Array ) { - - console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' ); - } else if ( array instanceof Uint16Array ) { if ( attribute.isFloat16BufferAttribute ) { @@ -12368,7 +12572,7 @@ function WebGLAttributes( gl, capabilities ) { } else { - console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); + throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); } @@ -12398,6 +12602,14 @@ function WebGLAttributes( gl, capabilities ) { type = 5121; + } else if ( array instanceof Uint8ClampedArray ) { + + type = 5121; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); + } return { @@ -12522,6 +12734,7 @@ class PlaneGeometry extends BufferGeometry { constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) { super(); + this.type = 'PlaneGeometry'; this.parameters = { @@ -12592,15 +12805,23 @@ class PlaneGeometry extends BufferGeometry { } + static fromJSON( data ) { + + return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); + + } + } var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; -var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif"; +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; -var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif"; +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; @@ -12608,9 +12829,11 @@ var begin_vertex = "vec3 transformed = vec3( position );"; var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; -var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn 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\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif"; +var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; -var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; @@ -12620,17 +12843,17 @@ var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 v var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; -var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; +var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; -var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; +var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; -var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; +var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; -var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; +var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; -var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(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\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; -var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; @@ -12638,59 +12861,61 @@ var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; -var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; -var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn 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.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn 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\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn 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\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}"; +var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}"; -var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; -var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; -var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; -var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; -var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif"; +var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; -var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif"; +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; -var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; -var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; -var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}"; +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; -var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif"; +var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; -var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif"; +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert\n#define Material_LightProbeLOD( material )\t(0)"; -var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif"; +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; -var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif"; +var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif"; var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; -var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)"; +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)"; var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; -var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\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}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; -var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif"; +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; -var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\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\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; -var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; -var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif"; +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; @@ -12702,11 +12927,11 @@ var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_ var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; -var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif"; +var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; -var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; @@ -12714,25 +12939,37 @@ var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_META var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; -var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif"; +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; -var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; -var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif"; +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\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#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; -var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; +var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + +var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; -var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; +var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; -var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; +var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\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\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; + +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif"; var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; -var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + +var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; @@ -12746,17 +12983,17 @@ var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUG var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; -var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\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\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\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\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; -var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; -var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif"; +var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif"; -var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; var skinbase_vertex = "#ifdef USE_SKINNING\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#endif"; -var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\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\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif"; +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; @@ -12768,11 +13005,11 @@ var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D spe var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; -var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; -var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif"; +var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif"; -var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif"; +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif"; var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; @@ -12786,81 +13023,83 @@ var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tat var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; -var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; -var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; +const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; -var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; +const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include \n\t#include \n}"; -var cube_frag = "#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; +const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; -var cube_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; +const fragment$f = "#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; -var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; +const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; -var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; +const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; -var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; +const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; -var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; +const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; -var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; +const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; -var equirect_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; +const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; -var 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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}"; -var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\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}"; -var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\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}"; +const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\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 \nvoid main() {\n\t#include \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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\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 \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying 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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; -var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\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\tvViewPosition = - mvPosition.xyz;\n}"; +const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; -var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying 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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; +const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; -var 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 \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying 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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$6 = "#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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; -var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}"; +const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; -var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; +const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; +const vertex$2 = "#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n}"; -var shadow_vert = "#include \n#include \n#include \nvoid main() {\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}"; +const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; -var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n}"; +const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; -var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; +const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; const ShaderChunk = { alphamap_fragment: alphamap_fragment, alphamap_pars_fragment: alphamap_pars_fragment, alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, aomap_fragment: aomap_fragment, aomap_pars_fragment: aomap_pars_fragment, begin_vertex: begin_vertex, beginnormal_vertex: beginnormal_vertex, bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, bumpmap_pars_fragment: bumpmap_pars_fragment, clipping_planes_fragment: clipping_planes_fragment, clipping_planes_pars_fragment: clipping_planes_pars_fragment, @@ -12892,7 +13131,8 @@ const ShaderChunk = { gradientmap_pars_fragment: gradientmap_pars_fragment, lightmap_fragment: lightmap_fragment, lightmap_pars_fragment: lightmap_pars_fragment, - lights_lambert_vertex: lights_lambert_vertex, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, lights_pars_begin: lights_pars_begin, lights_toon_fragment: lights_toon_fragment, lights_toon_pars_fragment: lights_toon_pars_fragment, @@ -12913,15 +13153,21 @@ const ShaderChunk = { map_particle_pars_fragment: map_particle_pars_fragment, metalnessmap_fragment: metalnessmap_fragment, metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphcolor_vertex: morphcolor_vertex, morphnormal_vertex: morphnormal_vertex, morphtarget_pars_vertex: morphtarget_pars_vertex, morphtarget_vertex: morphtarget_vertex, normal_fragment_begin: normal_fragment_begin, normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, normalmap_pars_fragment: normalmap_pars_fragment, clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + output_fragment: output_fragment, packing: packing, premultiplied_alpha_fragment: premultiplied_alpha_fragment, project_vertex: project_vertex, @@ -12941,8 +13187,8 @@ const ShaderChunk = { specularmap_pars_fragment: specularmap_pars_fragment, tonemapping_fragment: tonemapping_fragment, tonemapping_pars_fragment: tonemapping_pars_fragment, - transmissionmap_fragment: transmissionmap_fragment, - transmissionmap_pars_fragment: transmissionmap_pars_fragment, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_pars_fragment, uv_pars_fragment: uv_pars_fragment, uv_pars_vertex: uv_pars_vertex, uv_vertex: uv_vertex, @@ -12951,38 +13197,38 @@ const ShaderChunk = { uv2_vertex: uv2_vertex, worldpos_vertex: worldpos_vertex, - background_frag: background_frag, - background_vert: background_vert, - 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, - meshmatcap_frag: meshmatcap_frag, - meshmatcap_vert: meshmatcap_vert, - meshtoon_frag: meshtoon_frag, - meshtoon_vert: meshtoon_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, - sprite_frag: sprite_frag, - sprite_vert: sprite_vert + background_vert: vertex$g, + background_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 }; /** @@ -12993,14 +13239,15 @@ const UniformsLib = { common: { - diffuse: { value: new Color( 0xeeeeee ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, map: { value: null }, - uvTransform: { value: new Matrix3() }, - uv2Transform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + uv2Transform: { value: /*@__PURE__*/ new Matrix3() }, alphaMap: { value: null }, + alphaTest: { value: 0 } }, @@ -13014,9 +13261,9 @@ const UniformsLib = { envMap: { value: null }, flipEnvMap: { value: - 1 }, - reflectivity: { value: 1.0 }, - refractionRatio: { value: 0.98 }, - maxMipLevel: { value: 0 } + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 } // basic, lambert, phong }, @@ -13050,7 +13297,7 @@ const UniformsLib = { normalmap: { normalMap: { value: null }, - normalScale: { value: new Vector2( 1, 1 ) } + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } }, @@ -13085,7 +13332,7 @@ const UniformsLib = { fogDensity: { value: 0.00025 }, fogNear: { value: 1 }, fogFar: { value: 2000 }, - fogColor: { value: new Color( 0xffffff ) } + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } }, @@ -13127,8 +13374,9 @@ const UniformsLib = { shadowMapSize: {} } }, + spotLightMap: { value: [] }, spotShadowMap: { value: [] }, - spotShadowMatrix: { value: [] }, + spotLightMatrix: { value: [] }, pointLights: { value: [], properties: { color: {}, @@ -13170,25 +13418,27 @@ const UniformsLib = { points: { - diffuse: { value: new Color( 0xeeeeee ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, size: { value: 1.0 }, scale: { value: 1.0 }, map: { value: null }, alphaMap: { value: null }, - uvTransform: { value: new Matrix3() } + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } }, sprite: { - diffuse: { value: new Color( 0xeeeeee ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, - center: { value: new Vector2( 0.5, 0.5 ) }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, rotation: { value: 0.0 }, map: { value: null }, alphaMap: { value: null }, - uvTransform: { value: new Matrix3() } + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } } @@ -13198,7 +13448,7 @@ const ShaderLib = { basic: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13214,17 +13464,20 @@ const ShaderLib = { lambert: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13235,7 +13488,7 @@ const ShaderLib = { phong: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13248,8 +13501,8 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, - specular: { value: new Color( 0x111111 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, shininess: { value: 30 } } ] ), @@ -13261,7 +13514,7 @@ const ShaderLib = { standard: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, @@ -13275,7 +13528,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, roughness: { value: 1.0 }, metalness: { value: 0.0 }, envMapIntensity: { value: 1 } // temporary @@ -13289,7 +13542,7 @@ const ShaderLib = { toon: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, @@ -13301,7 +13554,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13312,7 +13565,7 @@ const ShaderLib = { matcap: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -13330,7 +13583,7 @@ const ShaderLib = { points: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.points, UniformsLib.fog ] ), @@ -13342,7 +13595,7 @@ const ShaderLib = { dashed: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.fog, { @@ -13359,7 +13612,7 @@ const ShaderLib = { depth: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap ] ), @@ -13371,7 +13624,7 @@ const ShaderLib = { normal: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -13381,14 +13634,14 @@ const ShaderLib = { } ] ), - vertexShader: ShaderChunk.normal_vert, - fragmentShader: ShaderChunk.normal_frag + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag }, sprite: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.sprite, UniformsLib.fog ] ), @@ -13401,7 +13654,7 @@ const ShaderLib = { background: { uniforms: { - uvTransform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, t2D: { value: null }, }, @@ -13409,13 +13662,10 @@ const ShaderLib = { fragmentShader: ShaderChunk.background_frag }, - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ cube: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.envmap, { opacity: { value: 1.0 } @@ -13440,11 +13690,11 @@ const ShaderLib = { distanceRGBA: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap, { - referencePosition: { value: new Vector3() }, + referencePosition: { value: /*@__PURE__*/ new Vector3() }, nearDistance: { value: 1 }, farDistance: { value: 1000 } } @@ -13457,11 +13707,11 @@ const ShaderLib = { shadow: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.lights, UniformsLib.fog, { - color: { value: new Color( 0x00000 ) }, + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, opacity: { value: 1.0 } }, ] ), @@ -13475,18 +13725,38 @@ const ShaderLib = { ShaderLib.physical = { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ ShaderLib.standard.uniforms, { clearcoat: { value: 0 }, clearcoatMap: { value: null }, clearcoatRoughness: { value: 0 }, clearcoatRoughnessMap: { value: null }, - clearcoatNormalScale: { value: new Vector2( 1, 1 ) }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, clearcoatNormalMap: { value: null }, - sheen: { value: new Color( 0x000000 ) }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, transmission: { value: 0 }, transmissionMap: { value: null }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, } ] ), @@ -13495,10 +13765,10 @@ ShaderLib.physical = { }; -function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) { +function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) { const clearColor = new Color( 0x000000 ); - let clearAlpha = 0; + let clearAlpha = alpha === true ? 0 : 1; let planeMesh; let boxMesh; @@ -13507,8 +13777,9 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha let currentBackgroundVersion = 0; let currentTonemapping = null; - function render( renderList, scene, camera, forceClear ) { + function render( renderList, scene ) { + let forceClear = false; let background = scene.isScene === true ? scene.background : null; if ( background && background.isTexture ) { @@ -13546,7 +13817,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } - if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) { + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { if ( boxMesh === undefined ) { @@ -13573,7 +13844,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha }; - // enable code injection for non-built-in material + // add "envMap" material property so the renderer can evaluate it like for built-in materials Object.defineProperty( boxMesh.material, 'envMap', { get: function () { @@ -13588,16 +13859,8 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } - if ( background.isWebGLCubeRenderTarget ) { - - // TODO Deprecate - - background = background.texture; - - } - boxMesh.material.uniforms.envMap.value = background; - boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1; + boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; if ( currentBackground !== background || currentBackgroundVersion !== background.version || @@ -13611,6 +13874,8 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } + boxMesh.layers.enableAll(); + // push to the pre-sorted opaque render list renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); @@ -13634,7 +13899,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha planeMesh.geometry.deleteAttribute( 'normal' ); - // enable code injection for non-built-in material + // add "map" material property so the renderer can evaluate it like for built-in materials Object.defineProperty( planeMesh.material, 'map', { get: function () { @@ -13671,6 +13936,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } + planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); @@ -13727,6 +13993,7 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { const defaultState = createBindingState( null ); let currentState = defaultState; + let forceUpdate = false; function setup( object, material, program, geometry, index ) { @@ -13743,9 +14010,9 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - updateBuffers = needsUpdate( geometry, index ); + updateBuffers = needsUpdate( object, geometry, program, index ); - if ( updateBuffers ) saveCache( geometry, index ); + if ( updateBuffers ) saveCache( object, geometry, program, index ); } else { @@ -13765,19 +14032,15 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - if ( object.isInstancedMesh === true ) { - - updateBuffers = true; - - } - if ( index !== null ) { attributes.update( index, 34963 ); } - if ( updateBuffers ) { + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; setupVertexAttributes( object, material, program, geometry ); @@ -13882,25 +14145,40 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function needsUpdate( geometry, index ) { + function needsUpdate( object, geometry, program, index ) { const cachedAttributes = currentState.attributes; const geometryAttributes = geometry.attributes; let attributesNum = 0; - for ( const key in geometryAttributes ) { + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } - const cachedAttribute = cachedAttributes[ key ]; - const geometryAttribute = geometryAttributes[ key ]; + if ( cachedAttribute === undefined ) return true; - if ( cachedAttribute === undefined ) return true; + if ( cachedAttribute.attribute !== geometryAttribute ) return true; - if ( cachedAttribute.attribute !== geometryAttribute ) return true; + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; - if ( cachedAttribute.data !== geometryAttribute.data ) return true; + attributesNum ++; - attributesNum ++; + } } @@ -13912,28 +14190,43 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function saveCache( geometry, index ) { + function saveCache( object, geometry, program, index ) { const cache = {}; const attributes = geometry.attributes; let attributesNum = 0; - for ( const key in attributes ) { + const programAttributes = program.getAttributes(); - const attribute = attributes[ key ]; + for ( const name in programAttributes ) { - const data = {}; - data.attribute = attribute; + const programAttribute = programAttributes[ name ]; - if ( attribute.data ) { + if ( programAttribute.location >= 0 ) { - data.data = attribute.data; + let attribute = attributes[ name ]; - } + if ( attribute === undefined ) { - cache[ key ] = data; + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; - attributesNum ++; + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } } @@ -14040,9 +14333,16 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { const programAttribute = programAttributes[ name ]; - if ( programAttribute >= 0 ) { + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { - const geometryAttribute = geometryAttributes[ name ]; + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } if ( geometryAttribute !== undefined ) { @@ -14065,87 +14365,87 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { const stride = data.stride; const offset = geometryAttribute.offset; - if ( data && data.isInstancedInterleavedBuffer ) { + if ( data.isInstancedInterleavedBuffer ) { - enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - if ( geometry._maxInstanceCount === undefined ) { - - geometry._maxInstanceCount = data.meshPerAttribute * data.count; + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); } - } else { - - enableAttribute( programAttribute ); + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { - } + geometry._maxInstanceCount = data.meshPerAttribute * data.count; - gl.bindBuffer( 34962, buffer ); - vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement ); + } - } else { + } else { - if ( geometryAttribute.isInstancedBufferAttribute ) { + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); + enableAttribute( programAttribute.location + i ); - if ( geometry._maxInstanceCount === undefined ) { + } - geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } - } + gl.bindBuffer( 34962, buffer ); - } else { + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - enableAttribute( programAttribute ); + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement + ); } - gl.bindBuffer( 34962, buffer ); - vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 ); + } else { - } + if ( geometryAttribute.isInstancedBufferAttribute ) { - } else if ( name === 'instanceMatrix' ) { + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - const attribute = attributes.get( object.instanceMatrix ); + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); - // TODO Attribute may not be available on context restore + } - if ( attribute === undefined ) continue; + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { - const buffer = attribute.buffer; - const type = attribute.type; + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - enableAttributeAndDivisor( programAttribute + 0, 1 ); - enableAttributeAndDivisor( programAttribute + 1, 1 ); - enableAttributeAndDivisor( programAttribute + 2, 1 ); - enableAttributeAndDivisor( programAttribute + 3, 1 ); + } - gl.bindBuffer( 34962, buffer ); + } else { - gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 ); - gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 ); - gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 ); - gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 ); + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - } else if ( name === 'instanceColor' ) { + enableAttribute( programAttribute.location + i ); - const attribute = attributes.get( object.instanceColor ); + } - // TODO Attribute may not be available on context restore + } - if ( attribute === undefined ) continue; + gl.bindBuffer( 34962, buffer ); - const buffer = attribute.buffer; - const type = attribute.type; + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - enableAttributeAndDivisor( programAttribute, 1 ); + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement + ); - gl.bindBuffer( 34962, buffer ); + } - gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 ); + } } else if ( materialDefaultAttributeValues !== undefined ) { @@ -14156,19 +14456,19 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { switch ( value.length ) { case 2: - gl.vertexAttrib2fv( programAttribute, value ); + gl.vertexAttrib2fv( programAttribute.location, value ); break; case 3: - gl.vertexAttrib3fv( programAttribute, value ); + gl.vertexAttrib3fv( programAttribute.location, value ); break; case 4: - gl.vertexAttrib4fv( programAttribute, value ); + gl.vertexAttrib4fv( programAttribute.location, value ); break; default: - gl.vertexAttrib1fv( programAttribute, value ); + gl.vertexAttrib1fv( programAttribute.location, value ); } @@ -14267,6 +14567,7 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { function reset() { resetDefaultState(); + forceUpdate = true; if ( currentState === defaultState ) return; @@ -14275,7 +14576,7 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - // for backward-compatilibity + // for backward-compatibility function resetDefaultState() { @@ -14415,10 +14716,8 @@ function WebGLCapabilities( gl, extensions, parameters ) { } - /* eslint-disable no-undef */ const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) || ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext ); - /* eslint-enable no-undef */ let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; const maxPrecision = getMaxPrecision( precision ); @@ -14430,6 +14729,8 @@ function WebGLCapabilities( gl, extensions, parameters ) { } + const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ); + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; const maxTextures = gl.getParameter( 34930 ); @@ -14452,6 +14753,8 @@ function WebGLCapabilities( gl, extensions, parameters ) { isWebGL2: isWebGL2, + drawBuffers: drawBuffers, + getMaxAnisotropy: getMaxAnisotropy, getMaxPrecision: getMaxPrecision, @@ -14662,7 +14965,7 @@ function WebGLCubeMaps( renderer ) { function get( texture ) { - if ( texture && texture.isTexture ) { + if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) { const mapping = texture.mapping; @@ -14679,14 +14982,10 @@ function WebGLCubeMaps( renderer ) { if ( image && image.height > 0 ) { - const currentRenderTarget = renderer.getRenderTarget(); - const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); renderTarget.fromEquirectangularTexture( renderer, texture ); cubemaps.set( texture, renderTarget ); - renderer.setRenderTarget( currentRenderTarget ); - texture.addEventListener( 'dispose', onTextureDispose ); return mapTextureMapping( renderTarget.texture, texture.mapping ); @@ -14739,3135 +15038,4809 @@ function WebGLCubeMaps( renderer ) { } -function WebGLExtensions( gl ) { - - const extensions = {}; +class OrthographicCamera extends Camera { - function getExtension( name ) { + constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { - if ( extensions[ name ] !== undefined ) { + super(); - return extensions[ name ]; + this.isOrthographicCamera = true; - } + this.type = 'OrthographicCamera'; - let extension; + this.zoom = 1; + this.view = null; - switch ( name ) { + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; + this.near = near; + this.far = far; - 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; + this.updateProjectionMatrix(); - 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; + copy( source, recursive ) { - default: - extension = gl.getExtension( name ); + super.copy( source, recursive ); - } + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - extensions[ name ] = extension; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - return extension; + return this; } - return { + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { - has: function ( name ) { + if ( this.view === null ) { - return getExtension( name ) !== null; + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; - }, + } - init: function ( capabilities ) { + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; - if ( capabilities.isWebGL2 ) { + this.updateProjectionMatrix(); - getExtension( 'EXT_color_buffer_float' ); + } - } else { + clearViewOffset() { - getExtension( 'WEBGL_depth_texture' ); - getExtension( 'OES_texture_float' ); - getExtension( 'OES_texture_half_float' ); - getExtension( 'OES_texture_half_float_linear' ); - getExtension( 'OES_standard_derivatives' ); - getExtension( 'OES_element_index_uint' ); - getExtension( 'OES_vertex_array_object' ); - getExtension( 'ANGLE_instanced_arrays' ); + if ( this.view !== null ) { - } + this.view.enabled = false; - getExtension( 'OES_texture_float_linear' ); - getExtension( 'EXT_color_buffer_half_float' ); + } - }, + this.updateProjectionMatrix(); - get: function ( name ) { + } - const extension = getExtension( name ); + updateProjectionMatrix() { - if ( extension === null ) { + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; - } + if ( this.view !== null && this.view.enabled ) { - return extension; + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; - } + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; - }; + } -} + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); -function WebGLGeometries( gl, attributes, info, bindingStates ) { + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); - const geometries = {}; - const wireframeAttributes = new WeakMap(); + } - function onGeometryDispose( event ) { + toJSON( meta ) { - const geometry = event.target; + const data = super.toJSON( meta ); - if ( geometry.index !== null ) { + 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; - attributes.remove( geometry.index ); + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - } + return data; - for ( const name in geometry.attributes ) { + } - attributes.remove( geometry.attributes[ name ] ); +} - } +const LOD_MIN = 4; - geometry.removeEventListener( 'dispose', onGeometryDispose ); +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; - delete geometries[ geometry.id ]; +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; - const attribute = wireframeAttributes.get( geometry ); +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; - if ( attribute ) { +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; - attributes.remove( attribute ); - wireframeAttributes.delete( geometry ); +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( 1, 1, 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; - } +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view +*/ - bindingStates.releaseStatesOfGeometry( geometry ); +class PMREMGenerator { - if ( geometry.isInstancedBufferGeometry === true ) { + constructor( renderer ) { - delete geometry._maxInstanceCount; + this._renderer = renderer; + this._pingPongRenderTarget = null; - } + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; - // + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; - info.memory.geometries --; + this._compileMaterial( this._blurMaterial ); } - function get( object, geometry ) { + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { - if ( geometries[ geometry.id ] === true ) return geometry; + _oldTarget = this._renderer.getRenderTarget(); - geometry.addEventListener( 'dispose', onGeometryDispose ); + this._setSize( 256 ); - geometries[ geometry.id ] = true; + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; - info.memory.geometries ++; + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); - return geometry; + if ( sigma > 0 ) { - } + this._blur( cubeUVRenderTarget, 0, 0, sigma ); - function update( geometry ) { + } - const geometryAttributes = geometry.attributes; + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - // Updating index buffer in VAO now. See WebGLBindingStates. + return cubeUVRenderTarget; - for ( const name in geometryAttributes ) { + } - attributes.update( geometryAttributes[ name ], 34962 ); + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { - } + return this._fromTexture( equirectangular, renderTarget ); - // morph targets + } - const morphAttributes = geometry.morphAttributes; + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { - for ( const name in morphAttributes ) { + return this._fromTexture( cubemap, renderTarget ); - const array = morphAttributes[ name ]; + } - for ( let i = 0, l = array.length; i < l; i ++ ) { + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { - attributes.update( array[ i ], 34962 ); + if ( this._cubemapMaterial === null ) { - } + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); } } - function updateWireframeAttribute( geometry ) { - - const indices = []; + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { - const geometryIndex = geometry.index; - const geometryPosition = geometry.attributes.position; - let version = 0; + if ( this._equirectMaterial === null ) { - if ( geometryIndex !== null ) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); - const array = geometryIndex.array; - version = geometryIndex.version; + } - for ( let i = 0, l = array.length; i < l; i += 3 ) { + } - const a = array[ i + 0 ]; - const b = array[ i + 1 ]; - const c = array[ i + 2 ]; + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { - indices.push( a, b, b, c, c, a ); + this._dispose(); - } + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); - } else { + } - const array = geometryPosition.array; - version = geometryPosition.version; + // private interface - for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + _setSize( cubeSize ) { - const a = i + 0; - const b = i + 1; - const c = i + 2; + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); - indices.push( a, b, b, c, c, a ); + } - } + _dispose() { - } + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); - const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); - attribute.version = version; + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); - // Updating index buffer in VAO now. See WebGLBindingStates + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { - // + this._lodPlanes[ i ].dispose(); - const previousAttribute = wireframeAttributes.get( geometry ); + } - if ( previousAttribute ) attributes.remove( previousAttribute ); + } - // + _cleanup( outputTarget ) { - wireframeAttributes.set( geometry, attribute ); + this._renderer.setRenderTarget( _oldTarget ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); } - function getWireframeAttribute( geometry ) { - - const currentAttribute = wireframeAttributes.get( geometry ); - - if ( currentAttribute ) { + _fromTexture( texture, renderTarget ) { - const geometryIndex = geometry.index; + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { - if ( geometryIndex !== null ) { + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); - // if the attribute is obsolete, create a new one + } else { // Equirectangular - if ( currentAttribute.version < geometryIndex.version ) { + this._setSize( texture.image.width / 4 ); - updateWireframeAttribute( geometry ); + } - } + _oldTarget = this._renderer.getRenderTarget(); - } + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - } else { + return cubeUVRenderTarget; - updateWireframeAttribute( geometry ); + } - } + _allocateTargets() { - return wireframeAttributes.get( geometry ); + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; - } + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + encoding: LinearEncoding, + depthBuffer: false + }; - return { + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); - get: get, - update: update, + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width ) { - getWireframeAttribute: getWireframeAttribute + if ( this._pingPongRenderTarget !== null ) { - }; + this._dispose(); -} + } -function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); - const isWebGL2 = capabilities.isWebGL2; + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) ); - let mode; + this._blurMaterial = _getBlurShader( _lodMax, width, height ); - function setMode( value ) { + } - mode = value; + return cubeUVRenderTarget; } - let type, bytesPerElement; - - function setIndex( value ) { + _compileMaterial( material ) { - type = value.type; - bytesPerElement = value.bytesPerElement; + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); } - function render( start, count ) { - - gl.drawElements( mode, count, type, start * bytesPerElement ); + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { - info.update( count, mode, 1 ); + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, - 1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; + const renderer = this._renderer; - } + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); - function renderInstances( start, count, primcount ) { + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; - if ( primcount === 0 ) return; + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ); - let extension, methodName; + const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); - if ( isWebGL2 ) { + let useSolidColor = false; + const background = scene.background; - extension = gl; - methodName = 'drawElementsInstanced'; + if ( background ) { - } else { + if ( background.isColor ) { - extension = extensions.get( 'ANGLE_instanced_arrays' ); - methodName = 'drawElementsInstancedANGLE'; + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; - if ( extension === null ) { + } - console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + } else { - } + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; } - extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); + for ( let i = 0; i < 6; i ++ ) { - info.update( count, mode, primcount ); + const col = i % 3; - } + if ( col === 0 ) { - // + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + } else if ( col === 1 ) { -} + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); -function WebGLInfo( gl ) { + } else { - const memory = { - geometries: 0, - textures: 0 - }; - - const render = { - frame: 0, - calls: 0, - triangles: 0, - points: 0, - lines: 0 - }; - - function update( count, mode, instanceCount ) { + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); - render.calls ++; + } - switch ( mode ) { + const size = this._cubeSize; - case 4: - render.triangles += instanceCount * ( count / 3 ); - break; + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); - case 1: - render.lines += instanceCount * ( count / 2 ); - break; + renderer.setRenderTarget( cubeUVRenderTarget ); - case 3: - render.lines += instanceCount * ( count - 1 ); - break; + if ( useSolidColor ) { - case 2: - render.lines += instanceCount * count; - break; + renderer.render( backgroundBox, cubeCamera ); - case 0: - render.points += instanceCount * count; - break; + } - default: - console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); - break; + renderer.render( scene, cubeCamera ); } - } - - function reset() { + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); - render.frame ++; - render.calls = 0; - render.triangles = 0; - render.points = 0; - render.lines = 0; + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; } - return { - memory: memory, - render: render, - programs: null, - autoReset: true, - reset: reset, - update: update - }; + _textureToCubeUV( texture, cubeUVRenderTarget ) { -} + const renderer = this._renderer; -function numericalSort( a, b ) { + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); - return a[ 0 ] - b[ 0 ]; + if ( isCubeTexture ) { -} + if ( this._cubemapMaterial === null ) { -function absNumericalSort( a, b ) { + this._cubemapMaterial = _getCubemapMaterial(); - return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); + } -} + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1; -function WebGLMorphtargets( gl ) { + } else { - const influencesList = {}; - const morphInfluences = new Float32Array( 8 ); + if ( this._equirectMaterial === null ) { - const workInfluences = []; + this._equirectMaterial = _getEquirectMaterial(); - for ( let i = 0; i < 8; i ++ ) { + } - workInfluences[ i ] = [ i, 0 ]; + } - } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh( this._lodPlanes[ 0 ], material ); - function update( object, geometry, material, program ) { + const uniforms = material.uniforms; - const objectInfluences = object.morphTargetInfluences; + uniforms[ 'envMap' ].value = texture; - // When object doesn't have morph target influences defined, we treat it as a 0-length array - // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences + const size = this._cubeSize; - const length = objectInfluences === undefined ? 0 : objectInfluences.length; + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); - let influences = influencesList[ geometry.id ]; + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); - if ( influences === undefined ) { + } - // initialise list + _applyPMREM( cubeUVRenderTarget ) { - influences = []; + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; - for ( let i = 0; i < length; i ++ ) { + for ( let i = 1; i < this._lodPlanes.length; i ++ ) { - influences[ i ] = [ i, 0 ]; + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); - } + const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; - influencesList[ geometry.id ] = influences; + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); } - // Collect influences - - for ( let i = 0; i < length; i ++ ) { + renderer.autoClear = autoClear; - const influence = influences[ i ]; + } - influence[ 0 ] = i; - influence[ 1 ] = objectInfluences[ i ]; + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { - } + const pingPongRenderTarget = this._pingPongRenderTarget; - influences.sort( absNumericalSort ); + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); - for ( let i = 0; i < 8; i ++ ) { + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); - if ( i < length && influences[ i ][ 1 ] ) { + } - workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; - workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { - } else { + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; - workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; - workInfluences[ i ][ 1 ] = 0; + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { - } + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); } - workInfluences.sort( numericalSort ); - - const morphTargets = material.morphTargets && geometry.morphAttributes.position; - const morphNormals = material.morphNormals && geometry.morphAttributes.normal; + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; - let morphInfluencesSum = 0; + const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial ); + const blurUniforms = blurMaterial.uniforms; - for ( let i = 0; i < 8; i ++ ) { + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; - const influence = workInfluences[ i ]; - const index = influence[ 0 ]; - const value = influence[ 1 ]; + if ( samples > MAX_SAMPLES ) { - if ( index !== Number.MAX_SAFE_INTEGER && value ) { + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); - if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { + } - geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); + const weights = []; + let sum = 0; - } + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { - if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); - geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); + if ( i === 0 ) { - } + sum += weight; - morphInfluences[ i ] = value; - morphInfluencesSum += value; + } else if ( i < samples ) { - } else { + sum += 2 * weight; - if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { + } - geometry.deleteAttribute( 'morphTarget' + i ); + } - } + for ( let i = 0; i < weights.length; i ++ ) { - if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { + weights[ i ] = weights[ i ] / sum; - geometry.deleteAttribute( 'morphNormal' + i ); + } - } + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; - morphInfluences[ i ] = 0; + if ( poleAxis ) { - } + blurUniforms[ 'poleAxis' ].value = poleAxis; } - // GLSL shader uses formula baseinfluence * base + sum(target * influence) - // This allows us to switch between absolute morphs and relative morphs without changing shader code - // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) - const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const { _lodMax } = this; + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = _lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); - program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); - program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); } - return { +} - update: update - }; -} +function _createPlanes( lodMax ) { -function WebGLObjects( gl, geometries, attributes, info ) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; - let updateMap = new WeakMap(); + let lod = lodMax; - function update( object ) { + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; - const frame = info.render.frame; + for ( let i = 0; i < totalLods; i ++ ) { - const geometry = object.geometry; - const buffergeometry = geometries.get( object, geometry ); + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; - // Update once per frame + if ( i > lodMax - LOD_MIN ) { - if ( updateMap.get( buffergeometry ) !== frame ) { + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; - geometries.update( buffergeometry ); + } else if ( i === 0 ) { - updateMap.set( buffergeometry, frame ); + sigma = 0; } - if ( object.isInstancedMesh ) { - - if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { - - object.addEventListener( 'dispose', onInstancedMeshDispose ); + sigmas.push( sigma ); - } + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; - attributes.update( object.instanceMatrix, 34962 ); + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; - if ( object.instanceColor !== null ) { + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); - attributes.update( object.instanceColor, 34962 ); + for ( let face = 0; face < cubeFaces; face ++ ) { - } + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + const fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); } - return buffergeometry; + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); - } + if ( lod > LOD_MIN ) { - function dispose() { + lod --; - updateMap = new WeakMap(); + } } - function onInstancedMeshDispose( event ) { - - const instancedMesh = event.target; - - instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); - - attributes.remove( instancedMesh.instanceMatrix ); - - if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); - - } + return { lodPlanes, sizeLods, sigmas }; - return { +} - update: update, - dispose: dispose +function _createRenderTarget( width, height, params ) { - }; + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; } -class DataTexture2DArray extends Texture { +function _setViewport( target, x, y, width, height ) { - constructor( data = null, width = 1, height = 1, depth = 1 ) { + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); - super( null ); +} - this.image = { data, width, height, depth }; +function _getBlurShader( lodMax, width, height ) { - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; + const weights = new Float32Array( MAX_SAMPLES ); + const poleAxis = new Vector3( 0, 1, 0 ); + const shaderMaterial = new ShaderMaterial( { - this.wrapR = ClampToEdgeWrapping; + name: 'SphericalGaussianBlur', - this.generateMipmaps = false; - this.flipY = false; + defines: { + 'n': MAX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, - this.needsUpdate = true; + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis } + }, - } + vertexShader: _getCommonVertexShader(), -} + fragmentShader: /* glsl */` -DataTexture2DArray.prototype.isDataTexture2DArray = true; + precision mediump float; + precision mediump int; -class DataTexture3D extends Texture { + varying vec3 vOutputDirection; - constructor( data = null, width = 1, height = 1, depth = 1 ) { + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; - // We're going to add .setXXX() methods for setting properties later. - // Users can still set in DataTexture3D directly. - // - // const texture = new THREE.DataTexture3D( data, width, height, depth ); - // texture.anisotropy = 16; - // - // See #14839 + #define ENVMAP_TYPE_CUBE_UV + #include - super( null ); + vec3 getSample( float theta, vec3 axis ) { - this.image = { data, width, height, depth }; + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; + return bilinearCubeUV( envMap, sampleDirection, mipInt ); - this.wrapR = ClampToEdgeWrapping; + } - this.generateMipmaps = false; - this.flipY = false; + void main() { - this.needsUpdate = true; + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - } + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { -} + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); -DataTexture3D.prototype.isDataTexture3D = true; + } -/** - * 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 )'. - * - * - * 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, [textures] ) - * - * uploads a uniform value(s) - * the 'textures' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (textures factorizations): - * - * .upload( gl, seq, values, textures ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * - * Methods of the top-level container (textures factorizations): - * - * .setValue( gl, name, value, textures ) - * - * sets uniform with name 'name' to 'value' - * - * .setOptional( gl, obj, prop ) - * - * like .set for an optional property of the object - * - */ + axis = normalize( axis ); -const emptyTexture = new Texture(); -const emptyTexture2dArray = new DataTexture2DArray(); -const emptyTexture3d = new DataTexture3D(); -const emptyCubeTexture = new CubeTexture(); + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); -// --- Utilities --- + for ( int i = 1; i < n; i++ ) { -// Array Caches (provide typed arrays for temporary by size) + if ( i >= samples ) { -const arrayCacheF32 = []; -const arrayCacheI32 = []; + break; -// Float32Array caches used for uploading Matrix uniforms + } -const mat4array = new Float32Array( 16 ); -const mat3array = new Float32Array( 9 ); -const mat2array = new Float32Array( 4 ); + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); -// Flattening for arrays of vectors and matrices + } -function flatten( array, nBlocks, blockSize ) { + } + `, - const firstElem = array[ 0 ]; + blending: NoBlending, + depthTest: false, + depthWrite: false - if ( firstElem <= 0 || firstElem > 0 ) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + } ); - const n = nBlocks * blockSize; - let r = arrayCacheF32[ n ]; + return shaderMaterial; - if ( r === undefined ) { +} - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; +function _getEquirectMaterial() { - } + return new ShaderMaterial( { - if ( nBlocks !== 0 ) { + name: 'EquirectangularToCubeUV', - firstElem.toArray( r, 0 ); + uniforms: { + 'envMap': { value: null } + }, - for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + vertexShader: _getCommonVertexShader(), - offset += blockSize; - array[ i ].toArray( r, offset ); + fragmentShader: /* glsl */` - } + precision mediump float; + precision mediump int; - } + varying vec3 vOutputDirection; - return r; + uniform sampler2D envMap; -} + #include -function arraysEqual( a, b ) { + void main() { - if ( a.length !== b.length ) return false; + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); - for ( let i = 0, l = a.length; i < l; i ++ ) { + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - if ( a[ i ] !== b[ i ] ) return false; + } + `, - } + blending: NoBlending, + depthTest: false, + depthWrite: false - return true; + } ); } -function copyArray( a, b ) { +function _getCubemapMaterial() { - for ( let i = 0, l = b.length; i < l; i ++ ) { + return new ShaderMaterial( { - a[ i ] = b[ i ]; + name: 'CubemapToCubeUV', - } + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: - 1 } + }, -} + vertexShader: _getCommonVertexShader(), -// Texture unit allocation + fragmentShader: /* glsl */` -function allocTexUnits( textures, n ) { + precision mediump float; + precision mediump int; - let r = arrayCacheI32[ n ]; + uniform float flipEnvMap; - if ( r === undefined ) { + varying vec3 vOutputDirection; - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + uniform samplerCube envMap; - } + void main() { - for ( let i = 0; i !== n; ++ i ) { + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - r[ i ] = textures.allocateTextureUnit(); + } + `, - } + blending: NoBlending, + depthTest: false, + depthWrite: false - return r; + } ); } -// --- Setters --- +function _getCommonVertexShader() { -// Note: Defining these methods externally, because they come in a bunch -// and this way their names minify. + return /* glsl */` -// Single scalar + precision mediump float; + precision mediump int; -function setValueV1f( gl, v ) { + attribute float faceIndex; - const cache = this.cache; + varying vec3 vOutputDirection; - if ( cache[ 0 ] === v ) return; + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { - gl.uniform1f( this.addr, v ); + uv = 2.0 * uv - 1.0; - cache[ 0 ] = v; + vec3 direction = vec3( uv, 1.0 ); -} + if ( face == 0.0 ) { -// Single float vector (from flat array or THREE.VectorN) + direction = direction.zyx; // ( 1, v, u ) pos x -function setValueV2f( gl, v ) { + } else if ( face == 1.0 ) { - const cache = this.cache; + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y - if ( v.x !== undefined ) { + } else if ( face == 2.0 ) { - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + direction.x *= -1.0; // ( -u, v, 1 ) pos z - gl.uniform2f( this.addr, v.x, v.y ); - - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - - } - - } else { - - if ( arraysEqual( cache, v ) ) return; + } else if ( face == 3.0 ) { - gl.uniform2fv( this.addr, v ); + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x - copyArray( cache, v ); + } else if ( face == 4.0 ) { - } + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y -} + } else if ( face == 5.0 ) { -function setValueV3f( gl, v ) { + direction.z *= -1.0; // ( u, v, -1 ) neg z - const cache = this.cache; + } - if ( v.x !== undefined ) { + return direction; - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + } - gl.uniform3f( this.addr, v.x, v.y, v.z ); + void main() { - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - cache[ 2 ] = v.z; + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); } + `; - } else if ( v.r !== undefined ) { - - if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { +} - gl.uniform3f( this.addr, v.r, v.g, v.b ); +function WebGLCubeUVMaps( renderer ) { - cache[ 0 ] = v.r; - cache[ 1 ] = v.g; - cache[ 2 ] = v.b; + let cubeUVmaps = new WeakMap(); - } + let pmremGenerator = null; - } else { + function get( texture ) { - if ( arraysEqual( cache, v ) ) return; + if ( texture && texture.isTexture ) { - gl.uniform3fv( this.addr, v ); + const mapping = texture.mapping; - copyArray( cache, v ); + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); - } + // equirect/cube map to cubeUV conversion -} + if ( isEquirectMap || isCubeMap ) { -function setValueV4f( gl, v ) { + if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) { - const cache = this.cache; + texture.needsPMREMUpdate = false; - if ( v.x !== undefined ) { + let renderTarget = cubeUVmaps.get( texture ); - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); - gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + cubeUVmaps.set( texture, renderTarget ); - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - cache[ 2 ] = v.z; - cache[ 3 ] = v.w; + return renderTarget.texture; - } + } else { - } else { + if ( cubeUVmaps.has( texture ) ) { - if ( arraysEqual( cache, v ) ) return; + return cubeUVmaps.get( texture ).texture; - gl.uniform4fv( this.addr, v ); + } else { - copyArray( cache, v ); + const image = texture.image; - } + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { -} + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); -// Single matrix (from flat array or MatrixN) + const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + cubeUVmaps.set( texture, renderTarget ); -function setValueM2( gl, v ) { + texture.addEventListener( 'dispose', onTextureDispose ); - const cache = this.cache; - const elements = v.elements; + return renderTarget.texture; - if ( elements === undefined ) { + } else { - if ( arraysEqual( cache, v ) ) return; + // image not yet ready. try the conversion next frame - gl.uniformMatrix2fv( this.addr, false, v ); + return null; - copyArray( cache, v ); + } - } else { + } - if ( arraysEqual( cache, elements ) ) return; + } - mat2array.set( elements ); + } - gl.uniformMatrix2fv( this.addr, false, mat2array ); + } - copyArray( cache, elements ); + return texture; } -} - -function setValueM3( gl, v ) { + function isCubeTextureComplete( image ) { - const cache = this.cache; - const elements = v.elements; + let count = 0; + const length = 6; - if ( elements === undefined ) { + for ( let i = 0; i < length; i ++ ) { - if ( arraysEqual( cache, v ) ) return; + if ( image[ i ] !== undefined ) count ++; - gl.uniformMatrix3fv( this.addr, false, v ); + } - copyArray( cache, v ); + return count === length; - } else { - if ( arraysEqual( cache, elements ) ) return; + } - mat3array.set( elements ); + function onTextureDispose( event ) { - gl.uniformMatrix3fv( this.addr, false, mat3array ); + const texture = event.target; - copyArray( cache, elements ); + texture.removeEventListener( 'dispose', onTextureDispose ); - } + const cubemapUV = cubeUVmaps.get( texture ); -} + if ( cubemapUV !== undefined ) { -function setValueM4( gl, v ) { + cubeUVmaps.delete( texture ); + cubemapUV.dispose(); - const cache = this.cache; - const elements = v.elements; + } - if ( elements === undefined ) { + } - if ( arraysEqual( cache, v ) ) return; + function dispose() { - gl.uniformMatrix4fv( this.addr, false, v ); + cubeUVmaps = new WeakMap(); - copyArray( cache, v ); + if ( pmremGenerator !== null ) { - } else { + pmremGenerator.dispose(); + pmremGenerator = null; - if ( arraysEqual( cache, elements ) ) return; + } - mat4array.set( elements ); + } - gl.uniformMatrix4fv( this.addr, false, mat4array ); + return { + get: get, + dispose: dispose + }; - copyArray( cache, elements ); +} - } +function WebGLExtensions( gl ) { -} + const extensions = {}; -// Single texture (2D / Cube) + function getExtension( name ) { -function setValueT1( gl, v, textures ) { + if ( extensions[ name ] !== undefined ) { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + return extensions[ name ]; - if ( cache[ 0 ] !== unit ) { + } - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + let extension; - } + switch ( name ) { - textures.safeSetTexture2D( v || emptyTexture, unit ); + 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; -function setValueT2DArray1( gl, v, textures ) { + 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; - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - if ( cache[ 0 ] !== unit ) { + default: + extension = gl.getExtension( name ); - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + } - } + extensions[ name ] = extension; - textures.setTexture2DArray( v || emptyTexture2dArray, unit ); + return extension; -} + } -function setValueT3D1( gl, v, textures ) { + return { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + has: function ( name ) { - if ( cache[ 0 ] !== unit ) { + return getExtension( name ) !== null; - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + }, - } + init: function ( capabilities ) { - textures.setTexture3D( v || emptyTexture3d, unit ); + if ( capabilities.isWebGL2 ) { -} + getExtension( 'EXT_color_buffer_float' ); -function setValueT6( gl, v, textures ) { + } else { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + getExtension( 'WEBGL_depth_texture' ); + getExtension( 'OES_texture_float' ); + getExtension( 'OES_texture_half_float' ); + getExtension( 'OES_texture_half_float_linear' ); + getExtension( 'OES_standard_derivatives' ); + getExtension( 'OES_element_index_uint' ); + getExtension( 'OES_vertex_array_object' ); + getExtension( 'ANGLE_instanced_arrays' ); - if ( cache[ 0 ] !== unit ) { + } - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); - } + }, - textures.safeSetTextureCube( v || emptyCubeTexture, unit ); + get: function ( name ) { -} + const extension = getExtension( name ); -// Integer / Boolean vectors or arrays thereof (always flat arrays) + if ( extension === null ) { -function setValueV1i( gl, v ) { + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - const cache = this.cache; + } - if ( cache[ 0 ] === v ) return; + return extension; - gl.uniform1i( this.addr, v ); + } - cache[ 0 ] = v; + }; } -function setValueV2i( gl, v ) { +function WebGLGeometries( gl, attributes, info, bindingStates ) { - const cache = this.cache; + const geometries = {}; + const wireframeAttributes = new WeakMap(); - if ( arraysEqual( cache, v ) ) return; + function onGeometryDispose( event ) { - gl.uniform2iv( this.addr, v ); + const geometry = event.target; - copyArray( cache, v ); + if ( geometry.index !== null ) { -} + attributes.remove( geometry.index ); -function setValueV3i( gl, v ) { + } - const cache = this.cache; + for ( const name in geometry.attributes ) { - if ( arraysEqual( cache, v ) ) return; + attributes.remove( geometry.attributes[ name ] ); - gl.uniform3iv( this.addr, v ); + } - copyArray( cache, v ); + geometry.removeEventListener( 'dispose', onGeometryDispose ); -} + delete geometries[ geometry.id ]; -function setValueV4i( gl, v ) { + const attribute = wireframeAttributes.get( geometry ); - const cache = this.cache; + if ( attribute ) { - if ( arraysEqual( cache, v ) ) return; + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); - gl.uniform4iv( this.addr, v ); + } - copyArray( cache, v ); + bindingStates.releaseStatesOfGeometry( geometry ); -} + if ( geometry.isInstancedBufferGeometry === true ) { -// uint + delete geometry._maxInstanceCount; -function setValueV1ui( gl, v ) { + } - const cache = this.cache; + // - if ( cache[ 0 ] === v ) return; + info.memory.geometries --; - gl.uniform1ui( this.addr, v ); + } - cache[ 0 ] = v; + function get( object, geometry ) { -} + if ( geometries[ geometry.id ] === true ) return geometry; -// Helper to pick the right setter for the singular case + geometry.addEventListener( 'dispose', onGeometryDispose ); -function getSingularSetter( type ) { + geometries[ geometry.id ] = true; - switch ( type ) { + info.memory.geometries ++; - case 0x1406: return setValueV1f; // FLOAT - case 0x8b50: return setValueV2f; // _VEC2 - case 0x8b51: return setValueV3f; // _VEC3 - case 0x8b52: return setValueV4f; // _VEC4 + return geometry; - case 0x8b5a: return setValueM2; // _MAT2 - case 0x8b5b: return setValueM3; // _MAT3 - case 0x8b5c: return setValueM4; // _MAT4 + } - case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL - case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 - case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 - case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + function update( geometry ) { - case 0x1405: return setValueV1ui; // UINT + const geometryAttributes = geometry.attributes; - case 0x8b5e: // SAMPLER_2D - case 0x8d66: // SAMPLER_EXTERNAL_OES - case 0x8dca: // INT_SAMPLER_2D - case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D - case 0x8b62: // SAMPLER_2D_SHADOW - return setValueT1; + // Updating index buffer in VAO now. See WebGLBindingStates. - case 0x8b5f: // SAMPLER_3D - case 0x8dcb: // INT_SAMPLER_3D - case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D - return setValueT3D1; + for ( const name in geometryAttributes ) { - case 0x8b60: // SAMPLER_CUBE - case 0x8dcc: // INT_SAMPLER_CUBE - case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE - case 0x8dc5: // SAMPLER_CUBE_SHADOW - return setValueT6; + attributes.update( geometryAttributes[ name ], 34962 ); - case 0x8dc1: // SAMPLER_2D_ARRAY - case 0x8dcf: // INT_SAMPLER_2D_ARRAY - case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY - case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW - return setValueT2DArray1; + } - } + // morph targets -} + const morphAttributes = geometry.morphAttributes; -// Array of scalars -function setValueV1fArray( gl, v ) { + for ( const name in morphAttributes ) { - gl.uniform1fv( this.addr, v ); + const array = morphAttributes[ name ]; -} + for ( let i = 0, l = array.length; i < l; i ++ ) { -// Integer / Boolean vectors or arrays thereof (always flat arrays) -function setValueV1iArray( gl, v ) { + attributes.update( array[ i ], 34962 ); - gl.uniform1iv( this.addr, v ); + } -} + } -function setValueV2iArray( gl, v ) { + } - gl.uniform2iv( this.addr, v ); + function updateWireframeAttribute( geometry ) { -} + const indices = []; -function setValueV3iArray( gl, v ) { + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; - gl.uniform3iv( this.addr, v ); + if ( geometryIndex !== null ) { -} + const array = geometryIndex.array; + version = geometryIndex.version; -function setValueV4iArray( gl, v ) { + for ( let i = 0, l = array.length; i < l; i += 3 ) { - gl.uniform4iv( this.addr, v ); + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; -} + indices.push( a, b, b, c, c, a ); + } -// Array of vectors (flat or from THREE classes) + } else { -function setValueV2fArray( gl, v ) { + const array = geometryPosition.array; + version = geometryPosition.version; - const data = flatten( v, this.size, 2 ); + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - gl.uniform2fv( this.addr, data ); + const a = i + 0; + const b = i + 1; + const c = i + 2; -} + indices.push( a, b, b, c, c, a ); -function setValueV3fArray( gl, v ) { + } - const data = flatten( v, this.size, 3 ); + } - gl.uniform3fv( this.addr, data ); + const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; -} + // Updating index buffer in VAO now. See WebGLBindingStates -function setValueV4fArray( gl, v ) { + // - const data = flatten( v, this.size, 4 ); + const previousAttribute = wireframeAttributes.get( geometry ); - gl.uniform4fv( this.addr, data ); + if ( previousAttribute ) attributes.remove( previousAttribute ); -} + // -// Array of matrices (flat or from THREE clases) + wireframeAttributes.set( geometry, attribute ); -function setValueM2Array( gl, v ) { + } - const data = flatten( v, this.size, 4 ); + function getWireframeAttribute( geometry ) { - gl.uniformMatrix2fv( this.addr, false, data ); + const currentAttribute = wireframeAttributes.get( geometry ); -} + if ( currentAttribute ) { -function setValueM3Array( gl, v ) { + const geometryIndex = geometry.index; - const data = flatten( v, this.size, 9 ); + if ( geometryIndex !== null ) { - gl.uniformMatrix3fv( this.addr, false, data ); + // if the attribute is obsolete, create a new one -} + if ( currentAttribute.version < geometryIndex.version ) { -function setValueM4Array( gl, v ) { + updateWireframeAttribute( geometry ); - const data = flatten( v, this.size, 16 ); + } - gl.uniformMatrix4fv( this.addr, false, data ); + } -} + } else { -// Array of textures (2D / Cube) + updateWireframeAttribute( geometry ); -function setValueT1Array( gl, v, textures ) { + } - const n = v.length; + return wireframeAttributes.get( geometry ); - const units = allocTexUnits( textures, n ); + } - gl.uniform1iv( this.addr, units ); + return { - for ( let i = 0; i !== n; ++ i ) { + get: get, + update: update, - textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] ); + getWireframeAttribute: getWireframeAttribute - } + }; } -function setValueT6Array( gl, v, textures ) { - - const n = v.length; +function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { - const units = allocTexUnits( textures, n ); + const isWebGL2 = capabilities.isWebGL2; - gl.uniform1iv( this.addr, units ); + let mode; - for ( let i = 0; i !== n; ++ i ) { + function setMode( value ) { - textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + mode = value; } -} - -// Helper to pick the right setter for a pure (bottom-level) array - -function getPureArraySetter( type ) { + let type, bytesPerElement; - switch ( type ) { + function setIndex( value ) { - case 0x1406: return setValueV1fArray; // FLOAT - case 0x8b50: return setValueV2fArray; // _VEC2 - case 0x8b51: return setValueV3fArray; // _VEC3 - case 0x8b52: return setValueV4fArray; // _VEC4 + type = value.type; + bytesPerElement = value.bytesPerElement; - case 0x8b5a: return setValueM2Array; // _MAT2 - case 0x8b5b: return setValueM3Array; // _MAT3 - case 0x8b5c: return setValueM4Array; // _MAT4 + } - case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL - case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 - case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 - case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + function render( start, count ) { - case 0x8b5e: // SAMPLER_2D - case 0x8d66: // SAMPLER_EXTERNAL_OES - case 0x8dca: // INT_SAMPLER_2D - case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D - case 0x8b62: // SAMPLER_2D_SHADOW - return setValueT1Array; + gl.drawElements( mode, count, type, start * bytesPerElement ); - case 0x8b60: // SAMPLER_CUBE - case 0x8dcc: // INT_SAMPLER_CUBE - case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE - case 0x8dc5: // SAMPLER_CUBE_SHADOW - return setValueT6Array; + info.update( count, mode, 1 ); } -} - -// --- Uniform Classes --- + function renderInstances( start, count, primcount ) { -function SingleUniform( id, activeInfo, addr ) { + if ( primcount === 0 ) return; - this.id = id; - this.addr = addr; - this.cache = []; - this.setValue = getSingularSetter( activeInfo.type ); + let extension, methodName; - // this.path = activeInfo.name; // DEBUG + if ( isWebGL2 ) { -} + extension = gl; + methodName = 'drawElementsInstanced'; -function PureArrayUniform( id, activeInfo, addr ) { + } else { - this.id = id; - this.addr = addr; - this.cache = []; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawElementsInstancedANGLE'; - // this.path = activeInfo.name; // DEBUG + if ( extension === null ) { -} + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; -PureArrayUniform.prototype.updateCache = function ( data ) { + } - const cache = this.cache; + } - if ( data instanceof Float32Array && cache.length !== data.length ) { + extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); - this.cache = new Float32Array( data.length ); + info.update( count, mode, primcount ); } - copyArray( cache, data ); + // -}; + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; -function StructuredUniform( id ) { +} - this.id = id; +function WebGLInfo( gl ) { - this.seq = []; - this.map = {}; - -} - -StructuredUniform.prototype.setValue = function ( gl, value, textures ) { + const memory = { + geometries: 0, + textures: 0 + }; - const seq = this.seq; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + function update( count, mode, instanceCount ) { - const u = seq[ i ]; - u.setValue( gl, value[ u.id ], textures ); + render.calls ++; - } + switch ( mode ) { -}; + case 4: + render.triangles += instanceCount * ( count / 3 ); + break; -// --- Top-level --- + case 1: + render.lines += instanceCount * ( count / 2 ); + break; -// Parser - builds up the property tree from the path strings + case 3: + render.lines += instanceCount * ( count - 1 ); + break; -const RePathPart = /(\w+)(\])?(\[|\.)?/g; + case 2: + render.lines += instanceCount * count; + break; -// 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. + case 0: + render.points += instanceCount * count; + break; -function addUniform( container, uniformObject ) { + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + } -} + } -function parseUniform( activeInfo, addr, container ) { + function reset() { - const path = activeInfo.name, - pathLength = path.length; + render.frame ++; + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + } - while ( true ) { + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; - const match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex; +} - let id = match[ 1 ]; - const idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; +function numericalSort( a, b ) { - if ( idIsIndex ) id = id | 0; // convert to integer + return a[ 0 ] - b[ 0 ]; - if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { +} - // bare name or "pure" bottom-level array "[0]" suffix +function absNumericalSort( a, b ) { - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); - break; +} - } else { +function WebGLMorphtargets( gl, capabilities, textures ) { - // step into inner node / create it in case it doesn't exist + const influencesList = {}; + const morphInfluences = new Float32Array( 8 ); + const morphTextures = new WeakMap(); + const morph = new Vector4(); - const map = container.map; - let next = map[ id ]; + const workInfluences = []; - if ( next === undefined ) { + for ( let i = 0; i < 8; i ++ ) { - next = new StructuredUniform( id ); - addUniform( container, next ); + workInfluences[ i ] = [ i, 0 ]; - } + } - container = next; + function update( object, geometry, material, program ) { - } + const objectInfluences = object.morphTargetInfluences; - } + if ( capabilities.isWebGL2 === true ) { -} + // instead of using attributes, the WebGL 2 code path encodes morph targets + // into an array of data textures. Each layer represents a single morph target. -// Root Container + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; -function WebGLUniforms( gl, program ) { + let entry = morphTextures.get( geometry ); - this.seq = []; - this.map = {}; + if ( entry === undefined || entry.count !== morphTargetsCount ) { - const n = gl.getProgramParameter( program, 35718 ); + if ( entry !== undefined ) entry.texture.dispose(); - for ( let i = 0; i < n; ++ i ) { + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; - const info = gl.getActiveUniform( program, i ), - addr = gl.getUniformLocation( program, info.name ); + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; - parseUniform( info, addr, this ); + let vertexDataCount = 0; - } + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; -} + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; -WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) { + if ( width > capabilities.maxTextureSize ) { - const u = this.map[ name ]; + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; - if ( u !== undefined ) u.setValue( gl, value, textures ); + } -}; + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); -WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; - const v = object[ name ]; + // fill buffer - if ( v !== undefined ) this.setValue( gl, name, v ); + const vertexDataStride = vertexDataCount * 4; -}; + for ( let i = 0; i < morphTargetsCount; i ++ ) { + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; -// Static interface + const offset = width * height * 4 * i; -WebGLUniforms.upload = function ( gl, seq, values, textures ) { + for ( let j = 0; j < morphTarget.count; j ++ ) { - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + const stride = j * vertexDataStride; - const u = seq[ i ], - v = values[ u.id ]; + if ( hasMorphPosition === true ) { - if ( v.needsUpdate !== false ) { + morph.fromBufferAttribute( morphTarget, j ); - // note: always updating when .needsUpdate is undefined - u.setValue( gl, v.value, textures ); + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; - } + } - } + if ( hasMorphNormals === true ) { -}; + morph.fromBufferAttribute( morphNormal, j ); -WebGLUniforms.seqWithValue = function ( seq, values ) { + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; - const r = []; + } - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + if ( hasMorphColors === true ) { - const u = seq[ i ]; - if ( u.id in values ) r.push( u ); + morph.fromBufferAttribute( morphColor, j ); - } + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; - return r; + } -}; + } -function WebGLShader( gl, type, string ) { + } - const shader = gl.createShader( type ); + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; - gl.shaderSource( shader, string ); - gl.compileShader( shader ); + morphTextures.set( geometry, entry ); - return shader; + function disposeTexture() { -} + texture.dispose(); -let programIdCount = 0; + morphTextures.delete( geometry ); -function addLineNumbers( string ) { + geometry.removeEventListener( 'dispose', disposeTexture ); - const lines = string.split( '\n' ); + } - for ( let i = 0; i < lines.length; i ++ ) { + geometry.addEventListener( 'dispose', disposeTexture ); - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; + } - } + // - return lines.join( '\n' ); + let morphInfluencesSum = 0; -} + for ( let i = 0; i < objectInfluences.length; i ++ ) { -function getEncodingComponents( encoding ) { + morphInfluencesSum += objectInfluences[ i ]; - switch ( encoding ) { + } - 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 ) )' ]; - case LogLuvEncoding: - return [ 'LogLuv', '( value )' ]; - default: - console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding ); - return [ 'Linear', '( value )' ]; + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - } + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); -} + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); -function getShaderErrors( gl, shader, type ) { - const status = gl.getShaderParameter( shader, 35713 ); - const log = gl.getShaderInfoLog( shader ).trim(); + } else { - if ( status && log === '' ) return ''; + // When object doesn't have morph target influences defined, we treat it as a 0-length array + // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences - // --enable-privileged-webgl-extension - // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + const length = objectInfluences === undefined ? 0 : objectInfluences.length; - const source = gl.getShaderSource( shader ); + let influences = influencesList[ geometry.id ]; - return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source ); + if ( influences === undefined || influences.length !== length ) { -} + // initialise list -function getTexelDecodingFunction( functionName, encoding ) { + influences = []; - const components = getEncodingComponents( encoding ); - return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }'; + for ( let i = 0; i < length; i ++ ) { -} + influences[ i ] = [ i, 0 ]; -function getTexelEncodingFunction( functionName, encoding ) { + } - const components = getEncodingComponents( encoding ); - return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; + influencesList[ geometry.id ] = influences; -} + } -function getToneMappingFunction( functionName, toneMapping ) { + // Collect influences - let toneMappingName; + for ( let i = 0; i < length; i ++ ) { - switch ( toneMapping ) { + const influence = influences[ i ]; - case LinearToneMapping: - toneMappingName = 'Linear'; - break; + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; - case ReinhardToneMapping: - toneMappingName = 'Reinhard'; - break; + } - case CineonToneMapping: - toneMappingName = 'OptimizedCineon'; - break; + influences.sort( absNumericalSort ); - case ACESFilmicToneMapping: - toneMappingName = 'ACESFilmic'; - break; + for ( let i = 0; i < 8; i ++ ) { - case CustomToneMapping: - toneMappingName = 'Custom'; - break; + if ( i < length && influences[ i ][ 1 ] ) { - default: - console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); - toneMappingName = 'Linear'; + workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; + workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; - } + } else { - return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; + workInfluences[ i ][ 1 ] = 0; -} + } -function generateExtensions( parameters ) { + } - const chunks = [ - ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', - ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', - ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', - ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' - ]; + workInfluences.sort( numericalSort ); - return chunks.filter( filterEmptyLine ).join( '\n' ); + const morphTargets = geometry.morphAttributes.position; + const morphNormals = geometry.morphAttributes.normal; -} + let morphInfluencesSum = 0; -function generateDefines( defines ) { + for ( let i = 0; i < 8; i ++ ) { - const chunks = []; + const influence = workInfluences[ i ]; + const index = influence[ 0 ]; + const value = influence[ 1 ]; - for ( const name in defines ) { + if ( index !== Number.MAX_SAFE_INTEGER && value ) { - const value = defines[ name ]; + if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { - if ( value === false ) continue; + geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); - chunks.push( '#define ' + name + ' ' + value ); + } - } + if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { - return chunks.join( '\n' ); + geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); -} + } -function fetchAttributeLocations( gl, program ) { + morphInfluences[ i ] = value; + morphInfluencesSum += value; - const attributes = {}; + } else { - const n = gl.getProgramParameter( program, 35721 ); + if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { - for ( let i = 0; i < n; i ++ ) { + geometry.deleteAttribute( 'morphTarget' + i ); - const info = gl.getActiveAttrib( program, i ); - const name = info.name; + } - // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { - attributes[ name ] = gl.getAttribLocation( program, name ); + geometry.deleteAttribute( 'morphNormal' + i ); - } + } - return attributes; + morphInfluences[ i ] = 0; -} + } -function filterEmptyLine( string ) { + } - return string !== ''; + // GLSL shader uses formula baseinfluence * base + sum(target * influence) + // This allows us to switch between absolute morphs and relative morphs without changing shader code + // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; -} + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); -function replaceLightNums( string, parameters ) { + } - return string - .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) - .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) - .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) - .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) - .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) - .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) - .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) - .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + } -} + return { -function replaceClippingPlaneNums( string, parameters ) { + update: update - return string - .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) - .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + }; } -// Resolve Includes - -const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; +function WebGLObjects( gl, geometries, attributes, info ) { -function resolveIncludes( string ) { + let updateMap = new WeakMap(); - return string.replace( includePattern, includeReplacer ); + function update( object ) { -} + const frame = info.render.frame; -function includeReplacer( match, include ) { + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); - const string = ShaderChunk[ include ]; + // Update once per frame - if ( string === undefined ) { + if ( updateMap.get( buffergeometry ) !== frame ) { - throw new Error( 'Can not resolve #include <' + include + '>' ); + geometries.update( buffergeometry ); - } + updateMap.set( buffergeometry, frame ); - return resolveIncludes( string ); + } -} + if ( object.isInstancedMesh ) { -// Unroll Loops + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { -const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; -const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + object.addEventListener( 'dispose', onInstancedMeshDispose ); -function unrollLoops( string ) { + } - return string - .replace( unrollLoopPattern, loopReplacer ) - .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer ); + attributes.update( object.instanceMatrix, 34962 ); -} + if ( object.instanceColor !== null ) { -function deprecatedLoopReplacer( match, start, end, snippet ) { + attributes.update( object.instanceColor, 34962 ); - console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' ); - return loopReplacer( match, start, end, snippet ); + } -} + } -function loopReplacer( match, start, end, snippet ) { + return buffergeometry; - let string = ''; + } - for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + function dispose() { - string += snippet - .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) - .replace( /UNROLLED_LOOP_INDEX/g, i ); + updateMap = new WeakMap(); } - return string; - -} - -// + function onInstancedMeshDispose( event ) { -function generatePrecision( parameters ) { + const instancedMesh = event.target; - let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); - if ( parameters.precision === 'highp' ) { + attributes.remove( instancedMesh.instanceMatrix ); - precisionstring += '\n#define HIGH_PRECISION'; + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); - } else if ( parameters.precision === 'mediump' ) { + } - precisionstring += '\n#define MEDIUM_PRECISION'; + return { - } else if ( parameters.precision === 'lowp' ) { + update: update, + dispose: dispose - precisionstring += '\n#define LOW_PRECISION'; + }; - } +} - return precisionstring; +/** + * 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 )'. + * + * + * 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, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ -} +const emptyTexture = /*@__PURE__*/ new Texture(); +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); -function generateShadowMapTypeDefine( parameters ) { +// --- Utilities --- - let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; +// Array Caches (provide typed arrays for temporary by size) - if ( parameters.shadowMapType === PCFShadowMap ) { +const arrayCacheF32 = []; +const arrayCacheI32 = []; - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; +// Float32Array caches used for uploading Matrix uniforms - } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { +const mat4array = new Float32Array( 16 ); +const mat3array = new Float32Array( 9 ); +const mat2array = new Float32Array( 4 ); - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; +// Flattening for arrays of vectors and matrices - } else if ( parameters.shadowMapType === VSMShadowMap ) { +function flatten( array, nBlocks, blockSize ) { - shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + const firstElem = array[ 0 ]; - } + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - return shadowMapTypeDefine; + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; -} + if ( r === undefined ) { -function generateEnvMapTypeDefine( parameters ) { + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + } - if ( parameters.envMap ) { + if ( nBlocks !== 0 ) { - switch ( parameters.envMapMode ) { + firstElem.toArray( r, 0 ); - case CubeReflectionMapping: - case CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { - case CubeUVReflectionMapping: - case CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; + offset += blockSize; + array[ i ].toArray( r, offset ); } } - return envMapTypeDefine; + return r; } -function generateEnvMapModeDefine( parameters ) { +function arraysEqual( a, b ) { - let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + if ( a.length !== b.length ) return false; - if ( parameters.envMap ) { + for ( let i = 0, l = a.length; i < l; i ++ ) { - switch ( parameters.envMapMode ) { + if ( a[ i ] !== b[ i ] ) return false; - case CubeRefractionMapping: - case CubeUVRefractionMapping: + } - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; + return true; - } +} - } +function copyArray( a, b ) { - return envMapModeDefine; + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } } -function generateEnvMapBlendingDefine( parameters ) { +// Texture unit allocation - let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; +function allocTexUnits( textures, n ) { - if ( parameters.envMap ) { + let r = arrayCacheI32[ n ]; - switch ( parameters.combine ) { + if ( r === undefined ) { - case MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - case MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; + } - case AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; + for ( let i = 0; i !== n; ++ i ) { - } + r[ i ] = textures.allocateTextureUnit(); } - return envMapBlendingDefine; + return r; } -function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { - - const gl = renderer.getContext(); +// --- Setters --- - const defines = parameters.defines; +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. - let vertexShader = parameters.vertexShader; - let fragmentShader = parameters.fragmentShader; +// Single scalar - const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); - const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); - const envMapModeDefine = generateEnvMapModeDefine( parameters ); - const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); +function setValueV1f( gl, v ) { + const cache = this.cache; - const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + if ( cache[ 0 ] === v ) return; - const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + gl.uniform1f( this.addr, v ); - const customDefines = generateDefines( defines ); + cache[ 0 ] = v; - const program = gl.createProgram(); +} - let prefixVertex, prefixFragment; - let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; +// Single float vector (from flat array or THREE.VectorN) - if ( parameters.isRawShaderMaterial ) { +function setValueV2f( gl, v ) { - prefixVertex = [ + const cache = this.cache; - customDefines + if ( v.x !== undefined ) { - ].filter( filterEmptyLine ).join( '\n' ); + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { - if ( prefixVertex.length > 0 ) { + gl.uniform2f( this.addr, v.x, v.y ); - prefixVertex += '\n'; + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; } - prefixFragment = [ + } else { - customExtensions, - customDefines + if ( arraysEqual( cache, v ) ) return; - ].filter( filterEmptyLine ).join( '\n' ); + gl.uniform2fv( this.addr, v ); - if ( prefixFragment.length > 0 ) { + copyArray( cache, v ); - prefixFragment += '\n'; + } - } +} - } else { +function setValueV3f( gl, v ) { - prefixVertex = [ + const cache = this.cache; - generatePrecision( parameters ), + if ( v.x !== undefined ) { - '#define SHADER_NAME ' + parameters.shaderName, + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { - customDefines, + gl.uniform3f( this.addr, v.x, v.y, v.z ); - parameters.instancing ? '#define USE_INSTANCING' : '', - parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + } - '#define GAMMA_FACTOR ' + gammaFactorDefine, + } else if ( v.r !== undefined ) { - '#define MAX_BONES ' + parameters.maxBones, - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { - 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', - ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + gl.uniform3f( this.addr, v.r, v.g, v.b ); - parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', - parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', - parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_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.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; - parameters.vertexTangents ? '#define USE_TANGENT' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', - parameters.vertexUvs ? '#define USE_UV' : '', - parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + } - parameters.flatShading ? '#define FLAT_SHADED' : '', + } else { - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', + if ( arraysEqual( cache, v ) ) return; - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + gl.uniform3fv( this.addr, v ); - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + copyArray( cache, v ); - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + } - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', +} - 'uniform mat4 modelMatrix;', - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;', - 'uniform vec3 cameraPosition;', - 'uniform bool isOrthographic;', +function setValueV4f( gl, v ) { - '#ifdef USE_INSTANCING', + const cache = this.cache; - ' attribute mat4 instanceMatrix;', + if ( v.x !== undefined ) { - '#endif', + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { - '#ifdef USE_INSTANCING_COLOR', + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - ' attribute vec3 instanceColor;', + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; - '#endif', + } - 'attribute vec3 position;', - 'attribute vec3 normal;', - 'attribute vec2 uv;', + } else { - '#ifdef USE_TANGENT', + if ( arraysEqual( cache, v ) ) return; - ' attribute vec4 tangent;', + gl.uniform4fv( this.addr, v ); - '#endif', + copyArray( cache, v ); - '#ifdef USE_COLOR', + } - ' attribute vec3 color;', +} - '#endif', +// Single matrix (from flat array or THREE.MatrixN) - '#ifdef USE_MORPHTARGETS', +function setValueM2( gl, v ) { - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + const cache = this.cache; + const elements = v.elements; - ' #ifdef USE_MORPHNORMALS', + if ( elements === undefined ) { - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + if ( arraysEqual( cache, v ) ) return; - ' #else', + gl.uniformMatrix2fv( this.addr, false, v ); - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', + copyArray( cache, v ); - ' #endif', + } else { - '#endif', + if ( arraysEqual( cache, elements ) ) return; - '#ifdef USE_SKINNING', + mat2array.set( elements ); - ' attribute vec4 skinIndex;', - ' attribute vec4 skinWeight;', + gl.uniformMatrix2fv( this.addr, false, mat2array ); - '#endif', + copyArray( cache, elements ); - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); +} - prefixFragment = [ +function setValueM3( gl, v ) { - customExtensions, + const cache = this.cache; + const elements = v.elements; - generatePrecision( parameters ), + if ( elements === undefined ) { - '#define SHADER_NAME ' + parameters.shaderName, + if ( arraysEqual( cache, v ) ) return; - customDefines, + gl.uniformMatrix3fv( this.addr, false, v ); - parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer + copyArray( cache, v ); - '#define GAMMA_FACTOR ' + gammaFactorDefine, + } else { - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + if ( arraysEqual( cache, elements ) ) return; - parameters.map ? '#define USE_MAP' : '', - parameters.matcap ? '#define USE_MATCAP' : '', - 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', - ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', - parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', - parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', - parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + mat3array.set( elements ); - parameters.sheen ? '#define USE_SHEEN' : '', - parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + gl.uniformMatrix3fv( this.addr, false, mat3array ); - parameters.vertexTangents ? '#define USE_TANGENT' : '', - parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', - parameters.vertexUvs ? '#define USE_UV' : '', - parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + copyArray( cache, elements ); - parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + } - parameters.flatShading ? '#define FLAT_SHADED' : '', +} - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', +function setValueM4( gl, v ) { - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + const cache = this.cache; + const elements = v.elements; - parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + if ( elements === undefined ) { - parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', + if ( arraysEqual( cache, v ) ) return; - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + gl.uniformMatrix4fv( this.addr, false, v ); - ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '', + copyArray( cache, v ); - 'uniform mat4 viewMatrix;', - 'uniform vec3 cameraPosition;', - 'uniform bool isOrthographic;', + } else { - ( 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 ) : '', + if ( arraysEqual( cache, elements ) ) return; - parameters.dithering ? '#define DITHERING' : '', + mat4array.set( elements ); - ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below - parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', - parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '', - parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', - parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', - parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '', - getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), + gl.uniformMatrix4fv( this.addr, false, mat4array ); - parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + copyArray( cache, elements ); - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); +} - } +// Single integer / boolean - vertexShader = resolveIncludes( vertexShader ); - vertexShader = replaceLightNums( vertexShader, parameters ); - vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); +function setValueV1i( gl, v ) { - fragmentShader = resolveIncludes( fragmentShader ); - fragmentShader = replaceLightNums( fragmentShader, parameters ); - fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + const cache = this.cache; - vertexShader = unrollLoops( vertexShader ); - fragmentShader = unrollLoops( fragmentShader ); + if ( cache[ 0 ] === v ) return; - if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + gl.uniform1i( this.addr, v ); - // GLSL 3.0 conversion for built-in materials and ShaderMaterial + cache[ 0 ] = v; - versionString = '#version 300 es\n'; +} - prefixVertex = [ - '#define attribute in', - '#define varying out', - '#define texture2D texture' - ].join( '\n' ) + '\n' + prefixVertex; +// Single integer / boolean vector (from flat array) - prefixFragment = [ - '#define varying in', - ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;', - ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', - '#define gl_FragDepthEXT gl_FragDepth', - '#define texture2D texture', - '#define textureCube texture', - '#define texture2DProj textureProj', - '#define texture2DLodEXT textureLod', - '#define texture2DProjLodEXT textureProjLod', - '#define textureCubeLodEXT textureLod', - '#define texture2DGradEXT textureGrad', - '#define texture2DProjGradEXT textureProjGrad', - '#define textureCubeGradEXT textureGrad' - ].join( '\n' ) + '\n' + prefixFragment; +function setValueV2i( gl, v ) { - } + const cache = this.cache; - const vertexGlsl = versionString + prefixVertex + vertexShader; - const fragmentGlsl = versionString + prefixFragment + fragmentShader; + if ( arraysEqual( cache, v ) ) return; - // console.log( '*VERTEX*', vertexGlsl ); - // console.log( '*FRAGMENT*', fragmentGlsl ); + gl.uniform2iv( this.addr, v ); - const glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); - const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); + copyArray( cache, v ); - gl.attachShader( program, glVertexShader ); - gl.attachShader( program, glFragmentShader ); +} - // Force a particular attribute to index 0. +function setValueV3i( gl, v ) { - if ( parameters.index0AttributeName !== undefined ) { + const cache = this.cache; - gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + if ( arraysEqual( cache, v ) ) return; - } else if ( parameters.morphTargets === true ) { + gl.uniform3iv( this.addr, v ); - // programs with morphTargets displace position out of attribute 0 - gl.bindAttribLocation( program, 0, 'position' ); + copyArray( cache, v ); - } +} - gl.linkProgram( program ); +function setValueV4i( gl, v ) { - // check for link errors - if ( renderer.debug.checkShaderErrors ) { + const cache = this.cache; - const programLog = gl.getProgramInfoLog( program ).trim(); - const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); - const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + if ( arraysEqual( cache, v ) ) return; - let runnable = true; - let haveDiagnostics = true; + gl.uniform4iv( this.addr, v ); - if ( gl.getProgramParameter( program, 35714 ) === false ) { + copyArray( cache, v ); - runnable = false; +} - const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); - const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); +// Single unsigned integer - console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors ); +function setValueV1ui( gl, v ) { - } else if ( programLog !== '' ) { + const cache = this.cache; - console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); + if ( cache[ 0 ] === v ) return; - } else if ( vertexLog === '' || fragmentLog === '' ) { + gl.uniform1ui( this.addr, v ); - haveDiagnostics = false; + cache[ 0 ] = v; - } +} - if ( haveDiagnostics ) { +// Single unsigned integer vector (from flat array) - this.diagnostics = { +function setValueV2ui( gl, v ) { - runnable: runnable, + const cache = this.cache; - programLog: programLog, + if ( arraysEqual( cache, v ) ) return; - vertexShader: { + gl.uniform2uiv( this.addr, v ); - log: vertexLog, - prefix: prefixVertex + copyArray( cache, v ); - }, +} - fragmentShader: { +function setValueV3ui( gl, v ) { - log: fragmentLog, - prefix: prefixFragment + const cache = this.cache; - } + if ( arraysEqual( cache, v ) ) return; - }; + gl.uniform3uiv( this.addr, v ); - } + copyArray( cache, v ); - } +} - // Clean up +function setValueV4ui( gl, v ) { - // Crashes in iOS9 and iOS10. #18402 - // gl.detachShader( program, glVertexShader ); - // gl.detachShader( program, glFragmentShader ); + const cache = this.cache; - gl.deleteShader( glVertexShader ); - gl.deleteShader( glFragmentShader ); + if ( arraysEqual( cache, v ) ) return; - // set up caching for uniform locations + gl.uniform4uiv( this.addr, v ); - let cachedUniforms; + copyArray( cache, v ); - this.getUniforms = function () { +} - if ( cachedUniforms === undefined ) { - cachedUniforms = new WebGLUniforms( gl, program ); +// Single texture (2D / Cube) - } +function setValueT1( gl, v, textures ) { - return cachedUniforms; + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - }; + if ( cache[ 0 ] !== unit ) { - // set up caching for attribute locations + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - let cachedAttributes; + } - this.getAttributes = function () { + textures.setTexture2D( v || emptyTexture, unit ); - if ( cachedAttributes === undefined ) { +} - cachedAttributes = fetchAttributeLocations( gl, program ); +function setValueT3D1( gl, v, textures ) { - } + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - return cachedAttributes; + if ( cache[ 0 ] !== unit ) { - }; + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - // free resource + } - this.destroy = function () { + textures.setTexture3D( v || empty3dTexture, unit ); - bindingStates.releaseStatesOfProgram( this ); +} - gl.deleteProgram( program ); - this.program = undefined; +function setValueT6( gl, v, textures ) { - }; + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - // + if ( cache[ 0 ] !== unit ) { - this.name = parameters.shaderName; - this.id = programIdCount ++; - this.cacheKey = cacheKey; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - return this; + } -} + textures.setTextureCube( v || emptyCubeTexture, unit ); -function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) { +} - const programs = []; +function setValueT2DArray1( gl, v, textures ) { - const isWebGL2 = capabilities.isWebGL2; - const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; - const floatVertexTextures = capabilities.floatVertexTextures; - const maxVertexUniforms = capabilities.maxVertexUniforms; - const vertexTextures = capabilities.vertexTextures; + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - let precision = capabilities.precision; + if ( cache[ 0 ] !== unit ) { - const shaderIDs = { - MeshDepthMaterial: 'depth', - MeshDistanceMaterial: 'distanceRGBA', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshToonMaterial: 'toon', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - MeshMatcapMaterial: 'matcap', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points', - ShadowMaterial: 'shadow', - SpriteMaterial: 'sprite' - }; + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - const parameterNames = [ - 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', - 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', - 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', - 'roughnessMap', 'metalnessMap', 'gradientMap', - 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', - 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', - 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', - 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha', - 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', - 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', - 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', - 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', - 'sheen', 'transmissionMap' - ]; + } - function getMaxBones( object ) { + textures.setTexture2DArray( v || emptyArrayTexture, unit ); - const skeleton = object.skeleton; - const bones = skeleton.bones; +} - if ( floatVertexTextures ) { +// Helper to pick the right setter for the singular case - return 1024; +function getSingularSetter( type ) { - } else { + switch ( type ) { - // 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) + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 - const nVertexUniforms = maxVertexUniforms; - const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 - const maxBones = Math.min( nVertexMatrices, bones.length ); + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 - if ( maxBones < bones.length ) { + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 - console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' ); - return 0; + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; - } + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; - return maxBones; + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; - } + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; } - function getTextureEncodingFromMap( map ) { +} - let encoding; - if ( map && map.isTexture ) { +// Array of scalars - encoding = map.encoding; +function setValueV1fArray( gl, v ) { - } else if ( map && map.isWebGLRenderTarget ) { + gl.uniform1fv( this.addr, v ); - console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' ); - encoding = map.texture.encoding; +} - } else { +// Array of vectors (from flat array or array of THREE.VectorN) - encoding = LinearEncoding; +function setValueV2fArray( gl, v ) { - } + const data = flatten( v, this.size, 2 ); - return encoding; + gl.uniform2fv( this.addr, data ); - } +} - function getParameters( material, lights, shadows, scene, object ) { +function setValueV3fArray( gl, v ) { - const fog = scene.fog; - const environment = material.isMeshStandardMaterial ? scene.environment : null; + const data = flatten( v, this.size, 3 ); - const envMap = cubemaps.get( material.envMap || environment ); + gl.uniform3fv( this.addr, data ); - const shaderID = shaderIDs[ material.type ]; +} - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) +function setValueV4fArray( gl, v ) { - const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0; + const data = flatten( v, this.size, 4 ); - if ( material.precision !== null ) { + gl.uniform4fv( this.addr, data ); - precision = capabilities.getMaxPrecision( material.precision ); - - if ( precision !== material.precision ) { +} - console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); +// Array of matrices (from flat array or array of THREE.MatrixN) - } +function setValueM2Array( gl, v ) { - } + const data = flatten( v, this.size, 4 ); - let vertexShader, fragmentShader; + gl.uniformMatrix2fv( this.addr, false, data ); - if ( shaderID ) { +} - const shader = ShaderLib[ shaderID ]; +function setValueM3Array( gl, v ) { - vertexShader = shader.vertexShader; - fragmentShader = shader.fragmentShader; + const data = flatten( v, this.size, 9 ); - } else { + gl.uniformMatrix3fv( this.addr, false, data ); - vertexShader = material.vertexShader; - fragmentShader = material.fragmentShader; +} - } +function setValueM4Array( gl, v ) { - const currentRenderTarget = renderer.getRenderTarget(); + const data = flatten( v, this.size, 16 ); - const parameters = { + gl.uniformMatrix4fv( this.addr, false, data ); - isWebGL2: isWebGL2, +} - shaderID: shaderID, - shaderName: material.type, +// Array of integer / boolean - vertexShader: vertexShader, - fragmentShader: fragmentShader, - defines: material.defines, +function setValueV1iArray( gl, v ) { - isRawShaderMaterial: material.isRawShaderMaterial === true, - glslVersion: material.glslVersion, + gl.uniform1iv( this.addr, v ); - precision: precision, +} - instancing: object.isInstancedMesh === true, - instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, +// Array of integer / boolean vectors (from flat array) - supportsVertexTextures: vertexTextures, - outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding, - map: !! material.map, - mapEncoding: getTextureEncodingFromMap( material.map ), - matcap: !! material.matcap, - matcapEncoding: getTextureEncodingFromMap( material.matcap ), - envMap: !! envMap, - envMapMode: envMap && envMap.mapping, - envMapEncoding: getTextureEncodingFromMap( envMap ), - envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ), - lightMap: !! material.lightMap, - lightMapEncoding: getTextureEncodingFromMap( material.lightMap ), - aoMap: !! material.aoMap, - emissiveMap: !! material.emissiveMap, - emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ), - bumpMap: !! material.bumpMap, - normalMap: !! material.normalMap, - objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, - tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, - clearcoatMap: !! material.clearcoatMap, - clearcoatRoughnessMap: !! material.clearcoatRoughnessMap, - clearcoatNormalMap: !! material.clearcoatNormalMap, - displacementMap: !! material.displacementMap, - roughnessMap: !! material.roughnessMap, - metalnessMap: !! material.metalnessMap, - specularMap: !! material.specularMap, - alphaMap: !! material.alphaMap, +function setValueV2iArray( gl, v ) { - gradientMap: !! material.gradientMap, + gl.uniform2iv( this.addr, v ); - sheen: !! material.sheen, +} - transmissionMap: !! material.transmissionMap, +function setValueV3iArray( gl, v ) { - combine: material.combine, + gl.uniform3iv( this.addr, v ); - vertexTangents: ( material.normalMap && material.vertexTangents ), - vertexColors: material.vertexColors, - vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap, - uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap, +} - fog: !! fog, - useFog: material.fog, - fogExp2: ( fog && fog.isFogExp2 ), +function setValueV4iArray( gl, v ) { - flatShading: !! material.flatShading, + gl.uniform4iv( this.addr, v ); - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: logarithmicDepthBuffer, +} - skinning: material.skinning && maxBones > 0, - maxBones: maxBones, - useVertexTexture: floatVertexTextures, +// Array of unsigned integer - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: renderer.maxMorphTargets, - maxMorphNormals: renderer.maxMorphNormals, +function setValueV1uiArray( gl, v ) { - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numRectAreaLights: lights.rectArea.length, - numHemiLights: lights.hemi.length, + gl.uniform1uiv( this.addr, v ); - numDirLightShadows: lights.directionalShadowMap.length, - numPointLightShadows: lights.pointShadowMap.length, - numSpotLightShadows: lights.spotShadowMap.length, +} - numClippingPlanes: clipping.numPlanes, - numClipIntersection: clipping.numIntersection, +// Array of unsigned integer vectors (from flat array) - dithering: material.dithering, +function setValueV2uiArray( gl, v ) { - shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, - shadowMapType: renderer.shadowMap.type, + gl.uniform2uiv( this.addr, v ); - toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, +} - premultipliedAlpha: material.premultipliedAlpha, +function setValueV3uiArray( gl, v ) { - alphaTest: material.alphaTest, - doubleSided: material.side === DoubleSide, - flipSided: material.side === BackSide, + gl.uniform3uiv( this.addr, v ); - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false, +} - index0AttributeName: material.index0AttributeName, +function setValueV4uiArray( gl, v ) { - extensionDerivatives: material.extensions && material.extensions.derivatives, - extensionFragDepth: material.extensions && material.extensions.fragDepth, - extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, - extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, + gl.uniform4uiv( this.addr, v ); - rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ), - rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ), - rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ), +} - customProgramCacheKey: material.customProgramCacheKey() - }; +// Array of textures (2D / 3D / Cube / 2DArray) - return parameters; +function setValueT1Array( gl, v, textures ) { - } + const n = v.length; - function getProgramCacheKey( parameters ) { + const units = allocTexUnits( textures, n ); - const array = []; + gl.uniform1iv( this.addr, units ); - if ( parameters.shaderID ) { + for ( let i = 0; i !== n; ++ i ) { - array.push( parameters.shaderID ); + textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - } else { + } - array.push( parameters.fragmentShader ); - array.push( parameters.vertexShader ); +} - } +function setValueT3DArray( gl, v, textures ) { - if ( parameters.defines !== undefined ) { + const n = v.length; - for ( const name in parameters.defines ) { + const units = allocTexUnits( textures, n ); - array.push( name ); - array.push( parameters.defines[ name ] ); + gl.uniform1iv( this.addr, units ); - } + for ( let i = 0; i !== n; ++ i ) { - } + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); - if ( parameters.isRawShaderMaterial === false ) { + } - for ( let i = 0; i < parameterNames.length; i ++ ) { +} - array.push( parameters[ parameterNames[ i ] ] ); +function setValueT6Array( gl, v, textures ) { - } + const n = v.length; - array.push( renderer.outputEncoding ); - array.push( renderer.gammaFactor ); + const units = allocTexUnits( textures, n ); - } + gl.uniform1iv( this.addr, units ); - array.push( parameters.customProgramCacheKey ); + for ( let i = 0; i !== n; ++ i ) { - return array.join(); + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); } - function getUniforms( material ) { - - const shaderID = shaderIDs[ material.type ]; - let uniforms; +} - if ( shaderID ) { +function setValueT2DArrayArray( gl, v, textures ) { - const shader = ShaderLib[ shaderID ]; - uniforms = UniformsUtils.clone( shader.uniforms ); + const n = v.length; - } else { + const units = allocTexUnits( textures, n ); - uniforms = material.uniforms; + gl.uniform1iv( this.addr, units ); - } + for ( let i = 0; i !== n; ++ i ) { - return uniforms; + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); } - function acquireProgram( parameters, cacheKey ) { +} - let program; - // Check if code has been already compiled - for ( let p = 0, pl = programs.length; p < pl; p ++ ) { +// Helper to pick the right setter for a pure (bottom-level) array - const preexistingProgram = programs[ p ]; +function getPureArraySetter( type ) { - if ( preexistingProgram.cacheKey === cacheKey ) { + switch ( type ) { - program = preexistingProgram; - ++ program.usedTimes; + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 - break; + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 - } + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 - } + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 - if ( program === undefined ) { + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; - program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); - programs.push( program ); + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; - } + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; - return program; + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; } - function releaseProgram( program ) { +} - if ( -- program.usedTimes === 0 ) { +// --- Uniform Classes --- - // Remove from unordered set - const i = programs.indexOf( program ); - programs[ i ] = programs[ programs.length - 1 ]; - programs.pop(); +class SingleUniform { - // Free WebGL resources - program.destroy(); + constructor( id, activeInfo, addr ) { - } + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); - } + // this.path = activeInfo.name; // DEBUG - return { - getParameters: getParameters, - getProgramCacheKey: getProgramCacheKey, - getUniforms: getUniforms, - acquireProgram: acquireProgram, - releaseProgram: releaseProgram, - // Exposed for resource monitoring & error feedback via renderer.info: - programs: programs - }; + } } -function WebGLProperties() { - - let properties = new WeakMap(); +class PureArrayUniform { - function get( object ) { + constructor( id, activeInfo, addr ) { - let map = properties.get( object ); + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - if ( map === undefined ) { + // this.path = activeInfo.name; // DEBUG - map = {}; - properties.set( object, map ); + } - } +} - return map; +class StructuredUniform { - } + constructor( id ) { - function remove( object ) { + this.id = id; - properties.delete( object ); + this.seq = []; + this.map = {}; } - function update( object, key, value ) { + setValue( gl, value, textures ) { - properties.get( object )[ key ] = value; + const seq = this.seq; - } + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - function dispose() { + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); - properties = new WeakMap(); + } } - return { - get: get, - remove: remove, - update: update, - dispose: dispose - }; - } -function painterSortStable( a, b ) { +// --- Top-level --- - if ( a.groupOrder !== b.groupOrder ) { +// Parser - builds up the property tree from the path strings - return a.groupOrder - b.groupOrder; +const RePathPart = /(\w+)(\])?(\[|\.)?/g; - } else if ( a.renderOrder !== b.renderOrder ) { +// 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 a.renderOrder - b.renderOrder; +function addUniform( container, uniformObject ) { - } else if ( a.program !== b.program ) { + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - return a.program.id - b.program.id; +} - } else if ( a.material.id !== b.material.id ) { +function parseUniform( activeInfo, addr, container ) { - return a.material.id - b.material.id; + const path = activeInfo.name, + pathLength = path.length; - } else if ( a.z !== b.z ) { + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - return a.z - b.z; + while ( true ) { - } else { + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; - return a.id - b.id; + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - } + if ( idIsIndex ) id = id | 0; // convert to integer -} + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { -function reversePainterSortStable( a, b ) { + // bare name or "pure" bottom-level array "[0]" suffix - if ( a.groupOrder !== b.groupOrder ) { + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - return a.groupOrder - b.groupOrder; + break; - } else if ( a.renderOrder !== b.renderOrder ) { + } else { - return a.renderOrder - b.renderOrder; + // step into inner node / create it in case it doesn't exist - } else if ( a.z !== b.z ) { + const map = container.map; + let next = map[ id ]; - return b.z - a.z; + if ( next === undefined ) { - } else { + next = new StructuredUniform( id ); + addUniform( container, next ); - return a.id - b.id; + } + + container = next; + + } } } +// Root Container -function WebGLRenderList( properties ) { +class WebGLUniforms { - const renderItems = []; - let renderItemsIndex = 0; + constructor( gl, program ) { - const opaque = []; - const transparent = []; + this.seq = []; + this.map = {}; - const defaultProgram = { id: - 1 }; + const n = gl.getProgramParameter( program, 35718 ); - function init() { + for ( let i = 0; i < n; ++ i ) { - renderItemsIndex = 0; + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); - opaque.length = 0; - transparent.length = 0; + parseUniform( info, addr, this ); + + } } - function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + setValue( gl, name, value, textures ) { - let renderItem = renderItems[ renderItemsIndex ]; - const materialProperties = properties.get( material ); + const u = this.map[ name ]; - if ( renderItem === undefined ) { + if ( u !== undefined ) u.setValue( gl, value, textures ); - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - program: materialProperties.program || defaultProgram, - groupOrder: groupOrder, - renderOrder: object.renderOrder, - z: z, - group: group - }; + } - renderItems[ renderItemsIndex ] = renderItem; + setOptional( gl, object, name ) { - } else { + const v = object[ name ]; - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.program = materialProperties.program || defaultProgram; - renderItem.groupOrder = groupOrder; - renderItem.renderOrder = object.renderOrder; - renderItem.z = z; - renderItem.group = group; + if ( v !== undefined ) this.setValue( gl, name, v ); - } + } - renderItemsIndex ++; + static upload( gl, seq, values, textures ) { - return renderItem; + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - } + const u = seq[ i ], + v = values[ u.id ]; - function push( object, geometry, material, groupOrder, z, group ) { + if ( v.needsUpdate !== false ) { - const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); - ( material.transparent === true ? transparent : opaque ).push( renderItem ); + } + + } } - function unshift( object, geometry, material, groupOrder, z, group ) { + static seqWithValue( seq, values ) { - const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + const r = []; - ( material.transparent === true ? transparent : opaque ).unshift( renderItem ); + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - } + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); - function sort( customOpaqueSort, customTransparentSort ) { + } - if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); - if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + return r; } - function finish() { +} - // Clear references from inactive renderItems in the list +function WebGLShader( gl, type, string ) { - for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + const shader = gl.createShader( type ); - const renderItem = renderItems[ i ]; + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - if ( renderItem.id === null ) break; + return shader; - renderItem.id = null; - renderItem.object = null; - renderItem.geometry = null; - renderItem.material = null; - renderItem.program = null; - renderItem.group = null; +} - } +let programIdCount = 0; + +function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); } - return { + return lines2.join( '\n' ); - opaque: opaque, - transparent: transparent, +} - init: init, - push: push, - unshift: unshift, - finish: finish, +function getEncodingComponents( encoding ) { - sort: sort - }; + switch ( encoding ) { + + case LinearEncoding: + return [ 'Linear', '( value )' ]; + case sRGBEncoding: + return [ 'sRGB', '( value )' ]; + default: + console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding ); + return [ 'Linear', '( value )' ]; + + } } -function WebGLRenderLists( properties ) { +function getShaderErrors( gl, shader, type ) { - let lists = new WeakMap(); + const status = gl.getShaderParameter( shader, 35713 ); + const errors = gl.getShaderInfoLog( shader ).trim(); - function get( scene, renderCallDepth ) { + if ( status && errors === '' ) return ''; - let list; + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { - if ( lists.has( scene ) === false ) { + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - list = new WebGLRenderList( properties ); - lists.set( scene, [ list ] ); + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); - } else { + } else { - if ( renderCallDepth >= lists.get( scene ).length ) { + return errors; - list = new WebGLRenderList( properties ); - lists.get( scene ).push( list ); + } - } else { +} - list = lists.get( scene )[ renderCallDepth ]; +function getTexelEncodingFunction( functionName, encoding ) { - } + const components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; - } +} - return list; +function getToneMappingFunction( functionName, toneMapping ) { - } + let toneMappingName; - function dispose() { + switch ( toneMapping ) { - lists = new WeakMap(); + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; + + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; + + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; + + case CustomToneMapping: + toneMappingName = 'Custom'; + break; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); + toneMappingName = 'Linear'; } - return { - get: get, - dispose: dispose - }; + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; } -function UniformsCache() { +function generateExtensions( parameters ) { - const lights = {}; + const chunks = [ + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', + ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; - return { + return chunks.filter( filterEmptyLine ).join( '\n' ); - get: function ( light ) { +} - if ( lights[ light.id ] !== undefined ) { +function generateDefines( defines ) { - return lights[ light.id ]; + const chunks = []; - } + for ( const name in defines ) { - let uniforms; + const value = defines[ name ]; - switch ( light.type ) { + if ( value === false ) continue; - case 'DirectionalLight': - uniforms = { - direction: new Vector3(), - color: new Color() - }; - break; + chunks.push( '#define ' + name + ' ' + value ); - case 'SpotLight': - uniforms = { - position: new Vector3(), + } + + return chunks.join( '\n' ); + +} + +function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, 35721 ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === 35674 ) locationSize = 2; + if ( info.type === 35675 ) locationSize = 3; + if ( info.type === 35676 ) locationSize = 4; + + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + +} + +function filterEmptyLine( string ) { + + return string !== ''; + +} + +function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + +} + +function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + +} + +// Resolve Includes + +const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + +function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + +} + +function includeReplacer( match, include ) { + + const string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + throw new Error( 'Can not resolve #include <' + include + '>' ); + + } + + return resolveIncludes( string ); + +} + +// Unroll Loops + +const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + +function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + +} + +function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + +} + +// + +function generatePrecision( parameters ) { + + let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + +} + +function generateShadowMapTypeDefine( parameters ) { + + let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + + if ( parameters.shadowMapType === PCFShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + + } else if ( parameters.shadowMapType === VSMShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + + } + + return shadowMapTypeDefine; + +} + +function generateEnvMapTypeDefine( parameters ) { + + let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; + + case CubeUVReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; + + } + + } + + return envMapTypeDefine; + +} + +function generateEnvMapModeDefine( parameters ) { + + let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeRefractionMapping: + + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; + + } + + } + + return envMapModeDefine; + +} + +function generateEnvMapBlendingDefine( parameters ) { + + let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; + + if ( parameters.envMap ) { + + switch ( parameters.combine ) { + + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; + + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; + + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; + + } + + } + + return envMapBlendingDefine; + +} + +function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + +} + +function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // console.log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + customExtensions, + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', + + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', + + ' #ifdef USE_MORPHNORMALS', + + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', + + ' #else', + + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', + + ' #endif', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + customExtensions, + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + + parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( 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.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + 'precision mediump sampler2DArray;', + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.morphTargets === true ) { + + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programLog = gl.getProgramInfoLog( program ).trim(); + const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, 35714 ) === false ) { + + runnable = false; + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + console.error( + 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } else if ( programLog !== '' ) { + + console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + this.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + cachedUniforms = new WebGLUniforms( gl, program ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + return cachedAttributes; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +let _id = 0; + +class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material ) { + + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + + const vertexShaderStage = this._getShaderStage( vertexShader ); + const fragmentShaderStage = this._getShaderStage( fragmentShader ); + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderID( material ) { + + return this._getShaderStage( material.vertexShader ).id; + + } + + getFragmentShaderID( material ) { + + return this._getShaderStage( material.fragmentShader ).id; + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + +} + +class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + +} + +function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const programs = []; + + const isWebGL2 = capabilities.isWebGL2; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const vertexTextures = capabilities.vertexTextures; + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getParameters( material, lights, shadows, scene, object ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + _customShaders.update( material ); + + customVertexShaderID = _customShaders.getVertexShaderID( material ); + customFragmentShaderID = _customShaders.getFragmentShaderID( material ); + + } + + const currentRenderTarget = renderer.getRenderTarget(); + + const useAlphaTest = material.alphaTest > 0; + const useClearcoat = material.clearcoat > 0; + const useIridescence = material.iridescence > 0; + + const parameters = { + + isWebGL2: isWebGL2, + + shaderID: shaderID, + shaderName: material.type, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + instancing: object.isInstancedMesh === true, + instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, + + supportsVertexTextures: vertexTextures, + outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ), + map: !! material.map, + matcap: !! material.matcap, + envMap: !! envMap, + envMapMode: envMap && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, + tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, + + decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ), + + clearcoat: useClearcoat, + clearcoatMap: useClearcoat && !! material.clearcoatMap, + clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap, + clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap, + + iridescence: useIridescence, + iridescenceMap: useIridescence && !! material.iridescenceMap, + iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap, + + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + specularIntensityMap: !! material.specularIntensityMap, + specularColorMap: !! material.specularColorMap, + + opaque: material.transparent === false && material.blending === NormalBlending, + + alphaMap: !! material.alphaMap, + alphaTest: useAlphaTest, + + gradientMap: !! material.gradientMap, + + sheen: material.sheen > 0, + sheenColorMap: !! material.sheenColorMap, + sheenRoughnessMap: !! material.sheenRoughnessMap, + + transmission: material.transmission > 0, + transmissionMap: !! material.transmissionMap, + thicknessMap: !! material.thicknessMap, + + combine: material.combine, + + vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( fog && fog.isFogExp2 ), + + flatShading: !! material.flatShading, + + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: !! material.depthPacking, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionDerivatives: material.extensions && material.extensions.derivatives, + extensionFragDepth: material.extensions && material.extensions.fragDepth, + extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, + extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, + + rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ), + rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ), + rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputEncoding ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputEncoding ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.combine ); + array.push( parameters.vertexUvs ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.isWebGL2 ) + _programLayers.enable( 0 ); + if ( parameters.supportsVertexTextures ) + _programLayers.enable( 1 ); + if ( parameters.instancing ) + _programLayers.enable( 2 ); + if ( parameters.instancingColor ) + _programLayers.enable( 3 ); + if ( parameters.map ) + _programLayers.enable( 4 ); + if ( parameters.matcap ) + _programLayers.enable( 5 ); + if ( parameters.envMap ) + _programLayers.enable( 6 ); + if ( parameters.lightMap ) + _programLayers.enable( 7 ); + if ( parameters.aoMap ) + _programLayers.enable( 8 ); + if ( parameters.emissiveMap ) + _programLayers.enable( 9 ); + if ( parameters.bumpMap ) + _programLayers.enable( 10 ); + if ( parameters.normalMap ) + _programLayers.enable( 11 ); + if ( parameters.objectSpaceNormalMap ) + _programLayers.enable( 12 ); + if ( parameters.tangentSpaceNormalMap ) + _programLayers.enable( 13 ); + if ( parameters.clearcoat ) + _programLayers.enable( 14 ); + if ( parameters.clearcoatMap ) + _programLayers.enable( 15 ); + if ( parameters.clearcoatRoughnessMap ) + _programLayers.enable( 16 ); + if ( parameters.clearcoatNormalMap ) + _programLayers.enable( 17 ); + if ( parameters.iridescence ) + _programLayers.enable( 18 ); + if ( parameters.iridescenceMap ) + _programLayers.enable( 19 ); + if ( parameters.iridescenceThicknessMap ) + _programLayers.enable( 20 ); + if ( parameters.displacementMap ) + _programLayers.enable( 21 ); + if ( parameters.specularMap ) + _programLayers.enable( 22 ); + if ( parameters.roughnessMap ) + _programLayers.enable( 23 ); + if ( parameters.metalnessMap ) + _programLayers.enable( 24 ); + if ( parameters.gradientMap ) + _programLayers.enable( 25 ); + if ( parameters.alphaMap ) + _programLayers.enable( 26 ); + if ( parameters.alphaTest ) + _programLayers.enable( 27 ); + if ( parameters.vertexColors ) + _programLayers.enable( 28 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 29 ); + if ( parameters.vertexUvs ) + _programLayers.enable( 30 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 31 ); + if ( parameters.uvsVertexOnly ) + _programLayers.enable( 32 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.skinning ) + _programLayers.enable( 4 ); + if ( parameters.morphTargets ) + _programLayers.enable( 5 ); + if ( parameters.morphNormals ) + _programLayers.enable( 6 ); + if ( parameters.morphColors ) + _programLayers.enable( 7 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 8 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 9 ); + if ( parameters.physicallyCorrectLights ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.specularIntensityMap ) + _programLayers.enable( 15 ); + if ( parameters.specularColorMap ) + _programLayers.enable( 16 ); + if ( parameters.transmission ) + _programLayers.enable( 17 ); + if ( parameters.transmissionMap ) + _programLayers.enable( 18 ); + if ( parameters.thicknessMap ) + _programLayers.enable( 19 ); + if ( parameters.sheen ) + _programLayers.enable( 20 ); + if ( parameters.sheenColorMap ) + _programLayers.enable( 21 ); + if ( parameters.sheenRoughnessMap ) + _programLayers.enable( 22 ); + if ( parameters.decodeVideoTexture ) + _programLayers.enable( 23 ); + if ( parameters.opaque ) + _programLayers.enable( 24 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program; + + // Check if code has been already compiled + for ( let p = 0, pl = programs.length; p < pl; p ++ ) { + + const preexistingProgram = programs[ p ]; + + if ( preexistingProgram.cacheKey === cacheKey ) { + + program = preexistingProgram; + ++ program.usedTimes; + + break; + + } + + } + + if ( program === undefined ) { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + +} + +function WebGLProperties() { + + let properties = new WeakMap(); + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; + +} + +function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + +} + +function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + +} + + +function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + +} + +function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), direction: new Vector3(), color: new Color(), distance: 0, @@ -17980,9 +19953,9 @@ function ShadowUniformsCache() { let nextVersion = 0; -function shadowCastingLightsFirst( lightA, lightB ) { +function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { - return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 ); + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); } @@ -18005,7 +19978,8 @@ function WebGLLights( extensions, capabilities ) { numDirectionalShadows: - 1, numPointShadows: - 1, - numSpotShadows: - 1 + numSpotShadows: - 1, + numSpotMaps: - 1 }, ambient: [ 0, 0, 0 ], @@ -18015,9 +19989,10 @@ function WebGLLights( extensions, capabilities ) { directionalShadowMap: [], directionalShadowMatrix: [], spot: [], + spotLightMap: [], spotShadow: [], spotShadowMap: [], - spotShadowMatrix: [], + spotLightMatrix: [], rectArea: [], rectAreaLTC1: null, rectAreaLTC2: null, @@ -18025,7 +20000,8 @@ function WebGLLights( extensions, capabilities ) { pointShadow: [], pointShadowMap: [], pointShadowMatrix: [], - hemi: [] + hemi: [], + numSpotLightShadowsWithMaps: 0 }; @@ -18035,7 +20011,7 @@ function WebGLLights( extensions, capabilities ) { const matrix4 = new Matrix4(); const matrix42 = new Matrix4(); - function setup( lights ) { + function setup( lights, physicallyCorrectLights ) { let r = 0, g = 0, b = 0; @@ -18050,8 +20026,14 @@ function WebGLLights( extensions, capabilities ) { let numDirectionalShadows = 0; let numPointShadows = 0; let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; - lights.sort( shadowCastingLightsFirst ); + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + // artist-friendly light intensity scaling factor + const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1; for ( let i = 0, l = lights.length; i < l; i ++ ) { @@ -18065,9 +20047,9 @@ function WebGLLights( extensions, capabilities ) { if ( light.isAmbientLight ) { - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + r += color.r * intensity * scaleFactor; + g += color.g * intensity * scaleFactor; + b += color.b * intensity * scaleFactor; } else if ( light.isLightProbe ) { @@ -18081,7 +20063,7 @@ function WebGLLights( extensions, capabilities ) { const uniforms = cache.get( light ); - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); if ( light.castShadow ) { @@ -18112,16 +20094,33 @@ function WebGLLights( extensions, capabilities ) { uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor ); uniforms.distance = distance; uniforms.coneCos = Math.cos( light.angle ); uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); uniforms.decay = light.decay; - if ( light.castShadow ) { + state.spot[ spotLength ] = uniforms; - const shadow = light.shadow; + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { const shadowUniforms = shadowCache.get( light ); @@ -18132,14 +20131,11 @@ function WebGLLights( extensions, capabilities ) { state.spotShadow[ spotLength ] = shadowUniforms; state.spotShadowMap[ spotLength ] = shadowMap; - state.spotShadowMatrix[ spotLength ] = light.shadow.matrix; numSpotShadows ++; } - state.spot[ spotLength ] = uniforms; - spotLength ++; } else if ( light.isRectAreaLight ) { @@ -18163,7 +20159,7 @@ function WebGLLights( extensions, capabilities ) { const uniforms = cache.get( light ); - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); uniforms.distance = light.distance; uniforms.decay = light.decay; @@ -18196,8 +20192,8 @@ function WebGLLights( extensions, capabilities ) { const uniforms = cache.get( light ); - uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); - uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor ); state.hemi[ hemiLength ] = uniforms; @@ -18253,7 +20249,8 @@ function WebGLLights( extensions, capabilities ) { hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || - hash.numSpotShadows !== numSpotShadows ) { + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps ) { state.directional.length = directionalLength; state.spot.length = spotLength; @@ -18269,7 +20266,9 @@ function WebGLLights( extensions, capabilities ) { state.spotShadowMap.length = numSpotShadows; state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadowMatrix.length = numPointShadows; - state.spotShadowMatrix.length = numSpotShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; hash.directionalLength = directionalLength; hash.pointLength = pointLength; @@ -18280,6 +20279,7 @@ function WebGLLights( extensions, capabilities ) { hash.numDirectionalShadows = numDirectionalShadows; hash.numPointShadows = numPointShadows; hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; state.version = nextVersion ++; @@ -18362,7 +20362,6 @@ function WebGLLights( extensions, capabilities ) { uniforms.direction.setFromMatrixPosition( light.matrixWorld ); uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); hemiLength ++; @@ -18406,9 +20405,9 @@ function WebGLRenderState( extensions, capabilities ) { } - function setupLights() { + function setupLights( physicallyCorrectLights ) { - lights.setup( lightsArray ); + lights.setup( lightsArray, physicallyCorrectLights ); } @@ -18443,23 +20442,24 @@ function WebGLRenderStates( extensions, capabilities ) { function get( scene, renderCallDepth = 0 ) { + const renderStateArray = renderStates.get( scene ); let renderState; - if ( renderStates.has( scene ) === false ) { + if ( renderStateArray === undefined ) { renderState = new WebGLRenderState( extensions, capabilities ); renderStates.set( scene, [ renderState ] ); } else { - if ( renderCallDepth >= renderStates.get( scene ).length ) { + if ( renderCallDepth >= renderStateArray.length ) { renderState = new WebGLRenderState( extensions, capabilities ); - renderStates.get( scene ).push( renderState ); + renderStateArray.push( renderState ); } else { - renderState = renderStates.get( scene )[ renderCallDepth ]; + renderState = renderStateArray[ renderCallDepth ]; } @@ -18482,37 +20482,18 @@ function WebGLRenderStates( extensions, capabilities ) { } -/** - * parameters = { - * - * opacity: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ - class MeshDepthMaterial extends Material { constructor( parameters ) { super(); + this.isMeshDepthMaterial = true; + this.type = 'MeshDepthMaterial'; this.depthPacking = BasicDepthPacking; - this.skinning = false; - this.morphTargets = false; - this.map = null; this.alphaMap = null; @@ -18524,8 +20505,6 @@ class MeshDepthMaterial extends Material { this.wireframe = false; this.wireframeLinewidth = 1; - this.fog = false; - this.setValues( parameters ); } @@ -18536,9 +20515,6 @@ class MeshDepthMaterial extends Material { this.depthPacking = source.depthPacking; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.map = source.map; this.alphaMap = source.alphaMap; @@ -18556,44 +20532,20 @@ class MeshDepthMaterial extends Material { } -MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - -/** - * parameters = { - * - * referencePosition: , - * nearDistance: , - * farDistance: , - * - * skinning: , - * morphTargets: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: - * - * } - */ - class MeshDistanceMaterial extends Material { constructor( parameters ) { super(); + this.isMeshDistanceMaterial = true; + this.type = 'MeshDistanceMaterial'; this.referencePosition = new Vector3(); this.nearDistance = 1; this.farDistance = 1000; - this.skinning = false; - this.morphTargets = false; - this.map = null; this.alphaMap = null; @@ -18602,8 +20554,6 @@ class MeshDistanceMaterial extends Material { this.displacementScale = 1; this.displacementBias = 0; - this.fog = false; - this.setValues( parameters ); } @@ -18616,9 +20566,6 @@ class MeshDistanceMaterial extends Material { this.nearDistance = source.nearDistance; this.farDistance = source.farDistance; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.map = source.map; this.alphaMap = source.alphaMap; @@ -18633,13 +20580,11 @@ class MeshDistanceMaterial extends Material { } -MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; +const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; -var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; +const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; -var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; - -function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { +function WebGLShadowMap( _renderer, _objects, _capabilities ) { let _frustum = new Frustum(); @@ -18648,29 +20593,27 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { _viewport = new Vector4(), - _depthMaterials = [], - _distanceMaterials = [], + _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, - _materialCache = {}; + _maxTextureSize = _capabilities.maxTextureSize; const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide }; const shadowMaterialVertical = new ShaderMaterial( { - defines: { - SAMPLE_RATE: 2.0 / 8.0, - HALF_SAMPLE_RATE: 1.0 / 8.0 + VSM_SAMPLES: 8 }, - uniforms: { shadow_pass: { value: null }, resolution: { value: new Vector2() }, radius: { value: 4.0 } }, - vertexShader: vsm_vert, - - fragmentShader: vsm_frag + vertexShader: vertex, + fragmentShader: fragment } ); @@ -18740,19 +20683,19 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { _viewportSize.copy( shadow.mapSize ); - if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) { + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { - if ( _shadowMapSize.x > maxTextureSize ) { + if ( _shadowMapSize.x > _maxTextureSize ) { - _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x ); + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; shadow.mapSize.x = _viewportSize.x; } - if ( _shadowMapSize.y > maxTextureSize ) { + if ( _shadowMapSize.y > _maxTextureSize ) { - _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y ); + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; shadow.mapSize.y = _viewportSize.y; @@ -18760,22 +20703,9 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } - if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { - - const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; - - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - shadow.map.texture.name = light.name + '.shadowMap'; - - shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - - shadow.camera.updateProjectionMatrix(); - - } - if ( shadow.map === null ) { - const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadow.map.texture.name = light.name + '.shadowMap'; @@ -18812,7 +20742,7 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { // do blur pass for VSM - if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { VSMPass( shadow, camera ); @@ -18832,6 +20762,22 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { const geometry = _objects.update( fullScreenMesh ); + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + // vertical pass shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; @@ -18852,107 +20798,25 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } - function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) { - - const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; - - let material = _depthMaterials[ index ]; - - if ( material === undefined ) { - - material = new MeshDepthMaterial( { - - depthPacking: RGBADepthPacking, - - morphTargets: useMorphing, - skinning: useSkinning - - } ); - - _depthMaterials[ index ] = material; - - } - - return material; - - } - - function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) { - - const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; - - let material = _distanceMaterials[ index ]; - - if ( material === undefined ) { - - material = new MeshDistanceMaterial( { - - morphTargets: useMorphing, - skinning: useSkinning - - } ); - - _distanceMaterials[ index ] = material; - - } - - return material; - - } - - function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) { + function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) { let result = null; - let getMaterialVariant = getDepthMaterialVariant; - let customMaterial = object.customDepthMaterial; - - if ( light.isPointLight === true ) { - - getMaterialVariant = getDistanceMaterialVariant; - customMaterial = object.customDistanceMaterial; - - } - - if ( customMaterial === undefined ) { - - let useMorphing = false; - - if ( material.morphTargets === true ) { - - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - - } - - let useSkinning = false; + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; - if ( object.isSkinnedMesh === true ) { + if ( customMaterial !== undefined ) { - if ( material.skinning === true ) { - - useSkinning = true; - - } else { - - console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object ); - - } - - } - - const useInstancing = object.isInstancedMesh === true; - - result = getMaterialVariant( useMorphing, useSkinning, useInstancing ); + result = customMaterial; } else { - result = customMaterial; + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; } - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) ) { // in this case we need a unique material instance reflecting the // appropriate state @@ -18994,10 +20858,17 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.clipShadows = material.clipShadows; result.clippingPlanes = material.clippingPlanes; result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; result.linewidth = material.linewidth; @@ -19039,7 +20910,7 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { if ( groupMaterial && groupMaterial.visible ) { - const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); + const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); @@ -19049,7 +20920,7 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } else if ( material.visible ) { - const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type ); + const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type ); _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); @@ -19384,8 +21255,15 @@ function WebGLState( gl, extensions, capabilities ) { const depthBuffer = new DepthBuffer(); const stencilBuffer = new StencilBuffer(); + const uboBindings = new WeakMap(); + const uboProgamMap = new WeakMap(); + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + let currentProgram = null; let currentBlendingEnabled = false; @@ -19427,8 +21305,11 @@ function WebGLState( gl, extensions, capabilities ) { let currentTextureSlot = null; let currentBoundTextures = {}; - const currentScissor = new Vector4(); - const currentViewport = new Vector4(); + const scissorParam = gl.getParameter( 3088 ); + const viewportParam = gl.getParameter( 2978 ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); function createTexture( type, target, count ) { @@ -19466,30 +21347,140 @@ function WebGLState( gl, extensions, capabilities ) { setCullFace( CullFaceBack ); enable( 2884 ); - setBlending( NoBlending ); + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + if ( isWebGL2 ) { + + // 36009 is equivalent to 36160 + + if ( target === 36009 ) { + + currentBoundFramebuffers[ 36160 ] = framebuffer; + + } + + if ( target === 36160 ) { + + currentBoundFramebuffers[ 36009 ] = framebuffer; + + } + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = 36064 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== 36064 ) { + + drawBuffers[ 0 ] = 36064; + + needsUpdate = true; + + } + + } - // + } else { - function enable( id ) { + if ( drawBuffers[ 0 ] !== 1029 ) { - if ( enabledCapabilities[ id ] !== true ) { + drawBuffers[ 0 ] = 1029; - gl.enable( id ); - enabledCapabilities[ id ] = true; + needsUpdate = true; + + } } - } + if ( needsUpdate ) { - function disable( id ) { + if ( capabilities.isWebGL2 ) { - if ( enabledCapabilities[ id ] !== false ) { + gl.drawBuffers( drawBuffers ); - gl.disable( id ); - enabledCapabilities[ id ] = false; + } else { + + extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + + } } + } function useProgram( program ) { @@ -19594,7 +21585,7 @@ function WebGLState( gl, extensions, capabilities ) { break; case SubtractiveBlending: - gl.blendFuncSeparate( 0, 0, 769, 771 ); + gl.blendFuncSeparate( 0, 769, 0, 1 ); break; case MultiplyBlending: @@ -19620,7 +21611,7 @@ function WebGLState( gl, extensions, capabilities ) { break; case SubtractiveBlending: - gl.blendFunc( 0, 769 ); + gl.blendFuncSeparate( 0, 769, 0, 1 ); break; case MultiplyBlending: @@ -19712,6 +21703,10 @@ function WebGLState( gl, extensions, capabilities ) { setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + material.alphaToCoverage === true + ? enable( 32926 ) + : disable( 32926 ); + } // @@ -19724,12110 +21719,11127 @@ function WebGLState( gl, extensions, capabilities ) { gl.frontFace( 2304 ); - } else { - - gl.frontFace( 2305 ); - - } - - currentFlipSided = flipSided; - - } - - } - - function setCullFace( cullFace ) { - - if ( cullFace !== CullFaceNone ) { - - enable( 2884 ); - - if ( cullFace !== currentCullFace ) { - - if ( cullFace === CullFaceBack ) { - - gl.cullFace( 1029 ); - - } else if ( cullFace === CullFaceFront ) { - - gl.cullFace( 1028 ); - - } else { - - gl.cullFace( 1032 ); - - } - - } - - } else { - - disable( 2884 ); - - } - - currentCullFace = cullFace; - - } - - function setLineWidth( width ) { - - if ( width !== currentLineWidth ) { - - if ( lineWidthAvailable ) gl.lineWidth( width ); - - currentLineWidth = width; - - } - - } - - function setPolygonOffset( polygonOffset, factor, units ) { - - if ( polygonOffset ) { - - enable( 32823 ); - - if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - - gl.polygonOffset( factor, units ); - - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; - - } - - } else { - - disable( 32823 ); - - } - - } - - function setScissorTest( scissorTest ) { - - if ( scissorTest ) { - - enable( 3089 ); - - } else { - - disable( 3089 ); - - } - - } - - // texture - - function activeTexture( webglSlot ) { - - if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1; - - if ( currentTextureSlot !== webglSlot ) { - - gl.activeTexture( webglSlot ); - currentTextureSlot = webglSlot; - - } - - } - - function bindTexture( webglType, webglTexture ) { - - if ( currentTextureSlot === null ) { - - activeTexture(); - - } - - let boundTexture = currentBoundTextures[ currentTextureSlot ]; - - if ( boundTexture === undefined ) { - - boundTexture = { type: undefined, texture: undefined }; - currentBoundTextures[ currentTextureSlot ] = boundTexture; - - } - - if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - - gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - - boundTexture.type = webglType; - boundTexture.texture = webglTexture; - - } - - } - - function unbindTexture() { - - const boundTexture = currentBoundTextures[ currentTextureSlot ]; - - if ( boundTexture !== undefined && boundTexture.type !== undefined ) { - - gl.bindTexture( boundTexture.type, null ); - - boundTexture.type = undefined; - boundTexture.texture = undefined; - - } - - } - - function compressedTexImage2D() { - - try { - - gl.compressedTexImage2D.apply( gl, arguments ); - - } catch ( error ) { - - console.error( 'THREE.WebGLState:', error ); - - } - - } - - function texImage2D() { - - try { - - gl.texImage2D.apply( gl, arguments ); - - } catch ( error ) { - - console.error( 'THREE.WebGLState:', error ); - - } - - } - - function texImage3D() { - - try { - - gl.texImage3D.apply( gl, arguments ); - - } catch ( error ) { - - console.error( 'THREE.WebGLState:', error ); - - } - - } - - // - - function scissor( scissor ) { - - if ( currentScissor.equals( scissor ) === false ) { - - gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); - currentScissor.copy( scissor ); - - } - - } - - function viewport( viewport ) { - - if ( currentViewport.equals( viewport ) === false ) { - - gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); - currentViewport.copy( viewport ); - - } - - } - - // - - function reset() { - - // reset state - - gl.disable( 3042 ); - gl.disable( 2884 ); - gl.disable( 2929 ); - gl.disable( 32823 ); - gl.disable( 3089 ); - gl.disable( 2960 ); - - gl.blendEquation( 32774 ); - gl.blendFunc( 1, 0 ); - gl.blendFuncSeparate( 1, 0, 1, 0 ); - - gl.colorMask( true, true, true, true ); - gl.clearColor( 0, 0, 0, 0 ); - - gl.depthMask( true ); - gl.depthFunc( 513 ); - gl.clearDepth( 1 ); - - gl.stencilMask( 0xffffffff ); - gl.stencilFunc( 519, 0, 0xffffffff ); - gl.stencilOp( 7680, 7680, 7680 ); - gl.clearStencil( 0 ); - - gl.cullFace( 1029 ); - gl.frontFace( 2305 ); - - gl.polygonOffset( 0, 0 ); - - gl.activeTexture( 33984 ); - - gl.useProgram( null ); - - gl.lineWidth( 1 ); - - gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); - gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); - - // reset internals - - enabledCapabilities = {}; - - currentTextureSlot = null; - currentBoundTextures = {}; - - currentProgram = null; - - currentBlendingEnabled = false; - currentBlending = null; - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; - currentPremultipledAlpha = false; - - currentFlipSided = null; - currentCullFace = null; - - currentLineWidth = null; - - currentPolygonOffsetFactor = null; - currentPolygonOffsetUnits = null; - - colorBuffer.reset(); - depthBuffer.reset(); - stencilBuffer.reset(); - - } - - return { - - buffers: { - color: colorBuffer, - depth: depthBuffer, - stencil: stencilBuffer - }, - - enable: enable, - disable: disable, - - useProgram: useProgram, - - setBlending: setBlending, - setMaterial: setMaterial, - - setFlipSided: setFlipSided, - setCullFace: setCullFace, - - setLineWidth: setLineWidth, - setPolygonOffset: setPolygonOffset, - - setScissorTest: setScissorTest, - - activeTexture: activeTexture, - bindTexture: bindTexture, - unbindTexture: unbindTexture, - compressedTexImage2D: compressedTexImage2D, - texImage2D: texImage2D, - texImage3D: texImage3D, - - scissor: scissor, - viewport: viewport, - - reset: reset - - }; - -} - -function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { - - const isWebGL2 = capabilities.isWebGL2; - const maxTextures = capabilities.maxTextures; - const maxCubemapSize = capabilities.maxCubemapSize; - const maxTextureSize = capabilities.maxTextureSize; - const maxSamples = capabilities.maxSamples; - - const _videoTextures = new WeakMap(); - let _canvas; - - // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, - // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! - // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). - - let useOffscreenCanvas = false; - - try { - - useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' - && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; - - } catch ( err ) { - - // Ignore any errors - - } - - function createCanvas( width, height ) { - - // Use OffscreenCanvas when available. Specially needed in web workers - - return useOffscreenCanvas ? - new OffscreenCanvas( width, height ) : - document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - - } - - function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { - - let scale = 1; - - // handle case if texture exceeds max size - - if ( image.width > maxSize || image.height > maxSize ) { - - scale = maxSize / Math.max( image.width, image.height ); - - } - - // only perform resize if necessary - - if ( scale < 1 || needsPowerOfTwo === true ) { - - // only perform resize for certain image types - - if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || - ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - - const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor; - - const width = floor( scale * image.width ); - const height = floor( scale * image.height ); - - if ( _canvas === undefined ) _canvas = createCanvas( width, height ); - - // cube textures can't reuse the same canvas - - const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; - - canvas.width = width; - canvas.height = height; - - const context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, width, height ); - - console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); - - return canvas; - - } else { - - if ( 'data' in image ) { - - console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); - - } - - return image; - - } - - } - - return image; - - } - - function isPowerOfTwo( image ) { - - return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height ); - - } - - function textureNeedsPowerOfTwo( texture ) { - - if ( isWebGL2 ) return false; - - return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || - ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); - - } - - function textureNeedsGenerateMipmaps( texture, supportsMips ) { - - return texture.generateMipmaps && supportsMips && - texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - - } - - function generateMipmap( target, texture, width, height ) { - - _gl.generateMipmap( target ); - - const textureProperties = properties.get( texture ); - - textureProperties.__maxMipLevel = Math.log2( Math.max( width, height ) ); - - } - - function getInternalFormat( internalFormatName, glFormat, glType ) { - - if ( isWebGL2 === false ) return glFormat; - - if ( internalFormatName !== null ) { - - if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; - - console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); - - } - - let internalFormat = glFormat; - - if ( glFormat === 6403 ) { - - if ( glType === 5126 ) internalFormat = 33326; - if ( glType === 5131 ) internalFormat = 33325; - if ( glType === 5121 ) internalFormat = 33321; - - } - - if ( glFormat === 6407 ) { - - if ( glType === 5126 ) internalFormat = 34837; - if ( glType === 5131 ) internalFormat = 34843; - if ( glType === 5121 ) internalFormat = 32849; - - } - - if ( glFormat === 6408 ) { - - if ( glType === 5126 ) internalFormat = 34836; - if ( glType === 5131 ) internalFormat = 34842; - if ( glType === 5121 ) internalFormat = 32856; + } else { - } + gl.frontFace( 2305 ); - if ( internalFormat === 33325 || internalFormat === 33326 || - internalFormat === 34842 || internalFormat === 34836 ) { + } - extensions.get( 'EXT_color_buffer_float' ); + currentFlipSided = flipSided; } - return internalFormat; - } - // Fallback filters for non-power-of-2 textures + function setCullFace( cullFace ) { - function filterFallback( f ) { + if ( cullFace !== CullFaceNone ) { - if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { + enable( 2884 ); - return 9728; + if ( cullFace !== currentCullFace ) { - } + if ( cullFace === CullFaceBack ) { - return 9729; + gl.cullFace( 1029 ); - } + } else if ( cullFace === CullFaceFront ) { - // + gl.cullFace( 1028 ); - function onTextureDispose( event ) { + } else { - const texture = event.target; + gl.cullFace( 1032 ); - texture.removeEventListener( 'dispose', onTextureDispose ); + } - deallocateTexture( texture ); + } - if ( texture.isVideoTexture ) { + } else { - _videoTextures.delete( texture ); + disable( 2884 ); } - info.memory.textures --; + currentCullFace = cullFace; } - function onRenderTargetDispose( event ) { + function setLineWidth( width ) { - const renderTarget = event.target; + if ( width !== currentLineWidth ) { - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + if ( lineWidthAvailable ) gl.lineWidth( width ); - deallocateRenderTarget( renderTarget ); + currentLineWidth = width; - info.memory.textures --; + } } - // + function setPolygonOffset( polygonOffset, factor, units ) { - function deallocateTexture( texture ) { + if ( polygonOffset ) { - const textureProperties = properties.get( texture ); + enable( 32823 ); - if ( textureProperties.__webglInit === undefined ) return; + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - _gl.deleteTexture( textureProperties.__webglTexture ); + gl.polygonOffset( factor, units ); - properties.remove( texture ); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - } + } - function deallocateRenderTarget( renderTarget ) { + } else { - const texture = renderTarget.texture; + disable( 32823 ); - const renderTargetProperties = properties.get( renderTarget ); - const textureProperties = properties.get( texture ); + } - if ( ! renderTarget ) return; + } - if ( textureProperties.__webglTexture !== undefined ) { + function setScissorTest( scissorTest ) { - _gl.deleteTexture( textureProperties.__webglTexture ); + if ( scissorTest ) { - } + enable( 3089 ); - if ( renderTarget.depthTexture ) { + } else { - renderTarget.depthTexture.dispose(); + disable( 3089 ); } - if ( renderTarget.isWebGLCubeRenderTarget ) { + } - for ( let i = 0; i < 6; i ++ ) { + // texture - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + function activeTexture( webglSlot ) { - } + if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1; - } else { + if ( currentTextureSlot !== webglSlot ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); - if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); - if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); - if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; } - properties.remove( texture ); - properties.remove( renderTarget ); - } - // + function bindTexture( webglType, webglTexture ) { - let textureUnits = 0; + if ( currentTextureSlot === null ) { - function resetTextureUnits() { + activeTexture(); - textureUnits = 0; + } - } + let boundTexture = currentBoundTextures[ currentTextureSlot ]; - function allocateTextureUnit() { + if ( boundTexture === undefined ) { - const textureUnit = textureUnits; + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; - if ( textureUnit >= maxTextures ) { + } - console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - } + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - textureUnits += 1; + boundTexture.type = webglType; + boundTexture.texture = webglTexture; - return textureUnit; + } } - // - - function setTexture2D( texture, slot ) { + function unbindTexture() { - const textureProperties = properties.get( texture ); + const boundTexture = currentBoundTextures[ currentTextureSlot ]; - if ( texture.isVideoTexture ) updateVideoTexture( texture ); + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.bindTexture( boundTexture.type, null ); - const image = texture.image; + boundTexture.type = undefined; + boundTexture.texture = undefined; - if ( image === undefined ) { + } - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' ); + } - } else if ( image.complete === false ) { + function compressedTexImage2D() { - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + try { - } else { + gl.compressedTexImage2D.apply( gl, arguments ); - uploadTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); } - state.activeTexture( 33984 + slot ); - state.bindTexture( 3553, textureProperties.__webglTexture ); - } - function setTexture2DArray( texture, slot ) { + function texSubImage2D() { - const textureProperties = properties.get( texture ); + try { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.texSubImage2D.apply( gl, arguments ); - uploadTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - state.activeTexture( 33984 + slot ); - state.bindTexture( 35866, textureProperties.__webglTexture ); + } } - function setTexture3D( texture, slot ) { + function texSubImage3D() { - const textureProperties = properties.get( texture ); + try { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.texSubImage3D.apply( gl, arguments ); - uploadTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - state.activeTexture( 33984 + slot ); - state.bindTexture( 32879, textureProperties.__webglTexture ); + } } - function setTextureCube( texture, slot ) { + function compressedTexSubImage2D() { - const textureProperties = properties.get( texture ); + try { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.compressedTexSubImage2D.apply( gl, arguments ); - uploadCubeTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - state.activeTexture( 33984 + slot ); - state.bindTexture( 34067, textureProperties.__webglTexture ); + } } - const wrappingToGL = { - [ RepeatWrapping ]: 10497, - [ ClampToEdgeWrapping ]: 33071, - [ MirroredRepeatWrapping ]: 33648 - }; - - const filterToGL = { - [ NearestFilter ]: 9728, - [ NearestMipmapNearestFilter ]: 9984, - [ NearestMipmapLinearFilter ]: 9986, - - [ LinearFilter ]: 9729, - [ LinearMipmapNearestFilter ]: 9985, - [ LinearMipmapLinearFilter ]: 9987 - }; - - function setTextureParameters( textureType, texture, supportsMips ) { + function texStorage2D() { - if ( supportsMips ) { + try { - _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); - _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); + gl.texStorage2D.apply( gl, arguments ); - if ( textureType === 32879 || textureType === 35866 ) { + } catch ( error ) { - _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); + console.error( 'THREE.WebGLState:', error ); - } + } - _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); - _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); + } - } else { + function texStorage3D() { - _gl.texParameteri( textureType, 10242, 33071 ); - _gl.texParameteri( textureType, 10243, 33071 ); + try { - if ( textureType === 32879 || textureType === 35866 ) { + gl.texStorage3D.apply( gl, arguments ); - _gl.texParameteri( textureType, 32882, 33071 ); + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - 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.' ); + } - } + function texImage2D() { - _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); + try { - if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { + gl.texImage2D.apply( gl, arguments ); - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' ); + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); } - if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + } - const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + function texImage3D() { - if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 - if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only + try { - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + gl.texImage3D.apply( gl, arguments ); - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); } } - function initTexture( textureProperties, texture ) { - - if ( textureProperties.__webglInit === undefined ) { - - textureProperties.__webglInit = true; + // - texture.addEventListener( 'dispose', onTextureDispose ); + function scissor( scissor ) { - textureProperties.__webglTexture = _gl.createTexture(); + if ( currentScissor.equals( scissor ) === false ) { - info.memory.textures ++; + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); } } - function uploadTexture( textureProperties, texture, slot ) { - - let textureType = 3553; + function viewport( viewport ) { - if ( texture.isDataTexture2DArray ) textureType = 35866; - if ( texture.isDataTexture3D ) textureType = 32879; + if ( currentViewport.equals( viewport ) === false ) { - initTexture( textureProperties, texture ); + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); - state.activeTexture( 33984 + slot ); - state.bindTexture( textureType, textureProperties.__webglTexture ); + } - _gl.pixelStorei( 37440, texture.flipY ); - _gl.pixelStorei( 37441, texture.premultiplyAlpha ); - _gl.pixelStorei( 3317, texture.unpackAlignment ); - _gl.pixelStorei( 37443, 0 ); + } - const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false; - const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + function updateUBOMapping( uniformsGroup, program ) { - const supportsMips = isPowerOfTwo( image ) || isWebGL2, - glFormat = utils.convert( texture.format ); + let mapping = uboProgamMap.get( program ); - let glType = utils.convert( texture.type ), - glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + if ( mapping === undefined ) { - setTextureParameters( textureType, texture, supportsMips ); + mapping = new WeakMap(); - let mipmap; - const mipmaps = texture.mipmaps; + uboProgamMap.set( program, mapping ); - if ( texture.isDepthTexture ) { + } - // populate depth texture with dummy data + let blockIndex = mapping.get( uniformsGroup ); - glInternalFormat = 6402; + if ( blockIndex === undefined ) { - if ( isWebGL2 ) { + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); - if ( texture.type === FloatType ) { + mapping.set( uniformsGroup, blockIndex ); - glInternalFormat = 36012; + } - } else if ( texture.type === UnsignedIntType ) { + } - glInternalFormat = 33190; + function uniformBlockBinding( uniformsGroup, program ) { - } else if ( texture.type === UnsignedInt248Type ) { + const mapping = uboProgamMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); - glInternalFormat = 35056; + if ( uboBindings.get( uniformsGroup ) !== blockIndex ) { - } else { + // bind shader specific block index to global block point - glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); - } + uboBindings.set( uniformsGroup, blockIndex ); - } else { + } - if ( texture.type === FloatType ) { + } - console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); + // - } + function reset() { - } + // reset state - // validation checks for WebGL 1 + gl.disable( 3042 ); + gl.disable( 2884 ); + gl.disable( 2929 ); + gl.disable( 32823 ); + gl.disable( 3089 ); + gl.disable( 2960 ); + gl.disable( 32926 ); - if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { + gl.blendEquation( 32774 ); + gl.blendFunc( 1, 0 ); + gl.blendFuncSeparate( 1, 0, 1, 0 ); - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); - console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + gl.depthMask( true ); + gl.depthFunc( 513 ); + gl.clearDepth( 1 ); - texture.type = UnsignedShortType; - glType = utils.convert( texture.type ); + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( 519, 0, 0xffffffff ); + gl.stencilOp( 7680, 7680, 7680 ); + gl.clearStencil( 0 ); - } + gl.cullFace( 1029 ); + gl.frontFace( 2305 ); - } + gl.polygonOffset( 0, 0 ); - if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) { + gl.activeTexture( 33984 ); - // Depth stencil textures need the DEPTH_STENCIL internal format - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - glInternalFormat = 34041; + gl.bindFramebuffer( 36160, null ); - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedInt248Type ) { + if ( isWebGL2 === true ) { - console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + gl.bindFramebuffer( 36009, null ); + gl.bindFramebuffer( 36008, null ); - texture.type = UnsignedInt248Type; - glType = utils.convert( texture.type ); + } - } + gl.useProgram( null ); - } + gl.lineWidth( 1 ); - // + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + // reset internals - } else if ( texture.isDataTexture ) { + enabledCapabilities = {}; - // 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 + currentTextureSlot = null; + currentBoundTextures = {}; - if ( mipmaps.length > 0 && supportsMips ) { + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; - for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + currentProgram = null; - mipmap = mipmaps[ i ]; - state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentPremultipledAlpha = false; - } + currentFlipSided = null; + currentCullFace = null; - texture.generateMipmaps = false; - textureProperties.__maxMipLevel = mipmaps.length - 1; + currentLineWidth = null; - } else { + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); - } + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); - } else if ( texture.isCompressedTexture ) { + } - for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + return { - mipmap = mipmaps[ i ]; + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + enable: enable, + disable: disable, - if ( glFormat !== null ) { + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, - state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + useProgram: useProgram, - } else { + setBlending: setBlending, + setMaterial: setMaterial, - console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + setFlipSided: setFlipSided, + setCullFace: setCullFace, - } + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, - } else { + setScissorTest: setScissorTest, - state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + texImage2D: texImage2D, + texImage3D: texImage3D, - } + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, - } + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, - textureProperties.__maxMipLevel = mipmaps.length - 1; + scissor: scissor, + viewport: viewport, - } else if ( texture.isDataTexture2DArray ) { + reset: reset - state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; + }; - } else if ( texture.isDataTexture3D ) { +} - state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { - } else { + const isWebGL2 = capabilities.isWebGL2; + const maxTextures = capabilities.maxTextures; + const maxCubemapSize = capabilities.maxCubemapSize; + const maxTextureSize = capabilities.maxTextureSize; + const maxSamples = capabilities.maxSamples; + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = /OculusBrowser/g.test( navigator.userAgent ); - // regular Texture (image, video, canvas) + const _videoTextures = new WeakMap(); + let _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 + const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source - if ( mipmaps.length > 0 && supportsMips ) { + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). - for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + let useOffscreenCanvas = false; - mipmap = mipmaps[ i ]; - state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); + try { - } + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + // eslint-disable-next-line compat/compat + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; - texture.generateMipmaps = false; - textureProperties.__maxMipLevel = mipmaps.length - 1; + } catch ( err ) { - } else { + // Ignore any errors - state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); - textureProperties.__maxMipLevel = 0; + } - } + function createCanvas( width, height ) { - } + // Use OffscreenCanvas when available. Specially needed in web workers - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + return useOffscreenCanvas ? + // eslint-disable-next-line compat/compat + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); - generateMipmap( textureType, texture, image.width, image.height ); + } - } + function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { - textureProperties.__version = texture.version; + let scale = 1; - if ( texture.onUpdate ) texture.onUpdate( texture ); + // handle case if texture exceeds max size - } + if ( image.width > maxSize || image.height > maxSize ) { - function uploadCubeTexture( textureProperties, texture, slot ) { + scale = maxSize / Math.max( image.width, image.height ); - if ( texture.image.length !== 6 ) return; + } - initTexture( textureProperties, texture ); + // only perform resize if necessary - state.activeTexture( 33984 + slot ); - state.bindTexture( 34067, textureProperties.__webglTexture ); + if ( scale < 1 || needsPowerOfTwo === true ) { - _gl.pixelStorei( 37440, texture.flipY ); - _gl.pixelStorei( 37441, texture.premultiplyAlpha ); - _gl.pixelStorei( 3317, texture.unpackAlignment ); - _gl.pixelStorei( 37443, 0 ); + // only perform resize for certain image types - const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) ); - const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - const cubeImage = []; + const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; - for ( let i = 0; i < 6; i ++ ) { + const width = floor( scale * image.width ); + const height = floor( scale * image.height ); - if ( ! isCompressed && ! isDataTexture ) { + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); - cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); + // cube textures can't reuse the same canvas - } else { + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + canvas.width = width; + canvas.height = height; - } + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); - } + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); - const image = cubeImage[ 0 ], - supportsMips = isPowerOfTwo( image ) || isWebGL2, - glFormat = utils.convert( texture.format ), - glType = utils.convert( texture.type ), - glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + return canvas; - setTextureParameters( 34067, texture, supportsMips ); + } else { - let mipmaps; + if ( 'data' in image ) { - if ( isCompressed ) { + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); - for ( let i = 0; i < 6; i ++ ) { + } - mipmaps = cubeImage[ i ].mipmaps; + return image; - for ( let j = 0; j < mipmaps.length; j ++ ) { + } - const mipmap = mipmaps[ j ]; + } - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + return image; - if ( glFormat !== null ) { + } - state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + function isPowerOfTwo$1( image ) { - } else { + return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); - console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + } - } + function textureNeedsPowerOfTwo( texture ) { - } else { + if ( isWebGL2 ) return false; - state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); - } + } - } + function textureNeedsGenerateMipmaps( texture, supportsMips ) { - } + return texture.generateMipmaps && supportsMips && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - textureProperties.__maxMipLevel = mipmaps.length - 1; + } - } else { + function generateMipmap( target ) { - mipmaps = texture.mipmaps; + _gl.generateMipmap( target ); - for ( let i = 0; i < 6; i ++ ) { + } - if ( isDataTexture ) { + function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) { - state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + if ( isWebGL2 === false ) return glFormat; - for ( let j = 0; j < mipmaps.length; j ++ ) { + if ( internalFormatName !== null ) { - const mipmap = mipmaps[ j ]; - const mipmapImage = mipmap.image[ i ].image; + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; - state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); - } + } - } else { + let internalFormat = glFormat; - state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + if ( glFormat === 6403 ) { - for ( let j = 0; j < mipmaps.length; j ++ ) { + if ( glType === 5126 ) internalFormat = 33326; + if ( glType === 5131 ) internalFormat = 33325; + if ( glType === 5121 ) internalFormat = 33321; - const mipmap = mipmaps[ j ]; + } - state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + if ( glFormat === 33319 ) { - } + if ( glType === 5126 ) internalFormat = 33328; + if ( glType === 5131 ) internalFormat = 33327; + if ( glType === 5121 ) internalFormat = 33323; - } + } - } + if ( glFormat === 6408 ) { - textureProperties.__maxMipLevel = mipmaps.length; + if ( glType === 5126 ) internalFormat = 34836; + if ( glType === 5131 ) internalFormat = 34842; + if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? 35907 : 32856; + if ( glType === 32819 ) internalFormat = 32854; + if ( glType === 32820 ) internalFormat = 32855; } - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + if ( internalFormat === 33325 || internalFormat === 33326 || + internalFormat === 33327 || internalFormat === 33328 || + internalFormat === 34842 || internalFormat === 34836 ) { - // We assume images for cube map have the same size. - generateMipmap( 34067, texture, image.width, image.height ); + extensions.get( 'EXT_color_buffer_float' ); } - textureProperties.__version = texture.version; - - if ( texture.onUpdate ) texture.onUpdate( texture ); + return internalFormat; } - // Render targets + function getMipLevels( texture, image, supportsMips ) { - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { - const texture = renderTarget.texture; + return Math.log2( Math.max( image.width, image.height ) ) + 1; - const glFormat = utils.convert( texture.format ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps - if ( textureTarget === 32879 || textureTarget === 35866 ) { + return texture.mipmaps.length; - state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null ); + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; } else { - state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + // texture without mipmaps (only base level) - } + return 1; - _gl.bindFramebuffer( 36160, framebuffer ); - _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 ); - _gl.bindFramebuffer( 36160, null ); + } } - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + // Fallback filters for non-power-of-2 textures - _gl.bindRenderbuffer( 36161, renderbuffer ); + function filterFallback( f ) { - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { - let glInternalFormat = 33189; + return 9728; - if ( isMultisample ) { + } - const depthTexture = renderTarget.depthTexture; + return 9729; - if ( depthTexture && depthTexture.isDepthTexture ) { + } - if ( depthTexture.type === FloatType ) { + // - glInternalFormat = 36012; + function onTextureDispose( event ) { - } else if ( depthTexture.type === UnsignedIntType ) { + const texture = event.target; - glInternalFormat = 33190; + texture.removeEventListener( 'dispose', onTextureDispose ); - } + deallocateTexture( texture ); - } + if ( texture.isVideoTexture ) { - const samples = getRenderTargetSamples( renderTarget ); + _videoTextures.delete( texture ); - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + } - } else { + } - _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + function onRenderTargetDispose( event ) { - } + const renderTarget = event.target; - _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + deallocateRenderTarget( renderTarget ); - if ( isMultisample ) { + } - const samples = getRenderTargetSamples( renderTarget ); + // - _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); + function deallocateTexture( texture ) { - } else { + const textureProperties = properties.get( texture ); - _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); + if ( textureProperties.__webglInit === undefined ) return; - } + // check if it's necessary to remove the WebGLTexture object + const source = texture.source; + const webglTextures = _sources.get( source ); - _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); + if ( webglTextures ) { - } else { + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; - const texture = renderTarget.texture; + // the WebGLTexture object is not used anymore, remove it - const glFormat = utils.convert( texture.format ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + if ( webglTexture.usedTimes === 0 ) { - if ( isMultisample ) { + deleteTexture( texture ); - const samples = getRenderTargetSamples( renderTarget ); + } - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + // remove the weak map entry if no WebGLTexture uses the source anymore - } else { + if ( Object.keys( webglTextures ).length === 0 ) { - _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + _sources.delete( source ); } } - _gl.bindRenderbuffer( 36161, null ); + properties.remove( texture ); } - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture( framebuffer, renderTarget ) { + function deleteTexture( texture ) { - const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); - if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); - _gl.bindFramebuffer( 36160, framebuffer ); + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; - if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + info.memory.textures --; - throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + } - } + function deallocateRenderTarget( renderTarget ) { - // 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 ) { + const texture = renderTarget.texture; - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglTexture !== undefined ) { + + _gl.deleteTexture( textureProperties.__webglTexture ); + + info.memory.textures --; } - setTexture2D( renderTarget.depthTexture, 0 ); + if ( renderTarget.depthTexture ) { - const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + renderTarget.depthTexture.dispose(); - if ( renderTarget.depthTexture.format === DepthFormat ) { + } - _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); + if ( renderTarget.isWebGLCubeRenderTarget ) { - } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + for ( let i = 0; i < 6; i ++ ) { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); + } } else { - throw new Error( 'Unknown depthTexture format' ); + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); - } + if ( renderTargetProperties.__webglColorRenderbuffer ) { - } + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); - const renderTargetProperties = properties.get( renderTarget ); + } - const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + } - if ( renderTarget.depthTexture ) { + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); - if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); + } - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + if ( renderTarget.isWebGLMultipleRenderTargets ) { - } else { + for ( let i = 0, il = texture.length; i < il; i ++ ) { - if ( isCube ) { + const attachmentProperties = properties.get( texture[ i ] ); - renderTargetProperties.__webglDepthbuffer = []; + if ( attachmentProperties.__webglTexture ) { - for ( let i = 0; i < 6; i ++ ) { + _gl.deleteTexture( attachmentProperties.__webglTexture ); - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + info.memory.textures --; } - } else { - - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + properties.remove( texture[ i ] ); } } - _gl.bindFramebuffer( 36160, null ); + properties.remove( texture ); + properties.remove( renderTarget ); } - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + // - const texture = renderTarget.texture; + let textureUnits = 0; - const renderTargetProperties = properties.get( renderTarget ); - const textureProperties = properties.get( texture ); + function resetTextureUnits() { - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + textureUnits = 0; - textureProperties.__webglTexture = _gl.createTexture(); + } - info.memory.textures ++; + function allocateTextureUnit() { - const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true ); - const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray; - const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; + const textureUnit = textureUnits; - // Handles WebGL2 RGBFormat fallback - #18858 + if ( textureUnit >= maxTextures ) { - if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) { + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); - texture.format = RGBAFormat; + } - console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' ); + textureUnits += 1; - } + return textureUnit; - // Setup framebuffer + } - if ( isCube ) { + function getTextureCacheKey( texture ) { - renderTargetProperties.__webglFramebuffer = []; + const array = []; - for ( let i = 0; i < 6; i ++ ) { + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.encoding ); - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + return array.join(); - } + } - } else { + // - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + function setTexture2D( texture, slot ) { - if ( isMultisample ) { + const textureProperties = properties.get( texture ); - if ( isWebGL2 ) { + if ( texture.isVideoTexture ) updateVideoTexture( texture ); - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); - renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { - _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer ); + const image = texture.image; - const glFormat = utils.convert( texture.format ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); - const samples = getRenderTargetSamples( renderTarget ); - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + if ( image === null ) { - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer ); - _gl.bindRenderbuffer( 36161, null ); + console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' ); - if ( renderTarget.depthBuffer ) { + } else if ( image.complete === false ) { - renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); - } + } else { - _gl.bindFramebuffer( 36160, null ); + uploadTexture( textureProperties, texture, slot ); + return; + } - } else { + } - console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); + state.activeTexture( 33984 + slot ); + state.bindTexture( 3553, textureProperties.__webglTexture ); - } + } - } + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; } - // Setup color buffer + state.activeTexture( 33984 + slot ); + state.bindTexture( 35866, textureProperties.__webglTexture ); - if ( isCube ) { + } - state.bindTexture( 34067, textureProperties.__webglTexture ); - setTextureParameters( 34067, texture, supportsMips ); + function setTexture3D( texture, slot ) { - for ( let i = 0; i < 6; i ++ ) { + const textureProperties = properties.get( texture ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i ); + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - } + uploadTexture( textureProperties, texture, slot ); + return; - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + } - generateMipmap( 34067, texture, renderTarget.width, renderTarget.height ); + state.activeTexture( 33984 + slot ); + state.bindTexture( 32879, textureProperties.__webglTexture ); - } + } - state.bindTexture( 34067, null ); + function setTextureCube( texture, slot ) { - } else { + const textureProperties = properties.get( texture ); - let glTextureType = 3553; + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - if ( isRenderTarget3D ) { + uploadCubeTexture( textureProperties, texture, slot ); + return; - // Render targets containing layers, i.e: Texture 3D and 2d arrays + } - if ( isWebGL2 ) { + state.activeTexture( 33984 + slot ); + state.bindTexture( 34067, textureProperties.__webglTexture ); - const isTexture3D = texture.isDataTexture3D; - glTextureType = isTexture3D ? 32879 : 35866; + } - } else { + const wrappingToGL = { + [ RepeatWrapping ]: 10497, + [ ClampToEdgeWrapping ]: 33071, + [ MirroredRepeatWrapping ]: 33648 + }; + + const filterToGL = { + [ NearestFilter ]: 9728, + [ NearestMipmapNearestFilter ]: 9984, + [ NearestMipmapLinearFilter ]: 9986, + + [ LinearFilter ]: 9729, + [ LinearMipmapNearestFilter ]: 9985, + [ LinearMipmapLinearFilter ]: 9987 + }; - console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' ); + function setTextureParameters( textureType, texture, supportsMips ) { - } + if ( supportsMips ) { + + _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === 32879 || textureType === 35866 ) { + + _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); } - state.bindTexture( glTextureType, textureProperties.__webglTexture ); - setTextureParameters( glTextureType, texture, supportsMips ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, glTextureType ); + _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + } else { + + _gl.texParameteri( textureType, 10242, 33071 ); + _gl.texParameteri( textureType, 10243, 33071 ); - generateMipmap( 3553, texture, renderTarget.width, renderTarget.height ); + if ( textureType === 32879 || textureType === 35866 ) { + + _gl.texParameteri( textureType, 32882, 33071 ); } - state.bindTexture( 3553, null ); + 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.' ); - // Setup depth and stencil buffers + } - if ( renderTarget.depthBuffer ) { + _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); - setupDepthRenderbuffer( renderTarget ); + 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.' ); - } + } - function updateRenderTargetMipmap( renderTarget ) { + } - const texture = renderTarget.texture; + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 + if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; - const webglTexture = properties.get( texture ).__webglTexture; + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - state.bindTexture( target, webglTexture ); - generateMipmap( target, texture, renderTarget.width, renderTarget.height ); - state.bindTexture( target, null ); + } } } - function updateMultisampleRenderTarget( renderTarget ) { + function initTexture( textureProperties, texture ) { - if ( renderTarget.isWebGLMultisampleRenderTarget ) { + let forceUpload = false; - if ( isWebGL2 ) { + if ( textureProperties.__webglInit === undefined ) { - const renderTargetProperties = properties.get( renderTarget ); + textureProperties.__webglInit = true; - _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); + texture.addEventListener( 'dispose', onTextureDispose ); - const width = renderTarget.width; - const height = renderTarget.height; - let mask = 16384; + } - if ( renderTarget.depthBuffer ) mask |= 256; - if ( renderTarget.stencilBuffer ) mask |= 1024; + // create Source <-> WebGLTextures mapping if necessary - _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + const source = texture.source; + let webglTextures = _sources.get( source ); - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905 + if ( webglTextures === undefined ) { - } else { + webglTextures = {}; + _sources.set( source, webglTextures ); - console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); + } - } + // check if there is already a WebGLTexture object for the given texture parameters - } + const textureCacheKey = getTextureCacheKey( texture ); - } + if ( textureCacheKey !== textureProperties.__cacheKey ) { - function getRenderTargetSamples( renderTarget ) { + // if not, create a new instance of WebGLTexture - return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ? - Math.min( maxSamples, renderTarget.samples ) : 0; + if ( webglTextures[ textureCacheKey ] === undefined ) { - } + // create new entry - function updateVideoTexture( texture ) { + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; - const frame = info.render.frame; + info.memory.textures ++; - // Check the last frame we updated the VideoTexture + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical - if ( _videoTextures.get( texture ) !== frame ) { + forceUpload = true; - _videoTextures.set( texture, frame ); - texture.update(); + } - } + webglTextures[ textureCacheKey ].usedTimes ++; - } + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. - // backwards compatibility + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; - let warnedTexture2D = false; - let warnedTextureCube = false; + if ( webglTexture !== undefined ) { - function safeSetTexture2D( texture, slot ) { + webglTextures[ textureProperties.__cacheKey ].usedTimes --; - if ( texture && texture.isWebGLRenderTarget ) { + if ( webglTexture.usedTimes === 0 ) { - if ( warnedTexture2D === false ) { + deleteTexture( texture ); - console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' ); - warnedTexture2D = true; + } } - texture = texture.texture; + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; } - setTexture2D( texture, slot ); + return forceUpload; } - function safeSetTextureCube( texture, slot ) { + function uploadTexture( textureProperties, texture, slot ) { - if ( texture && texture.isWebGLCubeRenderTarget ) { + let textureType = 3553; - if ( warnedTextureCube === false ) { + if ( texture.isDataArrayTexture ) textureType = 35866; + if ( texture.isData3DTexture ) textureType = 32879; - console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' ); - warnedTextureCube = true; + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; - } + state.activeTexture( 33984 + slot ); + state.bindTexture( textureType, textureProperties.__webglTexture ); - texture = texture.texture; + if ( source.version !== source.__currentVersion || forceUpload === true ) { - } + _gl.pixelStorei( 37440, texture.flipY ); + _gl.pixelStorei( 37441, texture.premultiplyAlpha ); + _gl.pixelStorei( 3317, texture.unpackAlignment ); + _gl.pixelStorei( 37443, 0 ); + const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false; + let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + image = verifyColorSpace( texture, image ); - setTextureCube( texture, slot ); + const supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ); - } + let glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture ); - // + setTextureParameters( textureType, texture, supportsMips ); - this.allocateTextureUnit = allocateTextureUnit; - this.resetTextureUnits = resetTextureUnits; + let mipmap; + const mipmaps = texture.mipmaps; - this.setTexture2D = setTexture2D; - this.setTexture2DArray = setTexture2DArray; - this.setTexture3D = setTexture3D; - this.setTextureCube = setTextureCube; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; - this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); + const levels = getMipLevels( texture, image, supportsMips ); - this.safeSetTexture2D = safeSetTexture2D; - this.safeSetTextureCube = safeSetTextureCube; + if ( texture.isDepthTexture ) { -} + // populate depth texture with dummy data -function WebGLUtils( gl, extensions, capabilities ) { + glInternalFormat = 6402; - const isWebGL2 = capabilities.isWebGL2; + if ( isWebGL2 ) { - function convert( p ) { + if ( texture.type === FloatType ) { - let extension; + glInternalFormat = 36012; - if ( p === UnsignedByteType ) return 5121; - if ( p === UnsignedShort4444Type ) return 32819; - if ( p === UnsignedShort5551Type ) return 32820; - if ( p === UnsignedShort565Type ) return 33635; + } else if ( texture.type === UnsignedIntType ) { - if ( p === ByteType ) return 5120; - if ( p === ShortType ) return 5122; - if ( p === UnsignedShortType ) return 5123; - if ( p === IntType ) return 5124; - if ( p === UnsignedIntType ) return 5125; - if ( p === FloatType ) return 5126; + glInternalFormat = 33190; - if ( p === HalfFloatType ) { + } else if ( texture.type === UnsignedInt248Type ) { - if ( isWebGL2 ) return 5131; + glInternalFormat = 35056; - extension = extensions.get( 'OES_texture_half_float' ); + } else { - if ( extension !== null ) { + glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D - return extension.HALF_FLOAT_OES; + } - } else { + } else { - return null; + if ( texture.type === FloatType ) { - } + console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); - } + } - if ( p === AlphaFormat ) return 6406; - if ( p === RGBFormat ) return 6407; - if ( p === RGBAFormat ) return 6408; - if ( p === LuminanceFormat ) return 6409; - if ( p === LuminanceAlphaFormat ) return 6410; - if ( p === DepthFormat ) return 6402; - if ( p === DepthStencilFormat ) return 34041; - if ( p === RedFormat ) return 6403; + } - // WebGL2 formats. + // validation checks for WebGL 1 - if ( p === RedIntegerFormat ) return 36244; - if ( p === RGFormat ) return 33319; - if ( p === RGIntegerFormat ) return 33320; - if ( p === RGBIntegerFormat ) return 36248; - if ( p === RGBAIntegerFormat ) return 36249; + if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { - if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || - p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); - if ( extension !== null ) { + texture.type = UnsignedIntType; + glType = utils.convert( texture.type ); - 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; + } - } else { + } - return null; + if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) { - } + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + glInternalFormat = 34041; - } + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { - if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || - p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); - if ( extension !== null ) { + } - 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; + } - } else { + // - return null; + if ( allocateMemory ) { - } + if ( useTexStorage ) { - } + state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height ); - if ( p === RGB_ETC1_Format ) { + } else { - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); - if ( extension !== null ) { + } - return extension.COMPRESSED_RGB_ETC1_WEBGL; + } - } else { + } else if ( texture.isDataTexture ) { - return null; + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - } + if ( mipmaps.length > 0 && supportsMips ) { - } + if ( useTexStorage && allocateMemory ) { - if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); - extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + } - if ( extension !== null ) { + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { - if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2; - if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC; + mipmap = mipmaps[ i ]; - } + if ( useTexStorage ) { - } + state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); - if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || - p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || - p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || - p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || - p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || - p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || - p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || - p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || - p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || - p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) { + } else { - extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - if ( extension !== null ) { + } - // TODO Complete? + } - return p; + texture.generateMipmaps = false; - } else { + } else { - return null; + if ( useTexStorage ) { - } + if ( allocateMemory ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - if ( p === RGBA_BPTC_Format ) { + } - extension = extensions.get( 'EXT_texture_compression_bptc' ); + state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); - if ( extension !== null ) { + } else { - // TODO Complete? + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); - return p; + } - } else { + } - return null; + } else if ( texture.isCompressedTexture ) { - } + if ( useTexStorage && allocateMemory ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); - if ( p === UnsignedInt248Type ) { + } - if ( isWebGL2 ) return 34042; + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { - extension = extensions.get( 'WEBGL_depth_texture' ); + mipmap = mipmaps[ i ]; - if ( extension !== null ) { + if ( texture.format !== RGBAFormat ) { - return extension.UNSIGNED_INT_24_8_WEBGL; + if ( glFormat !== null ) { - } else { + if ( useTexStorage ) { - return null; + state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); - } + } else { - } + state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } + } - return { convert: convert }; + } else { -} + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); -function ArrayCamera( array = [] ) { + } - PerspectiveCamera.call( this ); + } else { - this.cameras = array; + if ( useTexStorage ) { -} + state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); -ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), { + } else { - constructor: ArrayCamera, + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - isArrayCamera: true + } -} ); + } -class Group extends Object3D { + } - constructor() { + } else if ( texture.isDataArrayTexture ) { - super(); + if ( useTexStorage ) { - this.type = 'Group'; + if ( allocateMemory ) { - } + state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth ); -} + } -Group.prototype.isGroup = true; + state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); -function WebXRController() { + } else { - this._targetRay = null; - this._grip = null; - this._hand = null; + state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); -} + } -Object.assign( WebXRController.prototype, { + } else if ( texture.isData3DTexture ) { - constructor: WebXRController, + if ( useTexStorage ) { - getHandSpace: function () { + if ( allocateMemory ) { - if ( this._hand === null ) { + state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth ); - this._hand = new Group(); - this._hand.matrixAutoUpdate = false; - this._hand.visible = false; + } - this._hand.joints = {}; - this._hand.inputState = { pinching: false }; + state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); - } + } else { - return this._hand; + state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - }, + } - getTargetRaySpace: function () { + } else if ( texture.isFramebufferTexture ) { - if ( this._targetRay === null ) { + if ( allocateMemory ) { - this._targetRay = new Group(); - this._targetRay.matrixAutoUpdate = false; - this._targetRay.visible = false; + if ( useTexStorage ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - return this._targetRay; + } else { - }, + let width = image.width, height = image.height; - getGripSpace: function () { + for ( let i = 0; i < levels; i ++ ) { - if ( this._grip === null ) { + state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null ); - this._grip = new Group(); - this._grip.matrixAutoUpdate = false; - this._grip.visible = false; + width >>= 1; + height >>= 1; - } + } - return this._grip; + } + + } + + } else { - }, + // regular Texture (image, video, canvas) - dispatchEvent: function ( event ) { + // 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 ( this._targetRay !== null ) { + if ( mipmaps.length > 0 && supportsMips ) { - this._targetRay.dispatchEvent( event ); + if ( useTexStorage && allocateMemory ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); - if ( this._grip !== null ) { + } - this._grip.dispatchEvent( event ); + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { - } + mipmap = mipmaps[ i ]; - if ( this._hand !== null ) { + if ( useTexStorage ) { - this._hand.dispatchEvent( event ); + state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap ); - } + } else { - return this; + state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); - }, + } - disconnect: function ( inputSource ) { + } - this.dispatchEvent( { type: 'disconnected', data: inputSource } ); + texture.generateMipmaps = false; - if ( this._targetRay !== null ) { + } else { - this._targetRay.visible = false; + if ( useTexStorage ) { - } + if ( allocateMemory ) { - if ( this._grip !== null ) { + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - this._grip.visible = false; + } - } + state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image ); - if ( this._hand !== null ) { + } else { - this._hand.visible = false; + state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); - } + } - return this; + } - }, + } - update: function ( inputSource, frame, referenceSpace ) { + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - let inputPose = null; - let gripPose = null; - let handPose = null; + generateMipmap( textureType ); - const targetRay = this._targetRay; - const grip = this._grip; - const hand = this._hand; + } - if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { + source.__currentVersion = source.version; - if ( hand && inputSource.hand ) { + if ( texture.onUpdate ) texture.onUpdate( texture ); - handPose = true; + } - for ( const inputjoint of inputSource.hand.values() ) { + textureProperties.__version = texture.version; - // Update the joints groups with the XRJoint poses - const jointPose = frame.getJointPose( inputjoint, referenceSpace ); + } - if ( hand.joints[ inputjoint.jointName ] === undefined ) { + function uploadCubeTexture( textureProperties, texture, slot ) { - // The transform of this joint will be updated with the joint pose on each frame - const joint = new Group(); - joint.matrixAutoUpdate = false; - joint.visible = false; - hand.joints[ inputjoint.jointName ] = joint; - // ?? - hand.add( joint ); + if ( texture.image.length !== 6 ) return; - } + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; - const joint = hand.joints[ inputjoint.jointName ]; + state.activeTexture( 33984 + slot ); + state.bindTexture( 34067, textureProperties.__webglTexture ); - if ( jointPose !== null ) { + if ( source.version !== source.__currentVersion || forceUpload === true ) { - joint.matrix.fromArray( jointPose.transform.matrix ); - joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); - joint.jointRadius = jointPose.radius; + _gl.pixelStorei( 37440, texture.flipY ); + _gl.pixelStorei( 37441, texture.premultiplyAlpha ); + _gl.pixelStorei( 3317, texture.unpackAlignment ); + _gl.pixelStorei( 37443, 0 ); - } + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); - joint.visible = jointPose !== null; + const cubeImage = []; - } + for ( let i = 0; i < 6; i ++ ) { - // Custom events + if ( ! isCompressed && ! isDataTexture ) { - // Check pinchz - const indexTip = hand.joints[ 'index-finger-tip' ]; - const thumbTip = hand.joints[ 'thumb-tip' ]; - const distance = indexTip.position.distanceTo( thumbTip.position ); + cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); - const distanceToPinch = 0.02; - const threshold = 0.005; + } else { - if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - hand.inputState.pinching = false; - this.dispatchEvent( { - type: 'pinchend', - handedness: inputSource.handedness, - target: this - } ); + } - } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); - hand.inputState.pinching = true; - this.dispatchEvent( { - type: 'pinchstart', - handedness: inputSource.handedness, - target: this - } ); + } - } + const image = cubeImage[ 0 ], + supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); - } else { + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); + let levels = getMipLevels( texture, image, supportsMips ); - if ( targetRay !== null ) { + setTextureParameters( 34067, texture, supportsMips ); - inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + let mipmaps; - if ( inputPose !== null ) { + if ( isCompressed ) { - targetRay.matrix.fromArray( inputPose.transform.matrix ); - targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + if ( useTexStorage && allocateMemory ) { - } + state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height ); } - if ( grip !== null && inputSource.gripSpace ) { + for ( let i = 0; i < 6; i ++ ) { - gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); + mipmaps = cubeImage[ i ].mipmaps; - if ( gripPose !== null ) { + for ( let j = 0; j < mipmaps.length; j ++ ) { - grip.matrix.fromArray( gripPose.transform.matrix ); - grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); + const mipmap = mipmaps[ j ]; - } + if ( texture.format !== RGBAFormat ) { - } + if ( glFormat !== null ) { - } + if ( useTexStorage ) { - } + state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); - if ( targetRay !== null ) { + } else { - targetRay.visible = ( inputPose !== null ); + state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } + } - if ( grip !== null ) { + } else { - grip.visible = ( gripPose !== null ); + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); - } + } - if ( hand !== null ) { + } else { - hand.visible = ( handPose !== null ); + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); - return this; + } else { - } + state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); -} ); + } -function WebXRManager( renderer, gl ) { + } - const scope = this; + } - let session = null; + } - let framebufferScaleFactor = 1.0; + } else { - let referenceSpace = null; - let referenceSpaceType = 'local-floor'; + mipmaps = texture.mipmaps; - let pose = null; + if ( useTexStorage && allocateMemory ) { - const controllers = []; - const inputSourcesMap = new Map(); + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) - // + if ( mipmaps.length > 0 ) levels ++; - const cameraL = new PerspectiveCamera(); - cameraL.layers.enable( 1 ); - cameraL.viewport = new Vector4(); + state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); - const cameraR = new PerspectiveCamera(); - cameraR.layers.enable( 2 ); - cameraR.viewport = new Vector4(); + } - const cameras = [ cameraL, cameraR ]; + for ( let i = 0; i < 6; i ++ ) { - const cameraVR = new ArrayCamera(); - cameraVR.layers.enable( 1 ); - cameraVR.layers.enable( 2 ); + if ( isDataTexture ) { - let _currentDepthNear = null; - let _currentDepthFar = null; + if ( useTexStorage ) { - // + state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); - this.enabled = false; + } else { - this.isPresenting = false; + state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - this.getController = function ( index ) { + } - let controller = controllers[ index ]; + for ( let j = 0; j < mipmaps.length; j ++ ) { - if ( controller === undefined ) { + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; - controller = new WebXRController(); - controllers[ index ] = controller; + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); - return controller.getTargetRaySpace(); + } else { - }; + state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); - this.getControllerGrip = function ( index ) { + } - let controller = controllers[ index ]; + } - if ( controller === undefined ) { + } else { - controller = new WebXRController(); - controllers[ index ] = controller; + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); - return controller.getGripSpace(); + } else { - }; + state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); - this.getHand = function ( index ) { + } - let controller = controllers[ index ]; + for ( let j = 0; j < mipmaps.length; j ++ ) { - if ( controller === undefined ) { + const mipmap = mipmaps[ j ]; - controller = new WebXRController(); - controllers[ index ] = controller; + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); - return controller.getHandSpace(); + } else { - }; + state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); - // + } - function onSessionEvent( event ) { + } - const controller = inputSourcesMap.get( event.inputSource ); + } - if ( controller ) { + } - controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + } - } + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - } + // We assume images for cube map have the same size. + generateMipmap( 34067 ); - function onSessionEnd() { + } - inputSourcesMap.forEach( function ( controller, inputSource ) { + source.__currentVersion = source.version; - controller.disconnect( inputSource ); + if ( texture.onUpdate ) texture.onUpdate( texture ); - } ); + } - inputSourcesMap.clear(); + textureProperties.__version = texture.version; - _currentDepthNear = null; - _currentDepthFar = null; + } - // + // Render targets - renderer.setFramebuffer( null ); - renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830 - animation.stop(); + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) { - scope.isPresenting = false; + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const renderTargetProperties = properties.get( renderTarget ); - scope.dispatchEvent( { type: 'sessionend' } ); + if ( ! renderTargetProperties.__hasExternalTextures ) { - } + if ( textureTarget === 32879 || textureTarget === 35866 ) { - this.setFramebufferScaleFactor = function ( value ) { + state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null ); - framebufferScaleFactor = value; + } else { - if ( scope.isPresenting === true ) { + state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); + } } - }; + state.bindFramebuffer( 36160, framebuffer ); - this.setReferenceSpaceType = function ( value ) { + if ( useMultisampledRTT( renderTarget ) ) { - referenceSpaceType = value; + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); - if ( scope.isPresenting === true ) { + } else { - console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); + _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 ); } - }; - - this.getReferenceSpace = function () { + state.bindFramebuffer( 36160, null ); - return referenceSpace; + } - }; - this.getSession = function () { + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { - return session; + _gl.bindRenderbuffer( 36161, renderbuffer ); - }; + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - this.setSession = async function ( value ) { + let glInternalFormat = 33189; - session = value; + if ( isMultisample || useMultisampledRTT( renderTarget ) ) { - if ( session !== null ) { + const depthTexture = renderTarget.depthTexture; - session.addEventListener( 'select', onSessionEvent ); - session.addEventListener( 'selectstart', onSessionEvent ); - session.addEventListener( 'selectend', onSessionEvent ); - session.addEventListener( 'squeeze', onSessionEvent ); - session.addEventListener( 'squeezestart', onSessionEvent ); - session.addEventListener( 'squeezeend', onSessionEvent ); - session.addEventListener( 'end', onSessionEnd ); - session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + if ( depthTexture && depthTexture.isDepthTexture ) { - const attributes = gl.getContextAttributes(); + if ( depthTexture.type === FloatType ) { - if ( attributes.xrCompatible !== true ) { + glInternalFormat = 36012; - await gl.makeXRCompatible(); + } else if ( depthTexture.type === UnsignedIntType ) { - } + glInternalFormat = 33190; - const layerInit = { - antialias: attributes.antialias, - alpha: attributes.alpha, - depth: attributes.depth, - stencil: attributes.stencil, - framebufferScaleFactor: framebufferScaleFactor - }; + } - // eslint-disable-next-line no-undef - const baseLayer = new XRWebGLLayer( session, gl, layerInit ); + } - session.updateRenderState( { baseLayer: baseLayer } ); + const samples = getRenderTargetSamples( renderTarget ); - referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + if ( useMultisampledRTT( renderTarget ) ) { - animation.setContext( session ); - animation.start(); + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - scope.isPresenting = true; + } else { - scope.dispatchEvent( { type: 'sessionstart' } ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - } + } - }; + } else { - function onInputSourcesChange( event ) { + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); - const inputSources = session.inputSources; + } - // Assign inputSources to available controllers + _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); - for ( let i = 0; i < controllers.length; i ++ ) { + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - inputSourcesMap.set( inputSources[ i ], controllers[ i ] ); + const samples = getRenderTargetSamples( renderTarget ); - } + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { - // Notify disconnected + _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); - for ( let i = 0; i < event.removed.length; i ++ ) { + } else if ( useMultisampledRTT( renderTarget ) ) { - const inputSource = event.removed[ i ]; - const controller = inputSourcesMap.get( inputSource ); + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height ); - if ( controller ) { + } else { - controller.dispatchEvent( { type: 'disconnected', data: inputSource } ); - inputSourcesMap.delete( inputSource ); + _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); } - } - - // Notify connected - for ( let i = 0; i < event.added.length; i ++ ) { + _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); - const inputSource = event.added[ i ]; - const controller = inputSourcesMap.get( inputSource ); + } else { - if ( controller ) { + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; - controller.dispatchEvent( { type: 'connected', data: inputSource } ); + for ( let i = 0; i < textures.length; i ++ ) { - } + const texture = textures[ i ]; - } + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); - } + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { - // + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - const cameraLPos = new Vector3(); - const cameraRPos = new Vector3(); + } else if ( useMultisampledRTT( renderTarget ) ) { - /** - * Assumes 2 cameras that are parallel and share an X-axis, and that - * the cameras' projection and world matrices have already been set. - * And that near and far planes are identical for both cameras. - * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 - */ - function setProjectionFromUnion( camera, cameraL, cameraR ) { + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); - cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + } else { - const ipd = cameraLPos.distanceTo( cameraRPos ); + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); - const projL = cameraL.projectionMatrix.elements; - const projR = cameraR.projectionMatrix.elements; + } - // VR systems will have identical far and near planes, and - // most likely identical top and bottom frustum extents. - // Use the left camera for these values. - const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); - const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); - const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; - const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + } - const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; - const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; - const left = near * leftFov; - const right = near * rightFov; + } - // Calculate the new camera's position offset from the - // left camera. xOffset should be roughly half `ipd`. - const zOffset = ipd / ( - leftFov + rightFov ); - const xOffset = zOffset * - leftFov; + _gl.bindRenderbuffer( 36161, null ); - // TODO: Better way to apply this offset? - cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); - camera.translateX( xOffset ); - camera.translateZ( zOffset ); - camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); - camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + } - // Find the union of the frustum values of the cameras and scale - // the values so that the near plane's position does not change in world space, - // although must now be relative to the new union camera. - const near2 = near + zOffset; - const far2 = far + zOffset; - const left2 = left - xOffset; - const right2 = right + ( ipd - xOffset ); - const top2 = topFov * far / far2 * near2; - const bottom2 = bottomFov * far / far2 * near2; + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { - camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); - } + state.bindFramebuffer( 36160, framebuffer ); - function updateCamera( camera, parent ) { + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { - if ( parent === null ) { + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); - camera.matrixWorld.copy( camera.matrix ); + } - } else { + // 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 ) { - camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; } - camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + setTexture2D( renderTarget.depthTexture, 0 ); - } + const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); - this.getCamera = function ( camera ) { + if ( renderTarget.depthTexture.format === DepthFormat ) { - cameraVR.near = cameraR.near = cameraL.near = camera.near; - cameraVR.far = cameraR.far = cameraL.far = camera.far; + if ( useMultisampledRTT( renderTarget ) ) { - if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples ); - // Note that the new renderState won't apply until the next frame. See #18320 + } else { - session.updateRenderState( { - depthNear: cameraVR.near, - depthFar: cameraVR.far - } ); + _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); - _currentDepthNear = cameraVR.near; - _currentDepthFar = cameraVR.far; + } - } + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { - const parent = camera.parent; - const cameras = cameraVR.cameras; + if ( useMultisampledRTT( renderTarget ) ) { - updateCamera( cameraVR, parent ); + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples ); - for ( let i = 0; i < cameras.length; i ++ ) { + } else { - updateCamera( cameras[ i ], parent ); + _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); - } + } - // update camera and its children + } else { - camera.matrixWorld.copy( cameraVR.matrixWorld ); - camera.matrix.copy( cameraVR.matrix ); - camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + throw new Error( 'Unknown depthTexture format' ); - const children = camera.children; + } - for ( let i = 0, l = children.length; i < l; i ++ ) { + } - children[ i ].updateMatrixWorld( true ); + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - } + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - // update projection matrix for proper view frustum culling + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { - if ( cameras.length === 2 ) { + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); - setProjectionFromUnion( cameraVR, cameraL, cameraR ); + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); } else { - // assume single camera setup (AR) + if ( isCube ) { - cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); + renderTargetProperties.__webglDepthbuffer = []; - } + for ( let i = 0; i < 6; i ++ ) { - return cameraVR; + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); - }; + } - // Animation Loop + } else { - let onAnimationFrameCallback = null; + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); - function onAnimationFrame( time, frame ) { + } + + } - pose = frame.getViewerPose( referenceSpace ); + state.bindFramebuffer( 36160, null ); - if ( pose !== null ) { + } - const views = pose.views; - const baseLayer = session.renderState.baseLayer; + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { - renderer.setFramebuffer( baseLayer.framebuffer ); + const renderTargetProperties = properties.get( renderTarget ); - let cameraVRNeedsUpdate = false; + if ( colorTexture !== undefined ) { - // check if it's necessary to rebuild cameraVR's camera list + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 ); - if ( views.length !== cameraVR.cameras.length ) { + } - cameraVR.cameras.length = 0; - cameraVRNeedsUpdate = true; + if ( depthTexture !== undefined ) { - } + setupDepthRenderbuffer( renderTarget ); - for ( let i = 0; i < views.length; i ++ ) { + } - const view = views[ i ]; - const viewport = baseLayer.getViewport( view ); + } - const camera = cameras[ i ]; - camera.matrix.fromArray( view.transform.matrix ); - camera.projectionMatrix.fromArray( view.projectionMatrix ); - camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - if ( i === 0 ) { + const texture = renderTarget.texture; - cameraVR.matrix.copy( camera.matrix ); + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); - } + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - if ( cameraVRNeedsUpdate === true ) { + if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { - cameraVR.cameras.push( camera ); + if ( textureProperties.__webglTexture === undefined ) { - } + textureProperties.__webglTexture = _gl.createTexture(); } - } + textureProperties.__version = texture.version; + info.memory.textures ++; - // + } - const inputSources = session.inputSources; + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - for ( let i = 0; i < controllers.length; i ++ ) { + // Setup framebuffer - const controller = controllers[ i ]; - const inputSource = inputSources[ i ]; + if ( isCube ) { - controller.update( inputSource, frame, referenceSpace ); + renderTargetProperties.__webglFramebuffer = []; - } + for ( let i = 0; i < 6; i ++ ) { - if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - } + } - const animation = new WebGLAnimation(); - animation.setAnimationLoop( onAnimationFrame ); + } else { - this.setAnimationLoop = function ( callback ) { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - onAnimationFrameCallback = callback; + if ( isMultipleRenderTargets ) { - }; + if ( capabilities.drawBuffers ) { - this.dispose = function () {}; + const textures = renderTarget.texture; -} + for ( let i = 0, il = textures.length; i < il; i ++ ) { -Object.assign( WebXRManager.prototype, EventDispatcher.prototype ); + const attachmentProperties = properties.get( textures[ i ] ); -function WebGLMaterials( properties ) { + if ( attachmentProperties.__webglTexture === undefined ) { - function refreshFogUniforms( uniforms, fog ) { + attachmentProperties.__webglTexture = _gl.createTexture(); - uniforms.fogColor.value.copy( fog.color ); + info.memory.textures ++; - if ( fog.isFog ) { + } - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + } - } else if ( fog.isFogExp2 ) { + } else { - uniforms.fogDensity.value = fog.density; + console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' ); - } + } - } + } - function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) { + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - if ( material.isMeshBasicMaterial ) { + const textures = isMultipleRenderTargets ? texture : [ texture ]; - refreshUniformsCommon( uniforms, material ); + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; - } else if ( material.isMeshLambertMaterial ) { + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsLambert( uniforms, material ); + for ( let i = 0; i < textures.length; i ++ ) { - } else if ( material.isMeshToonMaterial ) { + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); - refreshUniformsCommon( uniforms, material ); - refreshUniformsToon( uniforms, material ); + _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } else if ( material.isMeshPhongMaterial ) { + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsPhong( uniforms, material ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } else if ( material.isMeshStandardMaterial ) { + } - refreshUniformsCommon( uniforms, material ); + _gl.bindRenderbuffer( 36161, null ); - if ( material.isMeshPhysicalMaterial ) { + if ( renderTarget.depthBuffer ) { - refreshUniformsPhysical( uniforms, material ); + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); - } else { + } - refreshUniformsStandard( uniforms, material ); + state.bindFramebuffer( 36160, null ); } - } else if ( material.isMeshMatcapMaterial ) { - - refreshUniformsCommon( uniforms, material ); - refreshUniformsMatcap( uniforms, material ); + } - } else if ( material.isMeshDepthMaterial ) { + // Setup color buffer - refreshUniformsCommon( uniforms, material ); - refreshUniformsDepth( uniforms, material ); + if ( isCube ) { - } else if ( material.isMeshDistanceMaterial ) { + state.bindTexture( 34067, textureProperties.__webglTexture ); + setTextureParameters( 34067, texture, supportsMips ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsDistance( uniforms, material ); + for ( let i = 0; i < 6; i ++ ) { - } else if ( material.isMeshNormalMaterial ) { + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsNormal( uniforms, material ); + } - } else if ( material.isLineBasicMaterial ) { + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - refreshUniformsLine( uniforms, material ); + generateMipmap( 34067 ); - if ( material.isLineDashedMaterial ) { + } - refreshUniformsDash( uniforms, material ); + state.unbindTexture(); - } + } else if ( isMultipleRenderTargets ) { - } else if ( material.isPointsMaterial ) { + const textures = renderTarget.texture; - refreshUniformsPoints( uniforms, material, pixelRatio, height ); + for ( let i = 0, il = textures.length; i < il; i ++ ) { - } else if ( material.isSpriteMaterial ) { + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); - refreshUniformsSprites( uniforms, material ); + state.bindTexture( 3553, attachmentProperties.__webglTexture ); + setTextureParameters( 3553, attachment, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 ); - } else if ( material.isShadowMaterial ) { + if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) { - uniforms.color.value.copy( material.color ); - uniforms.opacity.value = material.opacity; + generateMipmap( 3553 ); - } else if ( material.isShaderMaterial ) { + } - material.uniformsNeedUpdate = false; // #15581 + } - } + state.unbindTexture(); - } + } else { - function refreshUniformsCommon( uniforms, material ) { + let glTextureType = 3553; - uniforms.opacity.value = material.opacity; + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { - if ( material.color ) { + if ( isWebGL2 ) { - uniforms.diffuse.value.copy( material.color ); + glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866; - } + } else { - if ( material.emissive ) { + console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' ); - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + } - } + } - if ( material.map ) { + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType ); - uniforms.map.value = material.map; + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - } + generateMipmap( glTextureType ); - if ( material.alphaMap ) { + } - uniforms.alphaMap.value = material.alphaMap; + state.unbindTexture(); } - if ( material.specularMap ) { + // Setup depth and stencil buffers - uniforms.specularMap.value = material.specularMap; + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); } - const envMap = properties.get( material ).envMap; + } - if ( envMap ) { + function updateRenderTargetMipmap( renderTarget ) { - uniforms.envMap.value = envMap; + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1; + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + for ( let i = 0, il = textures.length; i < il; i ++ ) { - const maxMipLevel = properties.get( envMap ).__maxMipLevel; + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - if ( maxMipLevel !== undefined ) { + const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; + const webglTexture = properties.get( texture ).__webglTexture; - uniforms.maxMipLevel.value = maxMipLevel; + state.bindTexture( target, webglTexture ); + generateMipmap( target ); + state.unbindTexture(); } } - if ( material.lightMap ) { + } - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + function updateMultisampleRenderTarget( renderTarget ) { - } + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - if ( material.aoMap ) { + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = 16384; + const invalidationArray = []; + const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { - } + for ( let i = 0; i < textures.length; i ++ ) { - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. displacementMap map - // 4. normal map - // 5. bump map - // 6. roughnessMap map - // 7. metalnessMap map - // 8. alphaMap map - // 9. emissiveMap map - // 10. clearcoat map - // 11. clearcoat normal map - // 12. clearcoat roughnessMap map + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null ); - let uvScaleMap; + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 ); - if ( material.map ) { + } - uvScaleMap = material.map; + } - } else if ( material.specularMap ) { + state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); + state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); - uvScaleMap = material.specularMap; + for ( let i = 0; i < textures.length; i ++ ) { - } else if ( material.displacementMap ) { + invalidationArray.push( 36064 + i ); - uvScaleMap = material.displacementMap; + if ( renderTarget.depthBuffer ) { - } else if ( material.normalMap ) { + invalidationArray.push( depthStyle ); - uvScaleMap = material.normalMap; + } - } else if ( material.bumpMap ) { + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; - uvScaleMap = material.bumpMap; + if ( ignoreDepthValues === false ) { - } else if ( material.roughnessMap ) { + if ( renderTarget.depthBuffer ) mask |= 256; + if ( renderTarget.stencilBuffer ) mask |= 1024; - uvScaleMap = material.roughnessMap; + } - } else if ( material.metalnessMap ) { + if ( isMultipleRenderTargets ) { - uvScaleMap = material.metalnessMap; + _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } else if ( material.alphaMap ) { + } - uvScaleMap = material.alphaMap; + if ( ignoreDepthValues === true ) { - } else if ( material.emissiveMap ) { + _gl.invalidateFramebuffer( 36008, [ depthStyle ] ); + _gl.invalidateFramebuffer( 36009, [ depthStyle ] ); - uvScaleMap = material.emissiveMap; + } - } else if ( material.clearcoatMap ) { + if ( isMultipleRenderTargets ) { - uvScaleMap = material.clearcoatMap; + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 ); - } else if ( material.clearcoatNormalMap ) { + } - uvScaleMap = material.clearcoatNormalMap; + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); - } else if ( material.clearcoatRoughnessMap ) { + if ( supportsInvalidateFramebuffer ) { - uvScaleMap = material.clearcoatRoughnessMap; + _gl.invalidateFramebuffer( 36008, invalidationArray ); - } + } - if ( uvScaleMap !== undefined ) { - // backwards compatibility - if ( uvScaleMap.isWebGLRenderTarget ) { + } - uvScaleMap = uvScaleMap.texture; + state.bindFramebuffer( 36008, null ); + state.bindFramebuffer( 36009, null ); - } + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { - if ( uvScaleMap.matrixAutoUpdate === true ) { + for ( let i = 0; i < textures.length; i ++ ) { - uvScaleMap.updateMatrix(); + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } + const webglTexture = properties.get( textures[ i ] ).__webglTexture; - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 ); - } + } - // uv repeat and offset setting priorities for uv2 - // 1. ao map - // 2. light map + } - let uv2ScaleMap; + state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer ); + + } - if ( material.aoMap ) { + } - uv2ScaleMap = material.aoMap; + function getRenderTargetSamples( renderTarget ) { - } else if ( material.lightMap ) { + return Math.min( maxSamples, renderTarget.samples ); - uv2ScaleMap = material.lightMap; + } - } + function useMultisampledRTT( renderTarget ) { - if ( uv2ScaleMap !== undefined ) { + const renderTargetProperties = properties.get( renderTarget ); - // backwards compatibility - if ( uv2ScaleMap.isWebGLRenderTarget ) { + return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; - uv2ScaleMap = uv2ScaleMap.texture; + } - } + function updateVideoTexture( texture ) { - if ( uv2ScaleMap.matrixAutoUpdate === true ) { + const frame = info.render.frame; - uv2ScaleMap.updateMatrix(); + // Check the last frame we updated the VideoTexture - } + if ( _videoTextures.get( texture ) !== frame ) { - uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + _videoTextures.set( texture, frame ); + texture.update(); } } - function refreshUniformsLine( uniforms, material ) { + function verifyColorSpace( texture, image ) { - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; + const encoding = texture.encoding; + const format = texture.format; + const type = texture.type; - } + if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image; - function refreshUniformsDash( uniforms, material ) { + if ( encoding !== LinearEncoding ) { - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + // sRGB - } + if ( encoding === sRGBEncoding ) { - function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + if ( isWebGL2 === false ) { - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * pixelRatio; - uniforms.scale.value = height * 0.5; + // in WebGL 1, try to use EXT_sRGB extension and unsized formats - if ( material.map ) { + if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) { - uniforms.map.value = material.map; + texture.format = _SRGBAFormat; - } + // it's not possible to generate mips in WebGL 1 with this extension - if ( material.alphaMap ) { + texture.minFilter = LinearFilter; + texture.generateMipmaps = false; - uniforms.alphaMap.value = material.alphaMap; + } else { - } + // slow fallback (CPU decode) - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map + image = ImageUtils.sRGBToLinear( image ); - let uvScaleMap; + } - if ( material.map ) { + } else { - uvScaleMap = material.map; + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format - } else if ( material.alphaMap ) { + if ( format !== RGBAFormat || type !== UnsignedByteType ) { - uvScaleMap = material.alphaMap; + console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); - } + } - if ( uvScaleMap !== undefined ) { + } - if ( uvScaleMap.matrixAutoUpdate === true ) { + } else { - uvScaleMap.updateMatrix(); + console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding ); } - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - } - } + return image; - function refreshUniformsSprites( uniforms, material ) { + } - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; - uniforms.rotation.value = material.rotation; + // - if ( material.map ) { + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; - uniforms.map.value = material.map; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; - } +} - if ( material.alphaMap ) { +function WebGLUtils( gl, extensions, capabilities ) { - uniforms.alphaMap.value = material.alphaMap; + const isWebGL2 = capabilities.isWebGL2; - } + function convert( p, encoding = null ) { - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map + let extension; - let uvScaleMap; + if ( p === UnsignedByteType ) return 5121; + if ( p === UnsignedShort4444Type ) return 32819; + if ( p === UnsignedShort5551Type ) return 32820; - if ( material.map ) { + if ( p === ByteType ) return 5120; + if ( p === ShortType ) return 5122; + if ( p === UnsignedShortType ) return 5123; + if ( p === IntType ) return 5124; + if ( p === UnsignedIntType ) return 5125; + if ( p === FloatType ) return 5126; - uvScaleMap = material.map; + if ( p === HalfFloatType ) { - } else if ( material.alphaMap ) { + if ( isWebGL2 ) return 5131; - uvScaleMap = material.alphaMap; + extension = extensions.get( 'OES_texture_half_float' ); - } + if ( extension !== null ) { - if ( uvScaleMap !== undefined ) { + return extension.HALF_FLOAT_OES; - if ( uvScaleMap.matrixAutoUpdate === true ) { + } else { - uvScaleMap.updateMatrix(); + return null; } - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - } - } + if ( p === AlphaFormat ) return 6406; + if ( p === RGBAFormat ) return 6408; + if ( p === LuminanceFormat ) return 6409; + if ( p === LuminanceAlphaFormat ) return 6410; + if ( p === DepthFormat ) return 6402; + if ( p === DepthStencilFormat ) return 34041; + if ( p === RedFormat ) return 6403; - function refreshUniformsLambert( uniforms, material ) { + // @deprecated since r137 - if ( material.emissiveMap ) { + if ( p === RGBFormat ) { - uniforms.emissiveMap.value = material.emissiveMap; + console.warn( 'THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228' ); + return 6408; } - } + // WebGL 1 sRGB fallback - function refreshUniformsPhong( uniforms, material ) { + if ( p === _SRGBAFormat ) { - uniforms.specular.value.copy( material.specular ); - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + extension = extensions.get( 'EXT_sRGB' ); - if ( material.emissiveMap ) { + if ( extension !== null ) { - uniforms.emissiveMap.value = material.emissiveMap; + return extension.SRGB_ALPHA_EXT; - } + } else { - if ( material.bumpMap ) { + return null; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + } } - if ( material.normalMap ) { + // WebGL2 formats. - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + if ( p === RedIntegerFormat ) return 36244; + if ( p === RGFormat ) return 33319; + if ( p === RGIntegerFormat ) return 33320; + if ( p === RGBAIntegerFormat ) return 36249; - } + // S3TC - if ( material.displacementMap ) { + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( encoding === sRGBEncoding ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); - } + if ( extension !== null ) { - function refreshUniformsToon( uniforms, material ) { + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - if ( material.gradientMap ) { + } else { - uniforms.gradientMap.value = material.gradientMap; + return null; - } + } - if ( material.emissiveMap ) { + } else { - uniforms.emissiveMap.value = material.emissiveMap; + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - } + if ( extension !== null ) { - if ( material.bumpMap ) { + 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; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + } else { - } + return null; - if ( material.normalMap ) { + } - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + } } - if ( material.displacementMap ) { + // PVRTC - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - } + if ( extension !== null ) { - function refreshUniformsStandard( uniforms, material ) { + 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; - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + } else { - if ( material.roughnessMap ) { + return null; - uniforms.roughnessMap.value = material.roughnessMap; + } } - if ( material.metalnessMap ) { + // ETC1 - uniforms.metalnessMap.value = material.metalnessMap; + if ( p === RGB_ETC1_Format ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - if ( material.emissiveMap ) { + if ( extension !== null ) { - uniforms.emissiveMap.value = material.emissiveMap; + return extension.COMPRESSED_RGB_ETC1_WEBGL; - } + } else { - if ( material.bumpMap ) { + return null; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + } } - if ( material.normalMap ) { + // ETC2 - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); - if ( material.displacementMap ) { + if ( extension !== null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + + } else { + + return null; + + } } - const envMap = properties.get( material ).envMap; + // ASTC - if ( envMap ) { + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } } - } + // BPTC + + if ( p === RGBA_BPTC_Format ) { - function refreshUniformsPhysical( uniforms, material ) { + extension = extensions.get( 'EXT_texture_compression_bptc' ); - refreshUniformsStandard( uniforms, material ); + if ( extension !== null ) { - uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common + if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; - uniforms.clearcoat.value = material.clearcoat; - uniforms.clearcoatRoughness.value = material.clearcoatRoughness; - if ( material.sheen ) uniforms.sheen.value.copy( material.sheen ); + } else { - if ( material.clearcoatMap ) { + return null; - uniforms.clearcoatMap.value = material.clearcoatMap; + } } - if ( material.clearcoatRoughnessMap ) { + // - uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + if ( p === UnsignedInt248Type ) { - } + if ( isWebGL2 ) return 34042; - if ( material.clearcoatNormalMap ) { + extension = extensions.get( 'WEBGL_depth_texture' ); + + if ( extension !== null ) { - uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); - uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + return extension.UNSIGNED_INT_24_8_WEBGL; - if ( material.side === BackSide ) { + } else { - uniforms.clearcoatNormalScale.value.negate(); + return null; } } - uniforms.transmission.value = material.transmission; + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) - if ( material.transmissionMap ) { + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; - uniforms.transmissionMap.value = material.transmissionMap; + } - } + return { convert: convert }; + +} + +class ArrayCamera extends PerspectiveCamera { + + constructor( array = [] ) { + + super(); + + this.isArrayCamera = true; + + this.cameras = array; } - function refreshUniformsMatcap( uniforms, material ) { +} - if ( material.matcap ) { +class Group extends Object3D { - uniforms.matcap.value = material.matcap; + constructor() { - } + super(); - if ( material.bumpMap ) { + this.isGroup = true; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + this.type = 'Group'; - } + } - if ( material.normalMap ) { +} - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); +const _moveEvent = { type: 'move' }; - } +class WebXRController { - if ( material.displacementMap ) { + constructor() { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._targetRay = null; + this._grip = null; + this._hand = null; + + } + + getHandSpace() { + + if ( this._hand === null ) { + + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; } + return this._hand; + } - function refreshUniformsDepth( uniforms, material ) { + getTargetRaySpace() { - if ( material.displacementMap ) { + if ( this._targetRay === null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); } + return this._targetRay; + } - function refreshUniformsDistance( uniforms, material ) { + getGripSpace() { - if ( material.displacementMap ) { + if ( this._grip === null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); } - uniforms.referencePosition.value.copy( material.referencePosition ); - uniforms.nearDistance.value = material.nearDistance; - uniforms.farDistance.value = material.farDistance; + return this._grip; } - function refreshUniformsNormal( uniforms, material ) { + dispatchEvent( event ) { - if ( material.bumpMap ) { + if ( this._targetRay !== null ) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + this._targetRay.dispatchEvent( event ); } - if ( material.normalMap ) { + if ( this._grip !== null ) { - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + this._grip.dispatchEvent( event ); } - if ( material.displacementMap ) { + if ( this._hand !== null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._hand.dispatchEvent( event ); } - } - - return { - refreshFogUniforms: refreshFogUniforms, - refreshMaterialUniforms: refreshMaterialUniforms - }; + return this; -} + } -function createCanvasElement() { + disconnect( inputSource ) { - const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.style.display = 'block'; - return canvas; + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); -} + if ( this._targetRay !== null ) { -function WebGLRenderer( parameters ) { + this._targetRay.visible = false; - parameters = parameters || {}; + } - const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), - _context = parameters.context !== undefined ? parameters.context : null, + if ( this._grip !== 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, - _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', - _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; + this._grip.visible = false; - let currentRenderList = null; - let currentRenderState = null; + } - // render() can be called from within a callback triggered by another render. - // We track this so that the nested render call gets its list and state isolated from the parent render call. + if ( this._hand !== null ) { - const renderListStack = []; - const renderStateStack = []; + this._hand.visible = false; - // public properties + } - this.domElement = _canvas; + return this; - // Debug configuration container - this.debug = { + } - /** - * Enables error checking and reporting when shader programs are being compiled - * @type {boolean} - */ - checkShaderErrors: true - }; + update( inputSource, frame, referenceSpace ) { - // clearing + let inputPose = null; + let gripPose = null; + let handPose = null; - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; - // scene graph + if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { - this.sortObjects = true; + if ( hand && inputSource.hand ) { - // user-defined clipping + handPose = true; - this.clippingPlanes = []; - this.localClippingEnabled = false; + for ( const inputjoint of inputSource.hand.values() ) { - // physically based shading + // Update the joints groups with the XRJoint poses + const jointPose = frame.getJointPose( inputjoint, referenceSpace ); - this.gammaFactor = 2.0; // for backwards compatibility - this.outputEncoding = LinearEncoding; + if ( hand.joints[ inputjoint.jointName ] === undefined ) { - // physical lights + // The transform of this joint will be updated with the joint pose on each frame + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[ inputjoint.jointName ] = joint; + // ?? + hand.add( joint ); - this.physicallyCorrectLights = false; + } - // tone mapping + const joint = hand.joints[ inputjoint.jointName ]; - this.toneMapping = NoToneMapping; - this.toneMappingExposure = 1.0; + if ( jointPose !== null ) { - // morphs + joint.matrix.fromArray( jointPose.transform.matrix ); + joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); + joint.jointRadius = jointPose.radius; - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + } - // internal properties + joint.visible = jointPose !== null; - const _this = this; + } - let _isContextLost = false; + // Custom events - // internal state cache + // Check pinchz + const indexTip = hand.joints[ 'index-finger-tip' ]; + const thumbTip = hand.joints[ 'thumb-tip' ]; + const distance = indexTip.position.distanceTo( thumbTip.position ); - let _framebuffer = null; + const distanceToPinch = 0.02; + const threshold = 0.005; - let _currentActiveCubeFace = 0; - let _currentActiveMipmapLevel = 0; - let _currentRenderTarget = null; - let _currentFramebuffer = null; - let _currentMaterialId = - 1; + if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { - let _currentCamera = null; + hand.inputState.pinching = false; + this.dispatchEvent( { + type: 'pinchend', + handedness: inputSource.handedness, + target: this + } ); - const _currentViewport = new Vector4(); - const _currentScissor = new Vector4(); - let _currentScissorTest = null; + } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { - // + hand.inputState.pinching = true; + this.dispatchEvent( { + type: 'pinchstart', + handedness: inputSource.handedness, + target: this + } ); - let _width = _canvas.width; - let _height = _canvas.height; + } - let _pixelRatio = 1; - let _opaqueSort = null; - let _transparentSort = null; + } else { - const _viewport = new Vector4( 0, 0, _width, _height ); - const _scissor = new Vector4( 0, 0, _width, _height ); - let _scissorTest = false; + if ( grip !== null && inputSource.gripSpace ) { - // frustum + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); - const _frustum = new Frustum(); + if ( gripPose !== null ) { - // clipping + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); - let _clippingEnabled = false; - let _localClippingEnabled = false; + if ( gripPose.linearVelocity ) { - // camera matrices cache + grip.hasLinearVelocity = true; + grip.linearVelocity.copy( gripPose.linearVelocity ); - const _projScreenMatrix = new Matrix4(); + } else { - const _vector3 = new Vector3(); + grip.hasLinearVelocity = false; - const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + } - function getTargetPixelRatio() { + if ( gripPose.angularVelocity ) { - return _currentRenderTarget === null ? _pixelRatio : 1; + grip.hasAngularVelocity = true; + grip.angularVelocity.copy( gripPose.angularVelocity ); - } + } else { - // initialize + grip.hasAngularVelocity = false; - let _gl = _context; + } - function getContext( contextNames, contextAttributes ) { + } - for ( let i = 0; i < contextNames.length; i ++ ) { + } - const contextName = contextNames[ i ]; - const context = _canvas.getContext( contextName, contextAttributes ); - if ( context !== null ) return context; + } - } + if ( targetRay !== null ) { - return null; + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); - } + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { - try { + inputPose = gripPose; - const contextAttributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer, - powerPreference: _powerPreference, - failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat - }; + } - // event listeners must be registered before WebGL context is created, see #12753 + if ( inputPose !== null ) { - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); - if ( _gl === null ) { + if ( inputPose.linearVelocity ) { - const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); - if ( _this.isWebGL1Renderer === true ) { + } else { - contextNames.shift(); + targetRay.hasLinearVelocity = false; - } + } - _gl = getContext( contextNames, contextAttributes ); + if ( inputPose.angularVelocity ) { - if ( _gl === null ) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); - if ( getContext( contextNames ) ) { + } else { - throw new Error( 'Error creating WebGL context with your selected attributes.' ); + targetRay.hasAngularVelocity = false; - } else { + } - throw new Error( 'Error creating WebGL context.' ); + this.dispatchEvent( _moveEvent ); } } + } - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + if ( targetRay !== null ) { - if ( _gl.getShaderPrecisionFormat === undefined ) { + targetRay.visible = ( inputPose !== null ); - _gl.getShaderPrecisionFormat = function () { + } - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + if ( grip !== null ) { - }; + grip.visible = ( gripPose !== null ); } - } catch ( error ) { + if ( hand !== null ) { - console.error( 'THREE.WebGLRenderer: ' + error.message ); - throw error; + hand.visible = ( handPose !== null ); + + } + + return this; } - let extensions, capabilities, state, info; - let properties, textures, cubemaps, attributes, geometries, objects; - let programCache, materials, renderLists, renderStates, clipping; +} - let background, morphtargets, bufferRenderer, indexedBufferRenderer; +class DepthTexture extends Texture { - let utils, bindingStates; + constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { - function initGLContext() { + format = format !== undefined ? format : DepthFormat; - extensions = new WebGLExtensions( _gl ); + if ( format !== DepthFormat && format !== DepthStencilFormat ) { - capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); - extensions.init( capabilities ); + } - utils = new WebGLUtils( _gl, extensions, capabilities ); + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; - state = new WebGLState( _gl, extensions, capabilities ); - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - info = new WebGLInfo( _gl ); - properties = new WebGLProperties(); - textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); - cubemaps = new WebGLCubeMaps( _this ); - attributes = new WebGLAttributes( _gl, capabilities ); - bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); - geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); - objects = new WebGLObjects( _gl, geometries, attributes, info ); - morphtargets = new WebGLMorphtargets( _gl ); - clipping = new WebGLClipping( properties ); - programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping ); - materials = new WebGLMaterials( properties ); - renderLists = new WebGLRenderLists( properties ); - renderStates = new WebGLRenderStates( extensions, capabilities ); - background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha ); + this.isDepthTexture = true; - bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); - indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); + this.image = { width: width, height: height }; - info.programs = programCache.programs; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - _this.capabilities = capabilities; - _this.extensions = extensions; - _this.properties = properties; - _this.renderLists = renderLists; - _this.state = state; - _this.info = info; + this.flipY = false; + this.generateMipmaps = false; } - initGLContext(); - // xr +} - const xr = new WebXRManager( _this, _gl ); +class WebXRManager extends EventDispatcher { - this.xr = xr; + constructor( renderer, gl ) { - // shadow map + super(); - const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); + const scope = this; - this.shadowMap = shadowMap; + let session = null; + let framebufferScaleFactor = 1.0; - // API + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + let customReferenceSpace = null; - this.getContext = function () { + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; - return _gl; + const controllers = []; + const controllerInputSources = []; - }; + // - this.getContextAttributes = function () { + const cameraL = new PerspectiveCamera(); + cameraL.layers.enable( 1 ); + cameraL.viewport = new Vector4(); - return _gl.getContextAttributes(); + const cameraR = new PerspectiveCamera(); + cameraR.layers.enable( 2 ); + cameraR.viewport = new Vector4(); - }; + const cameras = [ cameraL, cameraR ]; - this.forceContextLoss = function () { + const cameraVR = new ArrayCamera(); + cameraVR.layers.enable( 1 ); + cameraVR.layers.enable( 2 ); - const extension = extensions.get( 'WEBGL_lose_context' ); - if ( extension ) extension.loseContext(); + let _currentDepthNear = null; + let _currentDepthFar = null; - }; + // - this.forceContextRestore = function () { + this.cameraAutoUpdate = true; + this.enabled = false; - const extension = extensions.get( 'WEBGL_lose_context' ); - if ( extension ) extension.restoreContext(); + this.isPresenting = false; - }; + this.getController = function ( index ) { - this.getPixelRatio = function () { + let controller = controllers[ index ]; - return _pixelRatio; + if ( controller === undefined ) { - }; + controller = new WebXRController(); + controllers[ index ] = controller; - this.setPixelRatio = function ( value ) { + } - if ( value === undefined ) return; + return controller.getTargetRaySpace(); - _pixelRatio = value; + }; - this.setSize( _width, _height, false ); + this.getControllerGrip = function ( index ) { - }; + let controller = controllers[ index ]; - this.getSize = function ( target ) { + if ( controller === undefined ) { - if ( target === undefined ) { + controller = new WebXRController(); + controllers[ index ] = controller; - console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' ); + } - target = new Vector2(); + return controller.getGripSpace(); - } + }; - return target.set( _width, _height ); + this.getHand = function ( index ) { - }; + let controller = controllers[ index ]; - this.setSize = function ( width, height, updateStyle ) { + if ( controller === undefined ) { - if ( xr.isPresenting ) { + controller = new WebXRController(); + controllers[ index ] = controller; - console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); - return; + } - } + return controller.getHandSpace(); - _width = width; - _height = height; + }; - _canvas.width = Math.floor( width * _pixelRatio ); - _canvas.height = Math.floor( height * _pixelRatio ); + // - if ( updateStyle !== false ) { + function onSessionEvent( event ) { - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); - } + if ( controllerIndex === - 1 ) { - this.setViewport( 0, 0, width, height ); + return; - }; + } - this.getDrawingBufferSize = function ( target ) { + const controller = controllers[ controllerIndex ]; - if ( target === undefined ) { + if ( controller !== undefined ) { - console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' ); + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); - target = new Vector2(); + } } - return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); - - }; - - this.setDrawingBufferSize = function ( width, height, pixelRatio ) { - - _width = width; - _height = height; - - _pixelRatio = pixelRatio; - - _canvas.width = Math.floor( width * pixelRatio ); - _canvas.height = Math.floor( height * pixelRatio ); - - this.setViewport( 0, 0, width, height ); - - }; + function onSessionEnd() { - this.getCurrentViewport = function ( target ) { + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); - if ( target === undefined ) { + for ( let i = 0; i < controllers.length; i ++ ) { - console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' ); + const inputSource = controllerInputSources[ i ]; - target = new Vector4(); + if ( inputSource === null ) continue; - } + controllerInputSources[ i ] = null; - return target.copy( _currentViewport ); + controllers[ i ].disconnect( inputSource ); - }; + } - this.getViewport = function ( target ) { + _currentDepthNear = null; + _currentDepthFar = null; - return target.copy( _viewport ); + // restore framebuffer/rendering state - }; + renderer.setRenderTarget( initialRenderTarget ); - this.setViewport = function ( x, y, width, height ) { + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; - if ( x.isVector4 ) { + // - _viewport.set( x.x, x.y, x.z, x.w ); + animation.stop(); - } else { + scope.isPresenting = false; - _viewport.set( x, y, width, height ); + scope.dispatchEvent( { type: 'sessionend' } ); } - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); - - }; - - this.getScissor = function ( target ) { - - return target.copy( _scissor ); - - }; + this.setFramebufferScaleFactor = function ( value ) { - this.setScissor = function ( x, y, width, height ) { + framebufferScaleFactor = value; - if ( x.isVector4 ) { + if ( scope.isPresenting === true ) { - _scissor.set( x.x, x.y, x.z, x.w ); + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); - } else { + } - _scissor.set( x, y, width, height ); + }; - } + this.setReferenceSpaceType = function ( value ) { - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + referenceSpaceType = value; - }; + if ( scope.isPresenting === true ) { - this.getScissorTest = function () { + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); - return _scissorTest; + } - }; + }; - this.setScissorTest = function ( boolean ) { + this.getReferenceSpace = function () { - state.setScissorTest( _scissorTest = boolean ); + return customReferenceSpace || referenceSpace; - }; + }; - this.setOpaqueSort = function ( method ) { + this.setReferenceSpace = function ( space ) { - _opaqueSort = method; + customReferenceSpace = space; - }; + }; - this.setTransparentSort = function ( method ) { + this.getBaseLayer = function () { - _transparentSort = method; + return glProjLayer !== null ? glProjLayer : glBaseLayer; - }; + }; - // Clearing + this.getBinding = function () { - this.getClearColor = function ( target ) { + return glBinding; - if ( target === undefined ) { + }; - console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' ); + this.getFrame = function () { - target = new Color(); + return xrFrame; - } + }; - return target.copy( background.getClearColor() ); + this.getSession = function () { - }; + return session; - this.setClearColor = function () { + }; - background.setClearColor.apply( background, arguments ); + this.setSession = async function ( value ) { - }; + session = value; - this.getClearAlpha = function () { + if ( session !== null ) { - return background.getClearAlpha(); + initialRenderTarget = renderer.getRenderTarget(); - }; + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); - this.setClearAlpha = function () { + if ( attributes.xrCompatible !== true ) { - background.setClearAlpha.apply( background, arguments ); + await gl.makeXRCompatible(); - }; + } - this.clear = function ( color, depth, stencil ) { + if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) { - let bits = 0; + const layerInit = { + antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true, + alpha: attributes.alpha, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; - if ( color === undefined || color ) bits |= 16384; - if ( depth === undefined || depth ) bits |= 256; - if ( stencil === undefined || stencil ) bits |= 1024; + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); - _gl.clear( bits ); + session.updateRenderState( { baseLayer: glBaseLayer } ); - }; + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + encoding: renderer.outputEncoding, + stencilBuffer: attributes.stencil + } + ); - this.clearColor = function () { + } else { - this.clear( true, false, false ); + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; - }; + if ( attributes.depth ) { - this.clearDepth = function () { + glDepthFormat = attributes.stencil ? 35056 : 33190; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; - this.clear( false, true, false ); + } - }; + const projectionlayerInit = { + colorFormat: 32856, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; - this.clearStencil = function () { + glBinding = new XRWebGLBinding( session, gl ); - this.clear( false, false, true ); + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); - }; + session.updateRenderState( { layers: [ glProjLayer ] } ); - // + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + encoding: renderer.outputEncoding, + samples: attributes.antialias ? 4 : 0 + } ); - this.dispose = function () { + const renderTargetProperties = renderer.properties.get( newRenderTarget ); + renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + } - renderLists.dispose(); - renderStates.dispose(); - properties.dispose(); - cubemaps.dispose(); - objects.dispose(); - bindingStates.dispose(); + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 - xr.dispose(); + // Set foveation to maximum. + this.setFoveation( 1.0 ); - animation.stop(); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); - }; + animation.setContext( session ); + animation.start(); - // Events + scope.isPresenting = true; - function onContextLost( event ) { + scope.dispatchEvent( { type: 'sessionstart' } ); - event.preventDefault(); + } - console.log( 'THREE.WebGLRenderer: Context Lost.' ); + }; - _isContextLost = true; + function onInputSourcesChange( event ) { - } + // Notify disconnected - function onContextRestore( /* event */ ) { + for ( let i = 0; i < event.removed.length; i ++ ) { - console.log( 'THREE.WebGLRenderer: Context Restored.' ); + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); - _isContextLost = false; + if ( index >= 0 ) { - initGLContext(); + controllerInputSources[ index ] = null; + controllers[ index ].dispatchEvent( { type: 'disconnected', data: inputSource } ); - } + } - function onMaterialDispose( event ) { + } - const material = event.target; + // Notify connected - material.removeEventListener( 'dispose', onMaterialDispose ); + for ( let i = 0; i < event.added.length; i ++ ) { - deallocateMaterial( material ); + const inputSource = event.added[ i ]; - } + let controllerIndex = controllerInputSources.indexOf( inputSource ); - // Buffer deallocation + if ( controllerIndex === - 1 ) { - function deallocateMaterial( material ) { + // Assign input source a controller that currently has no input source - releaseMaterialProgramReference( material ); + for ( let i = 0; i < controllers.length; i ++ ) { - properties.remove( material ); + if ( i >= controllerInputSources.length ) { - } + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + } else if ( controllerInputSources[ i ] === null ) { - function releaseMaterialProgramReference( material ) { + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; - const programInfo = properties.get( material ).program; + } - if ( programInfo !== undefined ) { + } - programCache.releaseProgram( programInfo ); + // If all controllers do currently receive input we ignore new ones - } + if ( controllerIndex === - 1 ) break; - } + } - // Buffer rendering + const controller = controllers[ controllerIndex ]; - function renderObjectImmediate( object, program ) { + if ( controller ) { - object.render( function ( object ) { + controller.dispatchEvent( { type: 'connected', data: inputSource } ); - _this.renderBufferImmediate( object, program ); + } - } ); + } - } + } - this.renderBufferImmediate = function ( object, program ) { + // - bindingStates.initAttributes(); + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); - const buffers = properties.get( object ); + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { - 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(); + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); - const programAttributes = program.getAttributes(); + const ipd = cameraLPos.distanceTo( cameraRPos ); - if ( object.hasPositions ) { + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; - _gl.bindBuffer( 34962, buffers.position ); - _gl.bufferData( 34962, object.positionArray, 35048 ); + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; - bindingStates.enableAttribute( programAttributes.position ); - _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 ); + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; - } + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; - if ( object.hasNormals ) { + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); - _gl.bindBuffer( 34962, buffers.normal ); - _gl.bufferData( 34962, object.normalArray, 35048 ); + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; - bindingStates.enableAttribute( programAttributes.normal ); - _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 ); + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); } - if ( object.hasUvs ) { + function updateCamera( camera, parent ) { - _gl.bindBuffer( 34962, buffers.uv ); - _gl.bufferData( 34962, object.uvArray, 35048 ); + if ( parent === null ) { - bindingStates.enableAttribute( programAttributes.uv ); - _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 ); + camera.matrixWorld.copy( camera.matrix ); - } + } else { - if ( object.hasColors ) { + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); - _gl.bindBuffer( 34962, buffers.color ); - _gl.bufferData( 34962, object.colorArray, 35048 ); + } - bindingStates.enableAttribute( programAttributes.color ); - _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); } - bindingStates.disableUnusedAttributes(); + this.updateCamera = function ( camera ) { - _gl.drawArrays( 4, 0, object.count ); + if ( session === null ) return; - object.count = 0; + cameraVR.near = cameraR.near = cameraL.near = camera.near; + cameraVR.far = cameraR.far = cameraL.far = camera.far; - }; + if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { - this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + // Note that the new renderState won't apply until the next frame. See #18320 - if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + session.updateRenderState( { + depthNear: cameraVR.near, + depthFar: cameraVR.far + } ); - const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + _currentDepthNear = cameraVR.near; + _currentDepthFar = cameraVR.far; - const program = setProgram( camera, scene, material, object ); + } - state.setMaterial( material, frontFaceCW ); + const parent = camera.parent; + const cameras = cameraVR.cameras; - // + updateCamera( cameraVR, parent ); - let index = geometry.index; - const position = geometry.attributes.position; + for ( let i = 0; i < cameras.length; i ++ ) { - // + updateCamera( cameras[ i ], parent ); - if ( index === null ) { + } - if ( position === undefined || position.count === 0 ) return; + cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale ); - } else if ( index.count === 0 ) { + // update user camera and its children - return; + camera.matrix.copy( cameraVR.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); - } + const children = camera.children; - // + for ( let i = 0, l = children.length; i < l; i ++ ) { - let rangeFactor = 1; + children[ i ].updateMatrixWorld( true ); - if ( material.wireframe === true ) { + } - index = geometries.getWireframeAttribute( geometry ); - rangeFactor = 2; + // update projection matrix for proper view frustum culling - } + if ( cameras.length === 2 ) { - if ( material.morphTargets || material.morphNormals ) { + setProjectionFromUnion( cameraVR, cameraL, cameraR ); - morphtargets.update( object, geometry, material, program ); + } else { - } + // assume single camera setup (AR) - bindingStates.setup( object, material, program, geometry, index ); + cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); - let attribute; - let renderer = bufferRenderer; + } - if ( index !== null ) { + }; - attribute = attributes.get( index ); + this.getCamera = function () { - renderer = indexedBufferRenderer; - renderer.setIndex( attribute ); + return cameraVR; - } + }; - // + this.getFoveation = function () { - const dataCount = ( index !== null ) ? index.count : position.count; + if ( glProjLayer !== null ) { - const rangeStart = geometry.drawRange.start * rangeFactor; - const rangeCount = geometry.drawRange.count * rangeFactor; + return glProjLayer.fixedFoveation; - const groupStart = group !== null ? group.start * rangeFactor : 0; - const groupCount = group !== null ? group.count * rangeFactor : Infinity; + } - const drawStart = Math.max( rangeStart, groupStart ); - const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + if ( glBaseLayer !== null ) { - const drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + return glBaseLayer.fixedFoveation; - if ( drawCount === 0 ) return; + } - // + return undefined; - if ( object.isMesh ) { + }; - if ( material.wireframe === true ) { + this.setFoveation = function ( foveation ) { - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( 1 ); + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution - } else { + if ( glProjLayer !== null ) { - renderer.setMode( 4 ); + glProjLayer.fixedFoveation = foveation; } - } else if ( object.isLine ) { - - let lineWidth = material.linewidth; - - if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + glBaseLayer.fixedFoveation = foveation; - if ( object.isLineSegments ) { + } - renderer.setMode( 1 ); + }; - } else if ( object.isLineLoop ) { + // Animation Loop - renderer.setMode( 2 ); + let onAnimationFrameCallback = null; - } else { + function onAnimationFrame( time, frame ) { - renderer.setMode( 3 ); + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; - } + if ( pose !== null ) { - } else if ( object.isPoints ) { + const views = pose.views; - renderer.setMode( 0 ); + if ( glBaseLayer !== null ) { - } else if ( object.isSprite ) { + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); - renderer.setMode( 4 ); + } - } + let cameraVRNeedsUpdate = false; - if ( object.isInstancedMesh ) { + // check if it's necessary to rebuild cameraVR's camera list - renderer.renderInstances( drawStart, drawCount, object.count ); + if ( views.length !== cameraVR.cameras.length ) { - } else if ( geometry.isInstancedBufferGeometry ) { + cameraVR.cameras.length = 0; + cameraVRNeedsUpdate = true; - const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount ); + } - renderer.renderInstances( drawStart, drawCount, instanceCount ); + for ( let i = 0; i < views.length; i ++ ) { - } else { + const view = views[ i ]; - renderer.render( drawStart, drawCount ); + let viewport = null; - } + if ( glBaseLayer !== null ) { - }; + viewport = glBaseLayer.getViewport( view ); - // Compile + } else { - this.compile = function ( scene, camera ) { + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; - currentRenderState = renderStates.get( scene ); - currentRenderState.init(); + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { - scene.traverseVisible( function ( object ) { + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture ); - if ( object.isLight && object.layers.test( camera.layers ) ) { + renderer.setRenderTarget( newRenderTarget ); - currentRenderState.pushLight( object ); + } - if ( object.castShadow ) { + } - currentRenderState.pushShadow( object ); + let camera = cameras[ i ]; - } + if ( camera === undefined ) { - } + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; - } ); + } - currentRenderState.setupLights(); + camera.matrix.fromArray( view.transform.matrix ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); - const compiled = new WeakMap(); + if ( i === 0 ) { - scene.traverse( function ( object ) { + cameraVR.matrix.copy( camera.matrix ); - const material = object.material; + } - if ( material ) { + if ( cameraVRNeedsUpdate === true ) { - if ( Array.isArray( material ) ) { + cameraVR.cameras.push( camera ); - for ( let i = 0; i < material.length; i ++ ) { + } - const material2 = material[ i ]; + } - if ( compiled.has( material2 ) === false ) { + } - initMaterial( material2, scene, object ); - compiled.set( material2 ); + // - } + for ( let i = 0; i < controllers.length; i ++ ) { - } + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; - } else if ( compiled.has( material ) === false ) { + if ( inputSource !== null && controller !== undefined ) { - initMaterial( material, scene, object ); - compiled.set( material ); + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); } } - } ); + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); - }; + xrFrame = null; - // Animation Loop + } - let onAnimationFrameCallback = null; + const animation = new WebGLAnimation(); - function onAnimationFrame( time ) { + animation.setAnimationLoop( onAnimationFrame ); - if ( xr.isPresenting ) return; - if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + this.setAnimationLoop = function ( callback ) { - } + onAnimationFrameCallback = callback; - const animation = new WebGLAnimation(); - animation.setAnimationLoop( onAnimationFrame ); + }; - if ( typeof window !== 'undefined' ) animation.setContext( window ); + this.dispose = function () {}; - this.setAnimationLoop = function ( callback ) { + } - onAnimationFrameCallback = callback; - xr.setAnimationLoop( callback ); +} - ( callback === null ) ? animation.stop() : animation.start(); +function WebGLMaterials( renderer, properties ) { - }; + function refreshFogUniforms( uniforms, fog ) { - // Rendering + uniforms.fogColor.value.copy( fog.color ); - this.render = function ( scene, camera ) { + if ( fog.isFog ) { - let renderTarget, forceClear; + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - if ( arguments[ 2 ] !== undefined ) { + } else if ( fog.isFogExp2 ) { - console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' ); - renderTarget = arguments[ 2 ]; + uniforms.fogDensity.value = fog.density; } - if ( arguments[ 3 ] !== undefined ) { - - console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' ); - forceClear = arguments[ 3 ]; - - } + } - if ( camera !== undefined && camera.isCamera !== true ) { + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + if ( material.isMeshBasicMaterial ) { - } + refreshUniformsCommon( uniforms, material ); - if ( _isContextLost === true ) return; + } else if ( material.isMeshLambertMaterial ) { - // reset caching for this frame + refreshUniformsCommon( uniforms, material ); - bindingStates.resetDefaultState(); - _currentMaterialId = - 1; - _currentCamera = null; + } else if ( material.isMeshToonMaterial ) { - // update scene graph + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + } else if ( material.isMeshPhongMaterial ) { - // update camera matrices and frustum + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); - if ( camera.parent === null ) camera.updateMatrixWorld(); + } else if ( material.isMeshStandardMaterial ) { - if ( xr.enabled === true && xr.isPresenting === true ) { + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); - camera = xr.getCamera( camera ); + if ( material.isMeshPhysicalMaterial ) { - } + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); - // - if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget ); + } - currentRenderState = renderStates.get( scene, renderStateStack.length ); - currentRenderState.init(); + } else if ( material.isMeshMatcapMaterial ) { - renderStateStack.push( currentRenderState ); + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromProjectionMatrix( _projScreenMatrix ); + } else if ( material.isMeshDepthMaterial ) { - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + refreshUniformsCommon( uniforms, material ); - currentRenderList = renderLists.get( scene, renderListStack.length ); - currentRenderList.init(); + } else if ( material.isMeshDistanceMaterial ) { - renderListStack.push( currentRenderList ); + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); - projectObject( scene, camera, 0, _this.sortObjects ); + } else if ( material.isMeshNormalMaterial ) { - currentRenderList.finish(); + refreshUniformsCommon( uniforms, material ); - if ( _this.sortObjects === true ) { + } else if ( material.isLineBasicMaterial ) { - currentRenderList.sort( _opaqueSort, _transparentSort ); + refreshUniformsLine( uniforms, material ); - } + if ( material.isLineDashedMaterial ) { - // + refreshUniformsDash( uniforms, material ); - if ( _clippingEnabled === true ) clipping.beginShadows(); + } - const shadowsArray = currentRenderState.state.shadowsArray; + } else if ( material.isPointsMaterial ) { - shadowMap.render( shadowsArray, scene, camera ); + refreshUniformsPoints( uniforms, material, pixelRatio, height ); - currentRenderState.setupLights(); - currentRenderState.setupLightsView( camera ); + } else if ( material.isSpriteMaterial ) { - if ( _clippingEnabled === true ) clipping.endShadows(); + refreshUniformsSprites( uniforms, material ); - // + } else if ( material.isShadowMaterial ) { - if ( this.info.autoReset === true ) this.info.reset(); + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; - if ( renderTarget !== undefined ) { + } else if ( material.isShaderMaterial ) { - this.setRenderTarget( renderTarget ); + material.uniformsNeedUpdate = false; // #15581 } - // + } + + function refreshUniformsCommon( uniforms, material ) { - background.render( currentRenderList, scene, camera, forceClear ); + uniforms.opacity.value = material.opacity; - // render scene + if ( material.color ) { - const opaqueObjects = currentRenderList.opaque; - const transparentObjects = currentRenderList.transparent; + uniforms.diffuse.value.copy( material.color ); - if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); - if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + } - // + if ( material.emissive ) { - if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - // + } - if ( _currentRenderTarget !== null ) { + if ( material.map ) { - // Generate mipmap if we're using any kind of mipmap filtering + uniforms.map.value = material.map; - textures.updateRenderTargetMipmap( _currentRenderTarget ); + } - // resolve multisample renderbuffers to a single-sample texture if necessary + if ( material.alphaMap ) { - textures.updateMultisampleRenderTarget( _currentRenderTarget ); + uniforms.alphaMap.value = material.alphaMap; } - // Ensure depth buffer writing is enabled so it can be cleared on next render + if ( material.bumpMap ) { - state.buffers.depth.setTest( true ); - state.buffers.depth.setMask( true ); - state.buffers.color.setMask( true ); + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; - state.setPolygonOffset( false ); + } - // _gl.finish(); + if ( material.displacementMap ) { - renderStateStack.pop(); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - if ( renderStateStack.length > 0 ) { + } - currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + if ( material.emissiveMap ) { - } else { + uniforms.emissiveMap.value = material.emissiveMap; - currentRenderState = null; + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); } - renderListStack.pop(); + if ( material.specularMap ) { - if ( renderListStack.length > 0 ) { + uniforms.specularMap.value = material.specularMap; - currentRenderList = renderListStack[ renderListStack.length - 1 ]; + } - } else { + if ( material.alphaTest > 0 ) { - currentRenderList = null; + uniforms.alphaTest.value = material.alphaTest; } - }; + const envMap = properties.get( material ).envMap; - function projectObject( object, camera, groupOrder, sortObjects ) { + if ( envMap ) { - if ( object.visible === false ) return; + uniforms.envMap.value = envMap; - const visible = object.layers.test( camera.layers ); + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; - if ( visible ) { + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; - if ( object.isGroup ) { + } - groupOrder = object.renderOrder; + if ( material.lightMap ) { - } else if ( object.isLOD ) { + uniforms.lightMap.value = material.lightMap; - if ( object.autoUpdate === true ) object.update( camera ); + // artist-friendly light intensity scaling factor + const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1; - } else if ( object.isLight ) { + uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; - currentRenderState.pushLight( object ); + } - if ( object.castShadow ) { + if ( material.aoMap ) { - currentRenderState.pushShadow( object ); + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; - } + } - } else if ( object.isSprite ) { + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. displacementMap map + // 4. normal map + // 5. bump map + // 6. roughnessMap map + // 7. metalnessMap map + // 8. alphaMap map + // 9. emissiveMap map + // 10. clearcoat map + // 11. clearcoat normal map + // 12. clearcoat roughnessMap map + // 13. iridescence map + // 14. iridescence thickness map + // 15. specular intensity map + // 16. specular tint map + // 17. transmission map + // 18. thickness map - if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + let uvScaleMap; - if ( sortObjects ) { + if ( material.map ) { - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + uvScaleMap = material.map; - } + } else if ( material.specularMap ) { - const geometry = objects.update( object ); - const material = object.material; + uvScaleMap = material.specularMap; - if ( material.visible ) { + } else if ( material.displacementMap ) { - currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + uvScaleMap = material.displacementMap; - } + } else if ( material.normalMap ) { - } + uvScaleMap = material.normalMap; + + } else if ( material.bumpMap ) { + + uvScaleMap = material.bumpMap; - } else if ( object.isImmediateRenderObject ) { + } else if ( material.roughnessMap ) { - if ( sortObjects ) { + uvScaleMap = material.roughnessMap; - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + } else if ( material.metalnessMap ) { - } + uvScaleMap = material.metalnessMap; - currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null ); + } else if ( material.alphaMap ) { - } else if ( object.isMesh || object.isLine || object.isPoints ) { + uvScaleMap = material.alphaMap; - if ( object.isSkinnedMesh ) { + } else if ( material.emissiveMap ) { - // update skeleton only once in a frame + uvScaleMap = material.emissiveMap; - if ( object.skeleton.frame !== info.render.frame ) { + } else if ( material.clearcoatMap ) { - object.skeleton.update(); - object.skeleton.frame = info.render.frame; + uvScaleMap = material.clearcoatMap; - } + } else if ( material.clearcoatNormalMap ) { - } + uvScaleMap = material.clearcoatNormalMap; - if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + } else if ( material.clearcoatRoughnessMap ) { - if ( sortObjects ) { + uvScaleMap = material.clearcoatRoughnessMap; - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + } else if ( material.iridescenceMap ) { - } + uvScaleMap = material.iridescenceMap; - const geometry = objects.update( object ); - const material = object.material; + } else if ( material.iridescenceThicknessMap ) { - if ( Array.isArray( material ) ) { + uvScaleMap = material.iridescenceThicknessMap; - const groups = geometry.groups; + } else if ( material.specularIntensityMap ) { - for ( let i = 0, l = groups.length; i < l; i ++ ) { + uvScaleMap = material.specularIntensityMap; - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + } else if ( material.specularColorMap ) { - if ( groupMaterial && groupMaterial.visible ) { + uvScaleMap = material.specularColorMap; - currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); + } else if ( material.transmissionMap ) { - } + uvScaleMap = material.transmissionMap; - } + } else if ( material.thicknessMap ) { - } else if ( material.visible ) { + uvScaleMap = material.thicknessMap; - currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + } else if ( material.sheenColorMap ) { - } + uvScaleMap = material.sheenColorMap; - } + } else if ( material.sheenRoughnessMap ) { - } + uvScaleMap = material.sheenRoughnessMap; } - const children = object.children; + if ( uvScaleMap !== undefined ) { - for ( let i = 0, l = children.length; i < l; i ++ ) { + // backwards compatibility + if ( uvScaleMap.isWebGLRenderTarget ) { - projectObject( children[ i ], camera, groupOrder, sortObjects ); + uvScaleMap = uvScaleMap.texture; - } + } - } + if ( uvScaleMap.matrixAutoUpdate === true ) { - function renderObjects( renderList, scene, camera ) { + uvScaleMap.updateMatrix(); - const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + } - for ( let i = 0, l = renderList.length; i < l; i ++ ) { + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - const renderItem = renderList[ i ]; + } - const object = renderItem.object; - const geometry = renderItem.geometry; - const material = overrideMaterial === null ? renderItem.material : overrideMaterial; - const group = renderItem.group; + // uv repeat and offset setting priorities for uv2 + // 1. ao map + // 2. light map - if ( camera.isArrayCamera ) { + let uv2ScaleMap; - const cameras = camera.cameras; + if ( material.aoMap ) { - for ( let j = 0, jl = cameras.length; j < jl; j ++ ) { + uv2ScaleMap = material.aoMap; - const camera2 = cameras[ j ]; + } else if ( material.lightMap ) { - if ( object.layers.test( camera2.layers ) ) { + uv2ScaleMap = material.lightMap; - state.viewport( _currentViewport.copy( camera2.viewport ) ); + } - currentRenderState.setupLightsView( camera2 ); + if ( uv2ScaleMap !== undefined ) { - renderObject( object, scene, camera2, geometry, material, group ); + // backwards compatibility + if ( uv2ScaleMap.isWebGLRenderTarget ) { - } + uv2ScaleMap = uv2ScaleMap.texture; - } + } - } else { + if ( uv2ScaleMap.matrixAutoUpdate === true ) { - renderObject( object, scene, camera, geometry, material, group ); + uv2ScaleMap.updateMatrix(); } + uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + } } - function renderObject( object, scene, camera, geometry, material, group ) { + function refreshUniformsLine( uniforms, material ) { - object.onBeforeRender( _this, scene, camera, geometry, material, group ); + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + } - if ( object.isImmediateRenderObject ) { + function refreshUniformsDash( uniforms, material ) { - const program = setProgram( camera, scene, material, object ); + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - state.setMaterial( material ); + } - bindingStates.reset(); + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { - renderObjectImmediate( object, program ); + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; - } else { + if ( material.map ) { - _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + uniforms.map.value = material.map; } - object.onAfterRender( _this, scene, camera, geometry, material, group ); + if ( material.alphaMap ) { - } + uniforms.alphaMap.value = material.alphaMap; - function initMaterial( material, scene, object ) { + } - if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + if ( material.alphaTest > 0 ) { - const materialProperties = properties.get( material ); + uniforms.alphaTest.value = material.alphaTest; - const lights = currentRenderState.state.lights; - const shadowsArray = currentRenderState.state.shadowsArray; + } - const lightsStateVersion = lights.state.version; + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map - const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); - const programCacheKey = programCache.getProgramCacheKey( parameters ); + let uvScaleMap; - let program = materialProperties.program; - let programChange = true; + if ( material.map ) { - // always update environment and fog - changing these trigger an initMaterial call, but it's possible that the program doesn't change + uvScaleMap = material.map; - materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; - materialProperties.fog = scene.fog; - materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment ); + } else if ( material.alphaMap ) { - if ( program === undefined ) { + uvScaleMap = material.alphaMap; - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + } - } else if ( program.cacheKey !== programCacheKey ) { + if ( uvScaleMap !== undefined ) { - // changed glsl or parameters - releaseMaterialProgramReference( material ); + if ( uvScaleMap.matrixAutoUpdate === true ) { - } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) { + uvScaleMap.updateMatrix(); - programChange = false; + } - } else if ( parameters.shaderID !== undefined ) { + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - // same glsl and uniform list - return; + } - } else { + } - // only rebuild uniform list - programChange = false; + function refreshUniformsSprites( uniforms, material ) { - } + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; - if ( programChange ) { + if ( material.map ) { - parameters.uniforms = programCache.getUniforms( material ); + uniforms.map.value = material.map; - material.onBeforeCompile( parameters, _this ); + } - program = programCache.acquireProgram( parameters, programCacheKey ); + if ( material.alphaMap ) { - materialProperties.program = program; - materialProperties.uniforms = parameters.uniforms; - materialProperties.outputEncoding = parameters.outputEncoding; + uniforms.alphaMap.value = material.alphaMap; } - const uniforms = materialProperties.uniforms; - - if ( ! material.isShaderMaterial && - ! material.isRawShaderMaterial || - material.clipping === true ) { + if ( material.alphaTest > 0 ) { - materialProperties.numClippingPlanes = clipping.numPlanes; - materialProperties.numIntersection = clipping.numIntersection; - uniforms.clippingPlanes = clipping.uniform; + uniforms.alphaTest.value = material.alphaTest; } - // store the light setup it was created for + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map - materialProperties.needsLights = materialNeedsLights( material ); - materialProperties.lightsStateVersion = lightsStateVersion; + let uvScaleMap; - if ( materialProperties.needsLights ) { + if ( material.map ) { - // wire up the material to this renderer's lighting state + uvScaleMap = material.map; - uniforms.ambientLightColor.value = lights.state.ambient; - uniforms.lightProbe.value = lights.state.probe; - uniforms.directionalLights.value = lights.state.directional; - uniforms.directionalLightShadows.value = lights.state.directionalShadow; - uniforms.spotLights.value = lights.state.spot; - uniforms.spotLightShadows.value = lights.state.spotShadow; - uniforms.rectAreaLights.value = lights.state.rectArea; - uniforms.ltc_1.value = lights.state.rectAreaLTC1; - uniforms.ltc_2.value = lights.state.rectAreaLTC2; - uniforms.pointLights.value = lights.state.point; - uniforms.pointLightShadows.value = lights.state.pointShadow; - uniforms.hemisphereLights.value = lights.state.hemi; + } else if ( material.alphaMap ) { - uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; - uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; - uniforms.spotShadowMap.value = lights.state.spotShadowMap; - uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix; - uniforms.pointShadowMap.value = lights.state.pointShadowMap; - uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; - // TODO (abelnation): add area lights shadow info to uniforms + uvScaleMap = material.alphaMap; } - const progUniforms = materialProperties.program.getUniforms(); - const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + if ( uvScaleMap !== undefined ) { - materialProperties.uniformsList = uniformsList; + if ( uvScaleMap.matrixAutoUpdate === true ) { - } + uvScaleMap.updateMatrix(); - function setProgram( camera, scene, material, object ) { + } - if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - textures.resetTextureUnits(); + } - const fog = scene.fog; - const environment = material.isMeshStandardMaterial ? scene.environment : null; - const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding; - const envMap = cubemaps.get( material.envMap || environment ); + } - const materialProperties = properties.get( material ); - const lights = currentRenderState.state.lights; + function refreshUniformsPhong( uniforms, material ) { - if ( _clippingEnabled === true ) { + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - if ( _localClippingEnabled === true || camera !== _currentCamera ) { + } - const useCache = - camera === _currentCamera && - material.id === _currentMaterialId; + function refreshUniformsToon( uniforms, material ) { - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - clipping.setState( material, camera, useCache ); + if ( material.gradientMap ) { - } + uniforms.gradientMap.value = material.gradientMap; } - if ( material.version === materialProperties.__version ) { + } - if ( material.fog && materialProperties.fog !== fog ) { + function refreshUniformsStandard( uniforms, material ) { - initMaterial( material, scene, object ); + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; - } else if ( materialProperties.environment !== environment ) { + if ( material.roughnessMap ) { - initMaterial( material, scene, object ); + uniforms.roughnessMap.value = material.roughnessMap; - } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + } - initMaterial( material, scene, object ); + if ( material.metalnessMap ) { - } else if ( materialProperties.numClippingPlanes !== undefined && - ( materialProperties.numClippingPlanes !== clipping.numPlanes || - materialProperties.numIntersection !== clipping.numIntersection ) ) { + uniforms.metalnessMap.value = material.metalnessMap; - initMaterial( material, scene, object ); + } - } else if ( materialProperties.outputEncoding !== encoding ) { + const envMap = properties.get( material ).envMap; - initMaterial( material, scene, object ); + if ( envMap ) { - } else if ( materialProperties.envMap !== envMap ) { + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - initMaterial( material, scene, object ); + } - } + } - } else { + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { - initMaterial( material, scene, object ); - materialProperties.__version = material.version; + uniforms.ior.value = material.ior; // also part of uniforms common - } + if ( material.sheen > 0 ) { - let refreshProgram = false; - let refreshMaterial = false; - let refreshLights = false; + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); - const program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.uniforms; + uniforms.sheenRoughness.value = material.sheenRoughness; - if ( state.useProgram( program.program ) ) { + if ( material.sheenColorMap ) { - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + uniforms.sheenColorMap.value = material.sheenColorMap; - } + } - if ( material.id !== _currentMaterialId ) { + if ( material.sheenRoughnessMap ) { - _currentMaterialId = material.id; + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; - refreshMaterial = true; + } } - if ( refreshProgram || _currentCamera !== camera ) { + if ( material.clearcoat > 0 ) { - p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; - if ( capabilities.logarithmicDepthBuffer ) { + if ( material.clearcoatMap ) { - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + uniforms.clearcoatMap.value = material.clearcoatMap; } - if ( _currentCamera !== camera ) { - - _currentCamera = camera; - - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + if ( material.clearcoatRoughnessMap ) { - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; } - // load material specific uniforms - // (shader material also gets them for the sake of genericity) - - if ( material.isShaderMaterial || - material.isMeshPhongMaterial || - material.isMeshToonMaterial || - material.isMeshStandardMaterial || - material.envMap ) { + if ( material.clearcoatNormalMap ) { - const uCamPos = p_uniforms.map.cameraPosition; + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; - if ( uCamPos !== undefined ) { + if ( material.side === BackSide ) { - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + uniforms.clearcoatNormalScale.value.negate(); } } - if ( material.isMeshPhongMaterial || - material.isMeshToonMaterial || - material.isMeshLambertMaterial || - material.isMeshBasicMaterial || - material.isMeshStandardMaterial || - material.isShaderMaterial ) { + } - p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + if ( material.iridescence > 0 ) { - } + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; - if ( material.isMeshPhongMaterial || - material.isMeshToonMaterial || - material.isMeshLambertMaterial || - material.isMeshBasicMaterial || - material.isMeshStandardMaterial || - material.isShaderMaterial || - material.isShadowMaterial || - material.skinning ) { + if ( material.iridescenceMap ) { - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + uniforms.iridescenceMap.value = material.iridescenceMap; } - } - - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // otherwise textures used for skinning can take over texture units reserved for other material textures - - if ( material.skinning ) { - - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + if ( material.iridescenceThicknessMap ) { - const skeleton = object.skeleton; + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; - if ( skeleton ) { + } - const bones = skeleton.bones; + } - if ( capabilities.floatVertexTextures ) { + if ( material.transmission > 0 ) { - if ( skeleton.boneTexture === null ) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); - // 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 ( material.transmissionMap ) { + uniforms.transmissionMap.value = material.transmissionMap; - let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix - size = MathUtils.ceilPowerOfTwo( size ); - size = Math.max( size, 4 ); + } - const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel - boneMatrices.set( skeleton.boneMatrices ); // copy current values + uniforms.thickness.value = material.thickness; - const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + if ( material.thicknessMap ) { - skeleton.boneMatrices = boneMatrices; - skeleton.boneTexture = boneTexture; - skeleton.boneTextureSize = size; + uniforms.thicknessMap.value = material.thicknessMap; - } + } - p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); - p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); - } else { + } - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); - } + if ( material.specularIntensityMap ) { - } + uniforms.specularIntensityMap.value = material.specularIntensityMap; } - if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + if ( material.specularColorMap ) { - materialProperties.receiveShadow = object.receiveShadow; - p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + uniforms.specularColorMap.value = material.specularColorMap; } - if ( refreshMaterial ) { + } - p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + function refreshUniformsMatcap( uniforms, material ) { - if ( materialProperties.needsLights ) { + if ( material.matcap ) { - // the current material requires lighting info + uniforms.matcap.value = material.matcap; - // 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 + } - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + } - } + function refreshUniformsDistance( uniforms, material ) { - // refresh uniforms common to several materials + uniforms.referencePosition.value.copy( material.referencePosition ); + uniforms.nearDistance.value = material.nearDistance; + uniforms.farDistance.value = material.farDistance; - if ( fog && material.fog ) { + } - materials.refreshFogUniforms( m_uniforms, fog ); + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; - } +} - materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height ); +function WebGLUniformsGroups( gl, info, capabilities, state ) { - WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; - } + const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program - if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + function bind( uniformsGroup, program ) { - WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); - material.uniformsNeedUpdate = false; + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); - } + } - if ( material.isSpriteMaterial ) { + function update( uniformsGroup, program ) { - p_uniforms.setValue( _gl, 'center', object.center ); + let buffer = buffers[ uniformsGroup.id ]; - } + if ( buffer === undefined ) { - // common matrices + prepareUniformsGroup( uniformsGroup ); - p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); - p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; - return program; + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); - } + } - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + // ensure to update the binding points/block indices mapping for this program - function markUniformsLightsNeedsUpdate( uniforms, value ) { + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); - uniforms.ambientLightColor.needsUpdate = value; - uniforms.lightProbe.needsUpdate = value; + // update UBO once per frame - uniforms.directionalLights.needsUpdate = value; - uniforms.directionalLightShadows.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.pointLightShadows.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.spotLightShadows.needsUpdate = value; - uniforms.rectAreaLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + const frame = info.render.frame; - } + if ( updateList[ uniformsGroup.id ] !== frame ) { - function materialNeedsLights( material ) { + updateBufferData( uniformsGroup ); - return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || - material.isMeshStandardMaterial || material.isShadowMaterial || - ( material.isShaderMaterial && material.lights === true ); + updateList[ uniformsGroup.id ] = frame; + + } } - // - this.setFramebuffer = function ( value ) { + function createBuffer( uniformsGroup ) { - if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value ); + // the setup of an UBO is independent of a particular shader program but global - _framebuffer = value; + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; - }; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; - this.getActiveCubeFace = function () { + gl.bindBuffer( 35345, buffer ); + gl.bufferData( 35345, size, usage ); + gl.bindBuffer( 35345, null ); + gl.bindBufferBase( 35345, bindingPointIndex, buffer ); - return _currentActiveCubeFace; + return buffer; - }; + } - this.getActiveMipmapLevel = function () { + function allocateBindingPointIndex() { - return _currentActiveMipmapLevel; + for ( let i = 0; i < maxBindingPoints; i ++ ) { - }; + if ( allocatedBindingPoints.indexOf( i ) === - 1 ) { - this.getRenderTarget = function () { + allocatedBindingPoints.push( i ); + return i; - return _currentRenderTarget; + } - }; + } - this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); - _currentRenderTarget = renderTarget; - _currentActiveCubeFace = activeCubeFace; - _currentActiveMipmapLevel = activeMipmapLevel; + return 0; - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + } - textures.setupRenderTarget( renderTarget ); + function updateBufferData( uniformsGroup ) { - } + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; - let framebuffer = _framebuffer; - let isCube = false; - let isRenderTarget3D = false; + gl.bindBuffer( 35345, buffer ); - if ( renderTarget ) { + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { - const texture = renderTarget.texture; + const uniform = uniforms[ i ]; - if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) { + // partly update the buffer if necessary - isRenderTarget3D = true; + if ( hasUniformChanged( uniform, i, cache ) === true ) { - } + const value = uniform.value; + const offset = uniform.__offset; - const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( typeof value === 'number' ) { - if ( renderTarget.isWebGLCubeRenderTarget ) { + uniform.__data[ 0 ] = value; + gl.bufferSubData( 35345, offset, uniform.__data ); - framebuffer = __webglFramebuffer[ activeCubeFace ]; - isCube = true; + } else { - } else if ( renderTarget.isWebGLMultisampleRenderTarget ) { + if ( uniform.value.isMatrix3 ) { - framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + // manually converting 3x3 to 3x4 - } else { + uniform.__data[ 0 ] = uniform.value.elements[ 0 ]; + uniform.__data[ 1 ] = uniform.value.elements[ 1 ]; + uniform.__data[ 2 ] = uniform.value.elements[ 2 ]; + uniform.__data[ 3 ] = uniform.value.elements[ 0 ]; + uniform.__data[ 4 ] = uniform.value.elements[ 3 ]; + uniform.__data[ 5 ] = uniform.value.elements[ 4 ]; + uniform.__data[ 6 ] = uniform.value.elements[ 5 ]; + uniform.__data[ 7 ] = uniform.value.elements[ 0 ]; + uniform.__data[ 8 ] = uniform.value.elements[ 6 ]; + uniform.__data[ 9 ] = uniform.value.elements[ 7 ]; + uniform.__data[ 10 ] = uniform.value.elements[ 8 ]; + uniform.__data[ 11 ] = uniform.value.elements[ 0 ]; - framebuffer = __webglFramebuffer; + } else { - } + value.toArray( uniform.__data ); - _currentViewport.copy( renderTarget.viewport ); - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + } - } else { + gl.bufferSubData( 35345, offset, uniform.__data ); - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); - _currentScissorTest = _scissorTest; + } + + } } - if ( _currentFramebuffer !== framebuffer ) { + gl.bindBuffer( 35345, null ); - _gl.bindFramebuffer( 36160, framebuffer ); - _currentFramebuffer = framebuffer; + } - } + function hasUniformChanged( uniform, index, cache ) { - state.viewport( _currentViewport ); - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + const value = uniform.value; - if ( isCube ) { + if ( cache[ index ] === undefined ) { - const textureProperties = properties.get( renderTarget.texture ); - _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + // cache entry does not exist so far - } else if ( isRenderTarget3D ) { + if ( typeof value === 'number' ) { - const textureProperties = properties.get( renderTarget.texture ); - const layer = activeCubeFace || 0; - _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); + cache[ index ] = value; - } + } else { - }; + cache[ index ] = value.clone(); - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + } - if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + return true; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + } else { - } + // compare current value with cached entry - let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( typeof value === 'number' ) { - if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + if ( cache[ index ] !== value ) { - framebuffer = framebuffer[ activeCubeFaceIndex ]; + cache[ index ] = value; + return true; - } + } - if ( framebuffer ) { + } else { - let restore = false; + const cachedObject = cache[ index ]; - if ( framebuffer !== _currentFramebuffer ) { + if ( cachedObject.equals( value ) === false ) { - _gl.bindFramebuffer( 36160, framebuffer ); + cachedObject.copy( value ); + return true; - restore = true; + } } - try { - - const texture = renderTarget.texture; - const textureFormat = texture.format; - const textureType = texture.type; + } - if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { + return false; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + } - } + function prepareUniformsGroup( uniformsGroup ) { - const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 - if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513) - ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox - ! halfFloatSupportedByExt ) { + const uniforms = uniformsGroup.uniforms; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + let chunkOffset = 0; // offset within a single chunk in bytes - } + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { - if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) { + const uniform = uniforms[ i ]; + const info = getUniformSize( uniform ); - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + // the following two properties will be used for partial buffer updates - if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; - _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + // - } + if ( i > 0 ) { - } else { + chunkOffset = offset % chunkSize; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + const remainingSizeInChunk = chunkSize - chunkOffset; - } + // check for chunk overflow - } finally { + if ( chunkOffset !== 0 && ( remainingSizeInChunk - info.boundary ) < 0 ) { - if ( restore ) { + // add padding and adjust offset - _gl.bindFramebuffer( 36160, _currentFramebuffer ); + offset += ( chunkSize - chunkOffset ); + uniform.__offset = offset; } } - } + offset += info.storage; - }; + } - this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { + // ensure correct final padding - const levelScale = Math.pow( 2, - level ); - const width = Math.floor( texture.image.width * levelScale ); - const height = Math.floor( texture.image.height * levelScale ); - const glFormat = utils.convert( texture.format ); + chunkOffset = offset % chunkSize; - textures.setTexture2D( texture, 0 ); + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); - _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 ); + // - state.unbindTexture(); + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; - }; + return this; - this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { + } - const width = srcTexture.image.width; - const height = srcTexture.image.height; - const glFormat = utils.convert( dstTexture.format ); - const glType = utils.convert( dstTexture.type ); + function getUniformSize( uniform ) { - textures.setTexture2D( dstTexture, 0 ); + const value = uniform.value; - // As another texture upload may have changed pixelStorei - // parameters, make sure they are correct for the dstTexture - _gl.pixelStorei( 37440, dstTexture.flipY ); - _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); - _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; - if ( srcTexture.isDataTexture ) { + // determine sizes according to STD140 - _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); + if ( typeof value === 'number' ) { - } else { + // float/int - if ( srcTexture.isCompressedTexture ) { + info.boundary = 4; + info.storage = 4; - _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); + } else if ( value.isVector2 ) { - } else { + // vec2 - _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image ); + info.boundary = 8; + info.storage = 8; - } + } else if ( value.isVector3 || value.isColor ) { - } + // vec3 - // Generate mipmaps only when copying level 0 - if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 ); + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes - state.unbindTexture(); + } else if ( value.isVector4 ) { - }; + // vec4 - this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { + info.boundary = 16; + info.storage = 16; - if ( _this.isWebGL1Renderer ) { + } else if ( value.isMatrix3 ) { - console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); - return; + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) - } + info.boundary = 48; + info.storage = 48; - const { width, height, data } = srcTexture.image; - const glFormat = utils.convert( dstTexture.format ); - const glType = utils.convert( dstTexture.type ); - let glTarget; + } else if ( value.isMatrix4 ) { - if ( dstTexture.isDataTexture3D ) { + // mat4 - textures.setTexture3D( dstTexture, 0 ); - glTarget = 32879; + info.boundary = 64; + info.storage = 64; - } else if ( dstTexture.isDataTexture2DArray ) { + } else if ( value.isTexture ) { - textures.setTexture2DArray( dstTexture, 0 ); - glTarget = 35866; + console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); } else { - console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); - return; + console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value ); } - _gl.pixelStorei( 37440, dstTexture.flipY ); - _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); - _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); + return info; - const unpackRowLen = _gl.getParameter( 3314 ); - const unpackImageHeight = _gl.getParameter( 32878 ); - const unpackSkipPixels = _gl.getParameter( 3316 ); - const unpackSkipRows = _gl.getParameter( 3315 ); - const unpackSkipImages = _gl.getParameter( 32877 ); + } - _gl.pixelStorei( 3314, width ); - _gl.pixelStorei( 32878, height ); - _gl.pixelStorei( 3316, sourceBox.min.x ); - _gl.pixelStorei( 3315, sourceBox.min.y ); - _gl.pixelStorei( 32877, sourceBox.min.z ); + function onUniformsGroupsDispose( event ) { - _gl.texSubImage3D( - glTarget, - level, - position.x, - position.y, - position.z, - sourceBox.max.x - sourceBox.min.x + 1, - sourceBox.max.y - sourceBox.min.y + 1, - sourceBox.max.z - sourceBox.min.z + 1, - glFormat, - glType, - data - ); + const uniformsGroup = event.target; - _gl.pixelStorei( 3314, unpackRowLen ); - _gl.pixelStorei( 32878, unpackImageHeight ); - _gl.pixelStorei( 3316, unpackSkipPixels ); - _gl.pixelStorei( 3315, unpackSkipRows ); - _gl.pixelStorei( 32877, unpackSkipImages ); + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); - // Generate mipmaps only when copying level 0 - if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); - state.unbindTexture(); + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); - }; + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; - this.initTexture = function ( texture ) { + } - textures.setTexture2D( texture, 0 ); + function dispose() { - state.unbindTexture(); + for ( const id in buffers ) { - }; + gl.deleteBuffer( buffers[ id ] ); - this.resetState = function () { + } - state.reset(); - bindingStates.reset(); + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; - }; + } - if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + return { - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef + bind: bind, + update: update, - } + dispose: dispose + + }; } -class WebGL1Renderer extends WebGLRenderer {} +function createCanvasElement() { -WebGL1Renderer.prototype.isWebGL1Renderer = true; + const canvas = createElementNS( 'canvas' ); + canvas.style.display = 'block'; + return canvas; -class FogExp2 { +} - constructor( color, density ) { +function WebGLRenderer( parameters = {} ) { - this.name = ''; + this.isWebGLRenderer = true; - this.color = new Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), + _context = parameters.context !== undefined ? parameters.context : null, - } + _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, + _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', + _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; - clone() { + let _alpha; - return new FogExp2( this.color, this.density ); + if ( _context !== null ) { - } + _alpha = _context.getContextAttributes().alpha; - toJSON( /* meta */ ) { + } else { - return { - type: 'FogExp2', - color: this.color.getHex(), - density: this.density - }; + _alpha = parameters.alpha !== undefined ? parameters.alpha : false; } -} + let currentRenderList = null; + let currentRenderState = null; -FogExp2.prototype.isFogExp2 = true; + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. -class Fog { + const renderListStack = []; + const renderStateStack = []; - constructor( color, near, far ) { + // public properties - this.name = ''; + this.domElement = _canvas; - this.color = new Color( color ); + // Debug configuration container + this.debug = { - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true + }; - } + // clearing - clone() { + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - return new Fog( this.color, this.near, this.far ); + // scene graph - } + this.sortObjects = true; - toJSON( /* meta */ ) { + // user-defined clipping - return { - type: 'Fog', - color: this.color.getHex(), - near: this.near, - far: this.far - }; + this.clippingPlanes = []; + this.localClippingEnabled = false; - } + // physically based shading -} + this.outputEncoding = LinearEncoding; -Fog.prototype.isFog = true; + // physical lights -class Scene extends Object3D { + this.physicallyCorrectLights = false; - constructor() { + // tone mapping - super(); + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1.0; - this.type = 'Scene'; + // - this.background = null; - this.environment = null; - this.fog = null; + Object.defineProperties( this, { - this.overrideMaterial = null; + // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d - this.autoUpdate = true; // checked by the renderer + gammaFactor: { + get: function () { - if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + return 2; - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef + }, + set: function () { + + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + } } - } + } ); - copy( source, recursive ) { + // internal properties - super.copy( source, recursive ); + const _this = this; - if ( source.background !== null ) this.background = source.background.clone(); - if ( source.environment !== null ) this.environment = source.environment.clone(); - if ( source.fog !== null ) this.fog = source.fog.clone(); + let _isContextLost = false; - if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + // internal state cache - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = - 1; - return this; + let _currentCamera = null; - } + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; - toJSON( meta ) { + // - const data = super.toJSON( meta ); + let _width = _canvas.width; + let _height = _canvas.height; - if ( this.background !== null ) data.object.background = this.background.toJSON( meta ); - if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta ); - if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; - return data; + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; - } + // frustum -} + const _frustum = new Frustum(); -Scene.prototype.isScene = true; + // clipping -function InterleavedBuffer( array, stride ) { + let _clippingEnabled = false; + let _localClippingEnabled = false; - this.array = array; - this.stride = stride; - this.count = array !== undefined ? array.length / stride : 0; + // transmission - this.usage = StaticDrawUsage; - this.updateRange = { offset: 0, count: - 1 }; + let _transmissionRenderTarget = null; - this.version = 0; + // camera matrices cache - this.uuid = MathUtils.generateUUID(); + const _projScreenMatrix = new Matrix4(); -} + const _vector2 = new Vector2(); + const _vector3 = new Vector3(); -Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', { + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; - set: function ( value ) { + function getTargetPixelRatio() { - if ( value === true ) this.version ++; + return _currentRenderTarget === null ? _pixelRatio : 1; } -} ); - -Object.assign( InterleavedBuffer.prototype, { + // initialize - isInterleavedBuffer: true, + let _gl = _context; - onUploadCallback: function () {}, + function getContext( contextNames, contextAttributes ) { - setUsage: function ( value ) { + for ( let i = 0; i < contextNames.length; i ++ ) { - this.usage = value; + const contextName = contextNames[ i ]; + const context = _canvas.getContext( contextName, contextAttributes ); + if ( context !== null ) return context; - return this; + } - }, + return null; - copy: function ( source ) { + } - this.array = new source.array.constructor( source.array ); - this.count = source.count; - this.stride = source.stride; - this.usage = source.usage; + try { - return this; + const contextAttributes = { + alpha: true, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer, + powerPreference: _powerPreference, + failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat + }; - }, + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); - copyAt: function ( index1, attribute, index2 ) { + // event listeners must be registered before WebGL context is created, see #12753 + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); - index1 *= this.stride; - index2 *= attribute.stride; + if ( _gl === null ) { - for ( let i = 0, l = this.stride; i < l; i ++ ) { + const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + if ( _this.isWebGL1Renderer === true ) { - } + contextNames.shift(); - return this; + } - }, + _gl = getContext( contextNames, contextAttributes ); - set: function ( value, offset = 0 ) { + if ( _gl === null ) { - this.array.set( value, offset ); + if ( getContext( contextNames ) ) { - return this; + throw new Error( 'Error creating WebGL context with your selected attributes.' ); - }, + } else { - clone: function ( data ) { + throw new Error( 'Error creating WebGL context.' ); - if ( data.arrayBuffers === undefined ) { + } - data.arrayBuffers = {}; + } } - if ( this.array.buffer._uuid === undefined ) { + // Some experimental-webgl implementations do not have getShaderPrecisionFormat + + if ( _gl.getShaderPrecisionFormat === undefined ) { + + _gl.getShaderPrecisionFormat = function () { + + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - this.array.buffer._uuid = MathUtils.generateUUID(); + }; } - if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + } catch ( error ) { - data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; + + } + + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - } + extensions.init( capabilities ); - const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); + utils = new WebGLUtils( _gl, extensions, capabilities ); - const ib = new InterleavedBuffer( array, this.stride ); - ib.setUsage( this.usage ); + state = new WebGLState( _gl, extensions, capabilities ); - return ib; + info = new WebGLInfo(); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + cubemaps = new WebGLCubeMaps( _this ); + cubeuvmaps = new WebGLCubeUVMaps( _this ); + attributes = new WebGLAttributes( _gl, capabilities ); + bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions, capabilities ); + background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); - }, + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); - onUpload: function ( callback ) { + info.programs = programCache.programs; - this.onUploadCallback = callback; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; - return this; + } - }, + initGLContext(); - toJSON: function ( data ) { + // xr - if ( data.arrayBuffers === undefined ) { + const xr = new WebXRManager( _this, _gl ); - data.arrayBuffers = {}; + this.xr = xr; - } + // API - // generate UUID for array buffer if necessary + this.getContext = function () { - if ( this.array.buffer._uuid === undefined ) { + return _gl; - this.array.buffer._uuid = MathUtils.generateUUID(); + }; - } + this.getContextAttributes = function () { - if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + return _gl.getContextAttributes(); - data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) ); + }; - } + this.forceContextLoss = function () { - // + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); - return { - uuid: this.uuid, - buffer: this.array.buffer._uuid, - type: this.array.constructor.name, - stride: this.stride - }; + }; - } + this.forceContextRestore = function () { -} ); + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); -const _vector$6 = new Vector3(); + }; -function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { + this.getPixelRatio = function () { - this.name = ''; + return _pixelRatio; - this.data = interleavedBuffer; - this.itemSize = itemSize; - this.offset = offset; + }; - this.normalized = normalized === true; + this.setPixelRatio = function ( value ) { -} + if ( value === undefined ) return; -Object.defineProperties( InterleavedBufferAttribute.prototype, { + _pixelRatio = value; - count: { + this.setSize( _width, _height, false ); - get: function () { + }; - return this.data.count; + this.getSize = function ( target ) { - } + return target.set( _width, _height ); - }, + }; - array: { + this.setSize = function ( width, height, updateStyle ) { - get: function () { + if ( xr.isPresenting ) { - return this.data.array; + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; } - }, + _width = width; + _height = height; - needsUpdate: { + _canvas.width = Math.floor( width * _pixelRatio ); + _canvas.height = Math.floor( height * _pixelRatio ); - set: function ( value ) { + if ( updateStyle !== false ) { - this.data.needsUpdate = value; + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; } - } + this.setViewport( 0, 0, width, height ); -} ); + }; -Object.assign( InterleavedBufferAttribute.prototype, { + this.getDrawingBufferSize = function ( target ) { - isInterleavedBufferAttribute: true, + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); - applyMatrix4: function ( m ) { + }; - for ( let i = 0, l = this.data.count; i < l; i ++ ) { + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { - _vector$6.x = this.getX( i ); - _vector$6.y = this.getY( i ); - _vector$6.z = this.getZ( i ); + _width = width; + _height = height; - _vector$6.applyMatrix4( m ); + _pixelRatio = pixelRatio; - this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + _canvas.width = Math.floor( width * pixelRatio ); + _canvas.height = Math.floor( height * pixelRatio ); - } + this.setViewport( 0, 0, width, height ); - return this; + }; - }, + this.getCurrentViewport = function ( target ) { - setX: function ( index, x ) { + return target.copy( _currentViewport ); - this.data.array[ index * this.data.stride + this.offset ] = x; + }; - return this; + this.getViewport = function ( target ) { - }, + return target.copy( _viewport ); - setY: function ( index, y ) { + }; - this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + this.setViewport = function ( x, y, width, height ) { - return this; + if ( x.isVector4 ) { - }, + _viewport.set( x.x, x.y, x.z, x.w ); - setZ: function ( index, z ) { + } else { - this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + _viewport.set( x, y, width, height ); - return this; + } - }, + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); - setW: function ( index, w ) { + }; - this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + this.getScissor = function ( target ) { - return this; + return target.copy( _scissor ); - }, + }; - getX: function ( index ) { + this.setScissor = function ( x, y, width, height ) { - return this.data.array[ index * this.data.stride + this.offset ]; + if ( x.isVector4 ) { - }, + _scissor.set( x.x, x.y, x.z, x.w ); - getY: function ( index ) { + } else { - return this.data.array[ index * this.data.stride + this.offset + 1 ]; + _scissor.set( x, y, width, height ); - }, + } - getZ: function ( index ) { + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); - return this.data.array[ index * this.data.stride + this.offset + 2 ]; + }; - }, + this.getScissorTest = function () { - getW: function ( index ) { + return _scissorTest; - return this.data.array[ index * this.data.stride + this.offset + 3 ]; + }; - }, + this.setScissorTest = function ( boolean ) { - setXY: function ( index, x, y ) { + state.setScissorTest( _scissorTest = boolean ); - index = index * this.data.stride + this.offset; + }; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; + this.setOpaqueSort = function ( method ) { - return this; + _opaqueSort = method; - }, + }; - setXYZ: function ( index, x, y, z ) { + this.setTransparentSort = function ( method ) { - index = index * this.data.stride + this.offset; + _transparentSort = method; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; + }; - return this; + // Clearing - }, + this.getClearColor = function ( target ) { - setXYZW: function ( index, x, y, z, w ) { + return target.copy( background.getClearColor() ); - 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; - this.data.array[ index + 3 ] = w; + this.setClearColor = function () { - return this; + background.setClearColor.apply( background, arguments ); - }, + }; - clone: function ( data ) { + this.getClearAlpha = function () { - if ( data === undefined ) { + return background.getClearAlpha(); - console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' ); + }; - const array = []; + this.setClearAlpha = function () { - for ( let i = 0; i < this.count; i ++ ) { + background.setClearAlpha.apply( background, arguments ); - const index = i * this.data.stride + this.offset; + }; - for ( let j = 0; j < this.itemSize; j ++ ) { + this.clear = function ( color = true, depth = true, stencil = true ) { - array.push( this.data.array[ index + j ] ); + let bits = 0; - } + if ( color ) bits |= 16384; + if ( depth ) bits |= 256; + if ( stencil ) bits |= 1024; - } + _gl.clear( bits ); - return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); + }; - } else { + this.clearColor = function () { - if ( data.interleavedBuffers === undefined ) { + this.clear( true, false, false ); - data.interleavedBuffers = {}; + }; - } + this.clearDepth = function () { - if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + this.clear( false, true, false ); - data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); + }; - } + this.clearStencil = function () { - return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); + this.clear( false, false, true ); - } + }; - }, + // - toJSON: function ( data ) { + this.dispose = function () { - if ( data === undefined ) { + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); - console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' ); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); - const array = []; + xr.dispose(); - for ( let i = 0; i < this.count; i ++ ) { + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); - const index = i * this.data.stride + this.offset; + if ( _transmissionRenderTarget ) { - for ( let j = 0; j < this.itemSize; j ++ ) { + _transmissionRenderTarget.dispose(); + _transmissionRenderTarget = null; - array.push( this.data.array[ index + j ] ); + } - } + animation.stop(); - } + }; - // deinterleave data and save it as an ordinary buffer attribute for now + // Events - return { - itemSize: this.itemSize, - type: this.array.constructor.name, - array: array, - normalized: this.normalized - }; + function onContextLost( event ) { - } else { + event.preventDefault(); - // save as true interlaved attribtue + console.log( 'THREE.WebGLRenderer: Context Lost.' ); - if ( data.interleavedBuffers === undefined ) { + _isContextLost = true; - data.interleavedBuffers = {}; + } - } + function onContextRestore( /* event */ ) { - if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + console.log( 'THREE.WebGLRenderer: Context Restored.' ); - data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); + _isContextLost = false; - } + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; - return { - isInterleavedBufferAttribute: true, - itemSize: this.itemSize, - data: this.data.uuid, - offset: this.offset, - normalized: this.normalized - }; + initGLContext(); - } + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; } -} ); + function onContextCreationError( event ) { -/** - * parameters = { - * color: , - * map: new THREE.Texture( ), - * alphaMap: new THREE.Texture( ), - * rotation: , - * sizeAttenuation: - * } - */ + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); -class SpriteMaterial extends Material { - - constructor( parameters ) { + } - super(); + function onMaterialDispose( event ) { - this.type = 'SpriteMaterial'; + const material = event.target; - this.color = new Color( 0xffffff ); + material.removeEventListener( 'dispose', onMaterialDispose ); - this.map = null; + deallocateMaterial( material ); - this.alphaMap = null; + } - this.rotation = 0; + // Buffer deallocation - this.sizeAttenuation = true; + function deallocateMaterial( material ) { - this.transparent = true; + releaseMaterialProgramReferences( material ); - this.setValues( parameters ); + properties.remove( material ); } - copy( source ) { - super.copy( source ); + function releaseMaterialProgramReferences( material ) { - this.color.copy( source.color ); + const programs = properties.get( material ).programs; - this.map = source.map; + if ( programs !== undefined ) { - this.alphaMap = source.alphaMap; + programs.forEach( function ( program ) { - this.rotation = source.rotation; + programCache.releaseProgram( program ); - this.sizeAttenuation = source.sizeAttenuation; + } ); - return this; + if ( material.isShaderMaterial ) { - } + programCache.releaseShaderCache( material ); -} + } -SpriteMaterial.prototype.isSpriteMaterial = true; + } -let _geometry; + } -const _intersectPoint = /*@__PURE__*/ new Vector3(); -const _worldScale = /*@__PURE__*/ new Vector3(); -const _mvPosition = /*@__PURE__*/ new Vector3(); + // Buffer rendering -const _alignedPosition = /*@__PURE__*/ new Vector2(); -const _rotatedPosition = /*@__PURE__*/ new Vector2(); -const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { -const _vA$1 = /*@__PURE__*/ new Vector3(); -const _vB$1 = /*@__PURE__*/ new Vector3(); -const _vC$1 = /*@__PURE__*/ new Vector3(); + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) -const _uvA$1 = /*@__PURE__*/ new Vector2(); -const _uvB$1 = /*@__PURE__*/ new Vector2(); -const _uvC$1 = /*@__PURE__*/ new Vector2(); + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); -class Sprite extends Object3D { + const program = setProgram( camera, scene, geometry, material, object ); - constructor( material ) { + state.setMaterial( material, frontFaceCW ); - super(); + // - this.type = 'Sprite'; + let index = geometry.index; + const position = geometry.attributes.position; - if ( _geometry === undefined ) { + // - _geometry = new BufferGeometry(); + if ( index === null ) { - const float32Array = new Float32Array( [ - - 0.5, - 0.5, 0, 0, 0, - 0.5, - 0.5, 0, 1, 0, - 0.5, 0.5, 0, 1, 1, - - 0.5, 0.5, 0, 0, 1 - ] ); + if ( position === undefined || position.count === 0 ) return; - const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); + } else if ( index.count === 0 ) { - _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); - _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); - _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); + return; } - this.geometry = _geometry; - this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - - this.center = new Vector2( 0.5, 0.5 ); - - } + // - raycast( raycaster, intersects ) { + let rangeFactor = 1; - if ( raycaster.camera === null ) { + if ( material.wireframe === true ) { - console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); + index = geometries.getWireframeAttribute( geometry ); + rangeFactor = 2; } - _worldScale.setFromMatrixScale( this.matrixWorld ); + bindingStates.setup( object, material, program, geometry, index ); - _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); - this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); + let attribute; + let renderer = bufferRenderer; - _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); + if ( index !== null ) { - if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + attribute = attributes.get( index ); - _worldScale.multiplyScalar( - _mvPosition.z ); + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); } - const rotation = this.material.rotation; - let sin, cos; + // - if ( rotation !== 0 ) { + const dataCount = ( index !== null ) ? index.count : position.count; - cos = Math.cos( rotation ); - sin = Math.sin( rotation ); + const rangeStart = geometry.drawRange.start * rangeFactor; + const rangeCount = geometry.drawRange.count * rangeFactor; - } + const groupStart = group !== null ? group.start * rangeFactor : 0; + const groupCount = group !== null ? group.count * rangeFactor : Infinity; - const center = this.center; + const drawStart = Math.max( rangeStart, groupStart ); + const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + const drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - _uvA$1.set( 0, 0 ); - _uvB$1.set( 1, 0 ); - _uvC$1.set( 1, 1 ); + if ( drawCount === 0 ) return; - // check first triangle - let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint ); + // - if ( intersect === null ) { + if ( object.isMesh ) { - // check second triangle - transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - _uvB$1.set( 0, 1 ); + if ( material.wireframe === true ) { - intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint ); - if ( intersect === null ) { + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( 1 ); - return; + } else { + + renderer.setMode( 4 ); } - } + } else if ( object.isLine ) { - const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); + let lineWidth = material.linewidth; - if ( distance < raycaster.near || distance > raycaster.far ) return; + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - intersects.push( { + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - distance: distance, - point: _intersectPoint.clone(), - uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ), - face: null, - object: this + if ( object.isLineSegments ) { - } ); + renderer.setMode( 1 ); - } + } else if ( object.isLineLoop ) { - copy( source ) { + renderer.setMode( 2 ); - super.copy( source ); + } else { - if ( source.center !== undefined ) this.center.copy( source.center ); + renderer.setMode( 3 ); - this.material = source.material; + } - return this; + } else if ( object.isPoints ) { - } + renderer.setMode( 0 ); -} + } else if ( object.isSprite ) { -Sprite.prototype.isSprite = true; + renderer.setMode( 4 ); -function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { + } - // compute position in camera space - _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); + if ( object.isInstancedMesh ) { - // to check if rotation is not zero - if ( sin !== undefined ) { + renderer.renderInstances( drawStart, drawCount, object.count ); - _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); - _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); + } else if ( geometry.isInstancedBufferGeometry ) { - } else { + const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount ); - _rotatedPosition.copy( _alignedPosition ); + renderer.renderInstances( drawStart, drawCount, instanceCount ); - } + } else { + renderer.render( drawStart, drawCount ); - vertexPosition.copy( mvPosition ); - vertexPosition.x += _rotatedPosition.x; - vertexPosition.y += _rotatedPosition.y; + } - // transform to world space - vertexPosition.applyMatrix4( _viewWorldMatrix ); + }; -} + // Compile -const _v1$4 = /*@__PURE__*/ new Vector3(); -const _v2$2 = /*@__PURE__*/ new Vector3(); + this.compile = function ( scene, camera ) { -class LOD extends Object3D { + function prepare( material, scene, object ) { - constructor() { + if ( material.transparent === true && material.side === DoubleSide ) { - super(); + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); - this._currentLevel = 0; + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); - this.type = 'LOD'; + material.side = DoubleSide; + + } else { + + getProgram( material, scene, object ); - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] - }, - isLOD: { - value: true, } - } ); - this.autoUpdate = true; + } - } + currentRenderState = renderStates.get( scene ); + currentRenderState.init(); - copy( source ) { + renderStateStack.push( currentRenderState ); - super.copy( source, false ); + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); - const levels = source.levels; + } - for ( let i = 0, l = levels.length; i < l; i ++ ) { + } - const level = levels[ i ]; + } ); - this.addLevel( level.object.clone(), level.distance ); + currentRenderState.setupLights( _this.physicallyCorrectLights ); - } + scene.traverse( function ( object ) { - this.autoUpdate = source.autoUpdate; + const material = object.material; - return this; + if ( material ) { - } + if ( Array.isArray( material ) ) { - addLevel( object, distance = 0 ) { + for ( let i = 0; i < material.length; i ++ ) { - distance = Math.abs( distance ); + const material2 = material[ i ]; - const levels = this.levels; + prepare( material2, scene, object ); - let l; + } - for ( l = 0; l < levels.length; l ++ ) { + } else { - if ( distance < levels[ l ].distance ) { + prepare( material, scene, object ); - break; + } } - } + } ); - levels.splice( l, 0, { distance: distance, object: object } ); + renderStateStack.pop(); + currentRenderState = null; - this.add( object ); + }; - return this; + // Animation Loop - } + let onAnimationFrameCallback = null; - getCurrentLevel() { + function onAnimationFrame( time ) { - return this._currentLevel; + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); } - getObjectForDistance( distance ) { - - const levels = this.levels; - - if ( levels.length > 0 ) { + function onXRSessionStart() { - let i, l; + animation.stop(); - for ( i = 1, l = levels.length; i < l; i ++ ) { + } - if ( distance < levels[ i ].distance ) { + function onXRSessionEnd() { - break; + animation.start(); - } + } - } + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); - return levels[ i - 1 ].object; + if ( typeof self !== 'undefined' ) animation.setContext( self ); - } + this.setAnimationLoop = function ( callback ) { - return null; + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); - } + ( callback === null ) ? animation.stop() : animation.start(); - raycast( raycaster, intersects ) { + }; - const levels = this.levels; + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); - if ( levels.length > 0 ) { + // Rendering - _v1$4.setFromMatrixPosition( this.matrixWorld ); + this.render = function ( scene, camera ) { - const distance = raycaster.ray.origin.distanceTo( _v1$4 ); + if ( camera !== undefined && camera.isCamera !== true ) { - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; } - } + if ( _isContextLost === true ) return; - update( camera ) { + // update scene graph - const levels = this.levels; + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); - if ( levels.length > 1 ) { + // update camera matrices and frustum - _v1$4.setFromMatrixPosition( camera.matrixWorld ); - _v2$2.setFromMatrixPosition( this.matrixWorld ); + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); - const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom; + if ( xr.enabled === true && xr.isPresenting === true ) { - levels[ 0 ].object.visible = true; + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); - let i, l; + camera = xr.getCamera(); // use XR camera for rendering - for ( i = 1, l = levels.length; i < l; i ++ ) { + } - if ( distance >= levels[ i ].distance ) { + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init(); - } else { + renderStateStack.push( currentRenderState ); - break; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); - } + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - } + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); - this._currentLevel = i - 1; + renderListStack.push( currentRenderList ); - for ( ; i < l; i ++ ) { + projectObject( scene, camera, 0, _this.sortObjects ); - levels[ i ].object.visible = false; + currentRenderList.finish(); - } + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); } - } + // - toJSON( meta ) { + if ( _clippingEnabled === true ) clipping.beginShadows(); - const data = super.toJSON( meta ); + const shadowsArray = currentRenderState.state.shadowsArray; - if ( this.autoUpdate === false ) data.object.autoUpdate = false; + shadowMap.render( shadowsArray, scene, camera ); - data.object.levels = []; + if ( _clippingEnabled === true ) clipping.endShadows(); - const levels = this.levels; + // - for ( let i = 0, l = levels.length; i < l; i ++ ) { + if ( this.info.autoReset === true ) this.info.reset(); - const level = levels[ i ]; + // - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + background.render( currentRenderList, scene ); - } + // render scene - return data; + currentRenderState.setupLights( _this.physicallyCorrectLights ); - } + if ( camera.isArrayCamera ) { -} + const cameras = camera.cameras; -const _basePosition = new Vector3(); + for ( let i = 0, l = cameras.length; i < l; i ++ ) { -const _skinIndex = new Vector4(); -const _skinWeight = new Vector4(); + const camera2 = cameras[ i ]; -const _vector$7 = new Vector3(); -const _matrix$1 = new Matrix4(); + renderScene( currentRenderList, scene, camera2, camera2.viewport ); -function SkinnedMesh( geometry, material ) { + } - Mesh.call( this, geometry, material ); + } else { - this.type = 'SkinnedMesh'; + renderScene( currentRenderList, scene, camera ); - this.bindMode = 'attached'; - this.bindMatrix = new Matrix4(); - this.bindMatrixInverse = new Matrix4(); + } -} + // -SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + if ( _currentRenderTarget !== null ) { - constructor: SkinnedMesh, + // resolve multisample renderbuffers to a single-sample texture if necessary - isSkinnedMesh: true, + textures.updateMultisampleRenderTarget( _currentRenderTarget ); - copy: function ( source ) { + // Generate mipmap if we're using any kind of mipmap filtering - Mesh.prototype.copy.call( this, source ); + textures.updateRenderTargetMipmap( _currentRenderTarget ); - this.bindMode = source.bindMode; - this.bindMatrix.copy( source.bindMatrix ); - this.bindMatrixInverse.copy( source.bindMatrixInverse ); + } - this.skeleton = source.skeleton; + // - return this; + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); - }, + // _gl.finish(); - bind: function ( skeleton, bindMatrix ) { + bindingStates.resetDefaultState(); + _currentMaterialId = - 1; + _currentCamera = null; - this.skeleton = skeleton; + renderStateStack.pop(); - if ( bindMatrix === undefined ) { + if ( renderStateStack.length > 0 ) { - this.updateMatrixWorld( true ); + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; - this.skeleton.calculateInverses(); + } else { - bindMatrix = this.matrixWorld; + currentRenderState = null; } - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.copy( bindMatrix ).invert(); - - }, + renderListStack.pop(); - pose: function () { + if ( renderListStack.length > 0 ) { - this.skeleton.pose(); + currentRenderList = renderListStack[ renderListStack.length - 1 ]; - }, + } else { - normalizeSkinWeights: function () { + currentRenderList = null; - const vector = new Vector4(); + } - const skinWeight = this.geometry.attributes.skinWeight; + }; - for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { + function projectObject( object, camera, groupOrder, sortObjects ) { - vector.x = skinWeight.getX( i ); - vector.y = skinWeight.getY( i ); - vector.z = skinWeight.getZ( i ); - vector.w = skinWeight.getW( i ); + if ( object.visible === false ) return; - const scale = 1.0 / vector.manhattanLength(); + const visible = object.layers.test( camera.layers ); - if ( scale !== Infinity ) { + if ( visible ) { - vector.multiplyScalar( scale ); + if ( object.isGroup ) { - } else { + groupOrder = object.renderOrder; - vector.set( 1, 0, 0, 0 ); // do something reasonable + } else if ( object.isLOD ) { - } + if ( object.autoUpdate === true ) object.update( camera ); - skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); + } else if ( object.isLight ) { - } + currentRenderState.pushLight( object ); - }, + if ( object.castShadow ) { - updateMatrixWorld: function ( force ) { + currentRenderState.pushShadow( object ); - Mesh.prototype.updateMatrixWorld.call( this, force ); + } - if ( this.bindMode === 'attached' ) { + } else if ( object.isSprite ) { - this.bindMatrixInverse.copy( this.matrixWorld ).invert(); + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { - } else if ( this.bindMode === 'detached' ) { + if ( sortObjects ) { - this.bindMatrixInverse.copy( this.bindMatrix ).invert(); + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - } else { + } - console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); + const geometry = objects.update( object ); + const material = object.material; - } + if ( material.visible ) { - }, + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); - boneTransform: function ( index, target ) { + } - const skeleton = this.skeleton; - const geometry = this.geometry; + } - _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); - _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); + } else if ( object.isMesh || object.isLine || object.isPoints ) { - _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix ); + if ( object.isSkinnedMesh ) { - target.set( 0, 0, 0 ); + // update skeleton only once in a frame - for ( let i = 0; i < 4; i ++ ) { + if ( object.skeleton.frame !== info.render.frame ) { - const weight = _skinWeight.getComponent( i ); + object.skeleton.update(); + object.skeleton.frame = info.render.frame; - if ( weight !== 0 ) { + } - const boneIndex = _skinIndex.getComponent( i ); + } - _matrix$1.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { - target.addScaledVector( _vector$7.copy( _basePosition ).applyMatrix4( _matrix$1 ), weight ); + if ( sortObjects ) { - } + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - } + } - return target.applyMatrix4( this.bindMatrixInverse ); + const geometry = objects.update( object ); + const material = object.material; - } + if ( Array.isArray( material ) ) { -} ); + const groups = geometry.groups; -function Bone() { + for ( let i = 0, l = groups.length; i < l; i ++ ) { - Object3D.call( this ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - this.type = 'Bone'; + if ( groupMaterial && groupMaterial.visible ) { -} + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); -Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { + } - constructor: Bone, + } - isBone: true + } else if ( material.visible ) { -} ); + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); -const _offsetMatrix = /*@__PURE__*/ new Matrix4(); -const _identityMatrix = /*@__PURE__*/ new Matrix4(); + } -class Skeleton { + } - constructor( bones = [], boneInverses = [] ) { + } - this.uuid = MathUtils.generateUUID(); + } - this.bones = bones.slice( 0 ); - this.boneInverses = boneInverses; - this.boneMatrices = null; + const children = object.children; - this.boneTexture = null; - this.boneTextureSize = 0; + for ( let i = 0, l = children.length; i < l; i ++ ) { - this.frame = - 1; + projectObject( children[ i ], camera, groupOrder, sortObjects ); - this.init(); + } } - init() { - - const bones = this.bones; - const boneInverses = this.boneInverses; + function renderScene( currentRenderList, scene, camera, viewport ) { - this.boneMatrices = new Float32Array( bones.length * 16 ); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + const transparentObjects = currentRenderList.transparent; - // calculate inverse bone matrices if necessary + currentRenderState.setupLightsView( camera ); - if ( boneInverses.length === 0 ) { + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera ); - this.calculateInverses(); + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); - } else { + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); - // handle special case + // Ensure depth buffer writing is enabled so it can be cleared on next render - if ( bones.length !== boneInverses.length ) { + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); - console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' ); + state.setPolygonOffset( false ); - this.boneInverses = []; + } - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + function renderTransmissionPass( opaqueObjects, scene, camera ) { - this.boneInverses.push( new Matrix4() ); + const isWebGL2 = capabilities.isWebGL2; - } + if ( _transmissionRenderTarget === null ) { - } + _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: ( isWebGL2 && _antialias === true ) ? 4 : 0 + } ); } - } + _this.getDrawingBufferSize( _vector2 ); - calculateInverses() { + if ( isWebGL2 ) { - this.boneInverses.length = 0; + _transmissionRenderTarget.setSize( _vector2.x, _vector2.y ); - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + } else { - const inverse = new Matrix4(); + _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) ); - if ( this.bones[ i ] ) { + } - inverse.copy( this.bones[ i ].matrixWorld ).invert(); + // - } + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget( _transmissionRenderTarget ); + _this.clear(); - this.boneInverses.push( inverse ); + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; - } + renderObjects( opaqueObjects, scene, camera ); + + _this.toneMapping = currentToneMapping; + + textures.updateMultisampleRenderTarget( _transmissionRenderTarget ); + textures.updateRenderTargetMipmap( _transmissionRenderTarget ); + + _this.setRenderTarget( currentRenderTarget ); } - pose() { + function renderObjects( renderList, scene, camera ) { - // recover the bind-time world matrices + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + for ( let i = 0, l = renderList.length; i < l; i ++ ) { - const bone = this.bones[ i ]; + const renderItem = renderList[ i ]; - if ( bone ) { + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; - bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); } } - // compute the local matrices, positions, rotations and scales + } - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + function renderObject( object, scene, camera, geometry, material, group ) { - const bone = this.bones[ i ]; + object.onBeforeRender( _this, scene, camera, geometry, material, group ); - if ( bone ) { + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - if ( bone.parent && bone.parent.isBone ) { + material.onBeforeRender( _this, scene, camera, geometry, object, group ); - bone.matrix.copy( bone.parent.matrixWorld ).invert(); - bone.matrix.multiply( bone.matrixWorld ); + if ( material.transparent === true && material.side === DoubleSide ) { - } else { + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); - bone.matrix.copy( bone.matrixWorld ); + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); - } + material.side = DoubleSide; - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + } else { - } + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); } + object.onAfterRender( _this, scene, camera, geometry, material, group ); + } - update() { + function getProgram( material, scene, object ) { - const bones = this.bones; - const boneInverses = this.boneInverses; - const boneMatrices = this.boneMatrices; - const boneTexture = this.boneTexture; + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... - // flatten bone matrices to array + const materialProperties = properties.get( material ); - for ( let i = 0, il = bones.length; i < il; i ++ ) { + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; - // compute the offset between the current and the original transform + const lightsStateVersion = lights.state.version; - const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); - _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); - _offsetMatrix.toArray( boneMatrices, i * 16 ); + let programs = materialProperties.programs; - } + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change - if ( boneTexture !== null ) { + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); - boneTexture.needsUpdate = true; + if ( programs === undefined ) { - } + // new material - } + material.addEventListener( 'dispose', onMaterialDispose ); - clone() { + programs = new Map(); + materialProperties.programs = programs; - return new Skeleton( this.bones, this.boneInverses ); + } - } + let program = programs.get( programCacheKey ); - getBoneByName( name ) { + if ( program !== undefined ) { - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + // early out if program and light state is identical - const bone = this.bones[ i ]; + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { - if ( bone.name === name ) { + updateCommonMaterialProperties( material, parameters ); - return bone; + return program; } - } - - return undefined; + } else { - } + parameters.uniforms = programCache.getUniforms( material ); - dispose( ) { + material.onBuild( object, parameters, _this ); - if ( this.boneTexture !== null ) { + material.onBeforeCompile( parameters, _this ); - this.boneTexture.dispose(); + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); - this.boneTexture = null; + materialProperties.uniforms = parameters.uniforms; } - } + const uniforms = materialProperties.uniforms; - fromJSON( json, bones ) { + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { - this.uuid = json.uuid; + uniforms.clippingPlanes = clipping.uniform; - for ( let i = 0, l = json.bones.length; i < l; i ++ ) { + } - const uuid = json.bones[ i ]; - let bone = bones[ uuid ]; + updateCommonMaterialProperties( material, parameters ); - if ( bone === undefined ) { + // store the light setup it was created for - console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid ); - bone = new Bone(); + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; - } + if ( materialProperties.needsLights ) { - this.bones.push( bone ); - this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms } - this.init(); + const progUniforms = program.getUniforms(); + const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - return this; + materialProperties.currentProgram = program; + materialProperties.uniformsList = uniformsList; + + return program; } - toJSON() { + function updateCommonMaterialProperties( material, parameters ) { - const data = { - metadata: { - version: 4.5, - type: 'Skeleton', - generator: 'Skeleton.toJSON' - }, - bones: [], - boneInverses: [] - }; + const materialProperties = properties.get( material ); - data.uuid = this.uuid; + materialProperties.outputEncoding = parameters.outputEncoding; + materialProperties.instancing = parameters.instancing; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; - const bones = this.bones; - const boneInverses = this.boneInverses; + } - for ( let i = 0, l = bones.length; i < l; i ++ ) { + function setProgram( camera, scene, geometry, material, object ) { - const bone = bones[ i ]; - data.bones.push( bone.uuid ); + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... - const boneInverse = boneInverses[ i ]; - data.boneInverses.push( boneInverse.toArray() ); + textures.resetTextureUnits(); - } + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding ); + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent; + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping; + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; - return data; + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; - } + if ( _clippingEnabled === true ) { -} + if ( _localClippingEnabled === true || camera !== _currentCamera ) { -const _instanceLocalMatrix = new Matrix4(); -const _instanceWorldMatrix = new Matrix4(); + const useCache = + camera === _currentCamera && + material.id === _currentMaterialId; -const _instanceIntersects = []; + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + clipping.setState( material, camera, useCache ); -const _mesh = new Mesh(); + } -function InstancedMesh( geometry, material, count ) { + } - Mesh.call( this, geometry, material ); + // - this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 ); - this.instanceColor = null; + let needsProgramChange = false; - this.count = count; + if ( material.version === materialProperties.__version ) { - this.frustumCulled = false; + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { -} + needsProgramChange = true; -InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + } else if ( materialProperties.outputEncoding !== encoding ) { - constructor: InstancedMesh, + needsProgramChange = true; - isInstancedMesh: true, + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { - copy: function ( source ) { + needsProgramChange = true; - Mesh.prototype.copy.call( this, source ); + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { - this.instanceMatrix.copy( source.instanceMatrix ); + needsProgramChange = true; - if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { - this.count = source.count; + needsProgramChange = true; - return this; + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { - }, + needsProgramChange = true; - getColorAt: function ( index, color ) { + } else if ( materialProperties.envMap !== envMap ) { - color.fromArray( this.instanceColor.array, index * 3 ); + needsProgramChange = true; - }, + } else if ( material.fog === true && materialProperties.fog !== fog ) { - getMatrixAt: function ( index, matrix ) { + needsProgramChange = true; - matrix.fromArray( this.instanceMatrix.array, index * 16 ); + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { - }, + needsProgramChange = true; - raycast: function ( raycaster, intersects ) { + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { - const matrixWorld = this.matrixWorld; - const raycastTimes = this.count; + needsProgramChange = true; - _mesh.geometry = this.geometry; - _mesh.material = this.material; + } else if ( materialProperties.vertexTangents !== vertexTangents ) { - if ( _mesh.material === undefined ) return; + needsProgramChange = true; - for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { + } else if ( materialProperties.morphTargets !== morphTargets ) { - // calculate the world matrix for each instance + needsProgramChange = true; - this.getMatrixAt( instanceId, _instanceLocalMatrix ); + } else if ( materialProperties.morphNormals !== morphNormals ) { - _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); + needsProgramChange = true; - // the mesh represents this single instance + } else if ( materialProperties.morphColors !== morphColors ) { - _mesh.matrixWorld = _instanceWorldMatrix; + needsProgramChange = true; - _mesh.raycast( raycaster, _instanceIntersects ); + } else if ( materialProperties.toneMapping !== toneMapping ) { - // process the result of raycast + needsProgramChange = true; - for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { + } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) { - const intersect = _instanceIntersects[ i ]; - intersect.instanceId = instanceId; - intersect.object = this; - intersects.push( intersect ); + needsProgramChange = true; } - _instanceIntersects.length = 0; + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; } - }, + // - setColorAt: function ( index, color ) { + let program = materialProperties.currentProgram; - if ( this.instanceColor === null ) { + if ( needsProgramChange === true ) { - this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 ); + program = getProgram( material, scene, object ); } - color.toArray( this.instanceColor.array, index * 3 ); - - }, + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; - setMatrixAt: function ( index, matrix ) { + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; - matrix.toArray( this.instanceMatrix.array, index * 16 ); + if ( state.useProgram( program.program ) ) { - }, + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - updateMorphTargets: function () { + } - }, + if ( material.id !== _currentMaterialId ) { - dispose: function () { + _currentMaterialId = material.id; - this.dispatchEvent( { type: 'dispose' } ); + refreshMaterial = true; - } + } -} ); + if ( refreshProgram || _currentCamera !== camera ) { -/** - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round" - * } - */ + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); -class LineBasicMaterial extends Material { + if ( capabilities.logarithmicDepthBuffer ) { - constructor( parameters ) { + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - super(); + } - this.type = 'LineBasicMaterial'; + if ( _currentCamera !== camera ) { - this.color = new Color( 0xffffff ); + _currentCamera = camera; - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + // 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.morphTargets = false; + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done - this.setValues( parameters ); + } - } + // load material specific uniforms + // (shader material also gets them for the sake of genericity) + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshStandardMaterial || + material.envMap ) { - copy( source ) { + const uCamPos = p_uniforms.map.cameraPosition; - super.copy( source ); + if ( uCamPos !== undefined ) { - this.color.copy( source.color ); + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + } - this.morphTargets = source.morphTargets; + } - return this; + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { - } + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); -} + } -LineBasicMaterial.prototype.isLineBasicMaterial = true; + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.isShadowMaterial || + object.isSkinnedMesh ) { -const _start = new Vector3(); -const _end = new Vector3(); -const _inverseMatrix$1 = new Matrix4(); -const _ray$1 = new Ray(); -const _sphere$2 = new Sphere(); + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); -function Line( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { + } - Object3D.call( this ); + } - this.type = 'Line'; + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures - this.geometry = geometry; - this.material = material; + if ( object.isSkinnedMesh ) { - this.updateMorphTargets(); + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); -} + const skeleton = object.skeleton; -Line.prototype = Object.assign( Object.create( Object3D.prototype ), { + if ( skeleton ) { - constructor: Line, + if ( capabilities.floatVertexTextures ) { - isLine: true, + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); - copy: function ( source ) { + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); - Object3D.prototype.copy.call( this, source ); + } else { - this.material = source.material; - this.geometry = source.geometry; + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); - return this; + } - }, + } - computeLineDistances: function () { + } - const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; - if ( geometry.isBufferGeometry ) { + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) { - // we assume non-indexed geometry + morphtargets.update( object, geometry, material, program ); - if ( geometry.index === null ) { + } - const positionAttribute = geometry.attributes.position; - const lineDistances = [ 0 ]; + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { - for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); - _start.fromBufferAttribute( positionAttribute, i - 1 ); - _end.fromBufferAttribute( positionAttribute, i ); + } - lineDistances[ i ] = lineDistances[ i - 1 ]; - lineDistances[ i ] += _start.distanceTo( _end ); + // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 - } + if ( material.isMeshGouraudMaterial && material.envMap !== null ) { - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + m_uniforms.envMap.value = envMap; - } else { + m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; - console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + } - } + if ( refreshMaterial ) { - } else if ( geometry.isGeometry ) { + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); - console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + if ( materialProperties.needsLights ) { - } + // the current material requires lighting info - return this; + // 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 - }, + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); - raycast: function ( raycaster, intersects ) { + } - const geometry = this.geometry; - const matrixWorld = this.matrixWorld; - const threshold = raycaster.params.Line.threshold; + // refresh uniforms common to several materials - // Checking boundingSphere distance to ray + if ( fog && material.fog === true ) { - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + materials.refreshFogUniforms( m_uniforms, fog ); - _sphere$2.copy( geometry.boundingSphere ); - _sphere$2.applyMatrix4( matrixWorld ); - _sphere$2.radius += threshold; + } - if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return; + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget ); - // + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); - _inverseMatrix$1.copy( matrixWorld ).invert(); - _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + } - const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - const localThresholdSq = localThreshold * localThreshold; + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { - const vStart = new Vector3(); - const vEnd = new Vector3(); - const interSegment = new Vector3(); - const interRay = new Vector3(); - const step = this.isLineSegments ? 2 : 1; + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + material.uniformsNeedUpdate = false; - if ( geometry.isBufferGeometry ) { + } - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; + if ( material.isSpriteMaterial ) { - if ( index !== null ) { + p_uniforms.setValue( _gl, 'center', object.center ); - const indices = index.array; + } - for ( let i = 0, l = indices.length - 1; i < l; i += step ) { + // common matrices - const a = indices[ i ]; - const b = indices[ i + 1 ]; + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - vStart.fromBufferAttribute( positionAttribute, a ); - vEnd.fromBufferAttribute( positionAttribute, b ); + // UBOs - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + if ( material.isShaderMaterial || material.isRawShaderMaterial ) { - if ( distSq > localThresholdSq ) continue; + const groups = material.uniformsGroups; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + for ( let i = 0, l = groups.length; i < l; i ++ ) { - const distance = raycaster.ray.origin.distanceTo( interRay ); + if ( capabilities.isWebGL2 ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + const group = groups[ i ]; - intersects.push( { + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); - 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 + } else { - } ); + console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' ); } - } else { + } - for ( let i = 0, l = positionAttribute.count - 1; i < l; i += step ) { + } - vStart.fromBufferAttribute( positionAttribute, i ); - vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + return program; - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + } - if ( distSq > localThresholdSq ) continue; + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + function markUniformsLightsNeedsUpdate( uniforms, value ) { - const distance = raycaster.ray.origin.distanceTo( interRay ); + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; - if ( distance < raycaster.near || distance > raycaster.far ) continue; + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - intersects.push( { + } - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + function materialNeedsLights( material ) { - } ); + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); - } + } - } + this.getActiveCubeFace = function () { - } else if ( geometry.isGeometry ) { + return _currentActiveCubeFace; - console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + }; - } + this.getActiveMipmapLevel = function () { - }, + return _currentActiveMipmapLevel; - updateMorphTargets: function () { + }; - const geometry = this.geometry; + this.getRenderTarget = function () { - if ( geometry.isBufferGeometry ) { + return _currentRenderTarget; - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); + }; - if ( keys.length > 0 ) { + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture; - if ( morphAttribute !== undefined ) { + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__hasExternalTextures = true; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( renderTargetProperties.__hasExternalTextures ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; - const name = morphAttribute[ m ].name || String( m ); + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { - } + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; } } - } else { + } - const morphTargets = geometry.morphTargets; + }; - if ( morphTargets !== undefined && morphTargets.length > 0 ) { + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { - console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; - } + }; - } + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { - } + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let useDefaultFramebuffer = true; -} ); + if ( renderTarget ) { -const _start$1 = new Vector3(); -const _end$1 = new Vector3(); + const renderTargetProperties = properties.get( renderTarget ); -function LineSegments( geometry, material ) { + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { - Line.call( this, geometry, material ); + // We need to make sure to rebind the framebuffer. + state.bindFramebuffer( 36160, null ); + useDefaultFramebuffer = false; - this.type = 'LineSegments'; + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { -} + textures.setupRenderTarget( renderTarget ); -LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { + } else if ( renderTargetProperties.__hasExternalTextures ) { - constructor: LineSegments, + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); - isLineSegments: true, + } - computeLineDistances: function () { + } - const geometry = this.geometry; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { - if ( geometry.isBufferGeometry ) { + const texture = renderTarget.texture; - // we assume non-indexed geometry + if ( texture.isData3DTexture || texture.isDataArrayTexture ) { - if ( geometry.index === null ) { + isRenderTarget3D = true; - const positionAttribute = geometry.attributes.position; - const lineDistances = []; + } - for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; - _start$1.fromBufferAttribute( positionAttribute, i ); - _end$1.fromBufferAttribute( positionAttribute, i + 1 ); + if ( renderTarget.isWebGLCubeRenderTarget ) { - lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; - lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); + framebuffer = __webglFramebuffer[ activeCubeFace ]; + isCube = true; - } + } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; } else { - console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + framebuffer = __webglFramebuffer; } - } else if ( geometry.isGeometry ) { + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { - console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; } - return this; + const framebufferBound = state.bindFramebuffer( 36160, framebuffer ); - } + if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) { -} ); + state.drawBuffers( renderTarget, framebuffer ); -class LineLoop extends Line { + } - constructor( geometry, material ) { + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); - super( geometry, material ); + if ( isCube ) { - this.type = 'LineLoop'; + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); - } + } else if ( isRenderTarget3D ) { -} + const textureProperties = properties.get( renderTarget.texture ); + const layer = activeCubeFace || 0; + _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); -LineLoop.prototype.isLineLoop = true; + } -/** - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * alphaMap: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * - * morphTargets: - * } - */ + _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings -class PointsMaterial extends Material { + }; - constructor( parameters ) { + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { - super(); + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { - this.type = 'PointsMaterial'; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - this.color = new Color( 0xffffff ); + } - this.map = null; + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; - this.alphaMap = null; + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { - this.size = 1; - this.sizeAttenuation = true; + framebuffer = framebuffer[ activeCubeFaceIndex ]; - this.morphTargets = false; + } - this.setValues( parameters ); + if ( framebuffer ) { - } + state.bindFramebuffer( 36160, framebuffer ); - copy( source ) { + try { - super.copy( source ); + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; - this.color.copy( source.color ); + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { - this.map = source.map; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; - this.alphaMap = source.alphaMap; + } - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); - this.morphTargets = source.morphTargets; + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! halfFloatSupportedByExt ) { - return this; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - } + } -} + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) -PointsMaterial.prototype.isPointsMaterial = true; + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { -const _inverseMatrix$2 = new Matrix4(); -const _ray$2 = new Ray(); -const _sphere$3 = new Sphere(); -const _position$1 = new Vector3(); + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); -function Points( geometry = new BufferGeometry(), material = new PointsMaterial() ) { + } - Object3D.call( this ); + } finally { - this.type = 'Points'; + // restore framebuffer of current render target if necessary - this.geometry = geometry; - this.material = material; + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( 36160, framebuffer ); - this.updateMorphTargets(); + } -} + } -Points.prototype = Object.assign( Object.create( Object3D.prototype ), { + }; - constructor: Points, + this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { - isPoints: true, + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); - copy: function ( source ) { + textures.setTexture2D( texture, 0 ); - Object3D.prototype.copy.call( this, source ); + _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height ); - this.material = source.material; - this.geometry = source.geometry; + state.unbindTexture(); - return this; + }; - }, + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { - raycast: function ( raycaster, intersects ) { + const width = srcTexture.image.width; + const height = srcTexture.image.height; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); - const geometry = this.geometry; - const matrixWorld = this.matrixWorld; - const threshold = raycaster.params.Points.threshold; + textures.setTexture2D( dstTexture, 0 ); - // Checking boundingSphere distance to ray + // As another texture upload may have changed pixelStorei + // parameters, make sure they are correct for the dstTexture + _gl.pixelStorei( 37440, dstTexture.flipY ); + _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + if ( srcTexture.isDataTexture ) { - _sphere$3.copy( geometry.boundingSphere ); - _sphere$3.applyMatrix4( matrixWorld ); - _sphere$3.radius += threshold; + _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); - if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; + } else { - // + if ( srcTexture.isCompressedTexture ) { - _inverseMatrix$2.copy( matrixWorld ).invert(); - _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); - const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - const localThresholdSq = localThreshold * localThreshold; + } else { - if ( geometry.isBufferGeometry ) { + _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image ); - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; + } - if ( index !== null ) { + } - const indices = index.array; + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 ); - for ( let i = 0, il = indices.length; i < il; i ++ ) { + state.unbindTexture(); - const a = indices[ i ]; + }; - _position$1.fromBufferAttribute( positionAttribute, a ); + this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { - testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + if ( _this.isWebGL1Renderer ) { - } + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); + return; - } else { + } - for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) { + const width = sourceBox.max.x - sourceBox.min.x + 1; + const height = sourceBox.max.y - sourceBox.min.y + 1; + const depth = sourceBox.max.z - sourceBox.min.z + 1; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; - _position$1.fromBufferAttribute( positionAttribute, i ); + if ( dstTexture.isData3DTexture ) { - testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + textures.setTexture3D( dstTexture, 0 ); + glTarget = 32879; - } + } else if ( dstTexture.isDataArrayTexture ) { - } + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = 35866; } else { - console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); + return; } - }, - - updateMorphTargets: function () { - - const geometry = this.geometry; - - if ( geometry.isBufferGeometry ) { + _gl.pixelStorei( 37440, dstTexture.flipY ); + _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); + const unpackRowLen = _gl.getParameter( 3314 ); + const unpackImageHeight = _gl.getParameter( 32878 ); + const unpackSkipPixels = _gl.getParameter( 3316 ); + const unpackSkipRows = _gl.getParameter( 3315 ); + const unpackSkipImages = _gl.getParameter( 32877 ); - if ( keys.length > 0 ) { + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image; - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + _gl.pixelStorei( 3314, image.width ); + _gl.pixelStorei( 32878, image.height ); + _gl.pixelStorei( 3316, sourceBox.min.x ); + _gl.pixelStorei( 3315, sourceBox.min.y ); + _gl.pixelStorei( 32877, sourceBox.min.z ); - if ( morphAttribute !== undefined ) { + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data ); - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + } else { - const name = morphAttribute[ m ].name || String( m ); + if ( srcTexture.isCompressedTexture ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); + _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); - } + } else { - } + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image ); } - } else { - - const morphTargets = geometry.morphTargets; + } - if ( morphTargets !== undefined && morphTargets.length > 0 ) { + _gl.pixelStorei( 3314, unpackRowLen ); + _gl.pixelStorei( 32878, unpackImageHeight ); + _gl.pixelStorei( 3316, unpackSkipPixels ); + _gl.pixelStorei( 3315, unpackSkipRows ); + _gl.pixelStorei( 32877, unpackSkipImages ); - console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); - } + state.unbindTexture(); - } + }; - } + this.initTexture = function ( texture ) { -} ); + if ( texture.isCubeTexture ) { -function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + textures.setTextureCube( texture, 0 ); - const rayPointDistanceSq = _ray$2.distanceSqToPoint( point ); + } else if ( texture.isData3DTexture ) { - if ( rayPointDistanceSq < localThresholdSq ) { + textures.setTexture3D( texture, 0 ); - const intersectPoint = new Vector3(); + } else if ( texture.isDataArrayTexture ) { - _ray$2.closestPointToPoint( point, intersectPoint ); - intersectPoint.applyMatrix4( matrixWorld ); + textures.setTexture2DArray( texture, 0 ); - const distance = raycaster.ray.origin.distanceTo( intersectPoint ); + } else { - if ( distance < raycaster.near || distance > raycaster.far ) return; + textures.setTexture2D( texture, 0 ); - intersects.push( { + } - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint, - index: index, - face: null, - object: object + state.unbindTexture(); - } ); + }; - } + this.resetState = function () { -} + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; -class VideoTexture extends Texture { + state.reset(); + bindingStates.reset(); - constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + }; - super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - this.format = format !== undefined ? format : RGBFormat; + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); - this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; - this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + } - this.generateMipmaps = false; +} - const scope = this; +class WebGL1Renderer extends WebGLRenderer {} - function updateVideo() { +WebGL1Renderer.prototype.isWebGL1Renderer = true; - scope.needsUpdate = true; - video.requestVideoFrameCallback( updateVideo ); +class FogExp2 { - } + constructor( color, density = 0.00025 ) { - if ( 'requestVideoFrameCallback' in video ) { + this.isFogExp2 = true; - video.requestVideoFrameCallback( updateVideo ); + this.name = ''; - } + this.color = new Color( color ); + this.density = density; } clone() { - return new this.constructor( this.image ).copy( this ); + return new FogExp2( this.color, this.density ); } - update() { - - const video = this.image; - const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; - - if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { - - this.needsUpdate = true; + toJSON( /* meta */ ) { - } + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; } } -VideoTexture.prototype.isVideoTexture = true; +class Fog { -class CompressedTexture extends Texture { + constructor( color, near = 1, far = 1000 ) { - constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isFog = true; - super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.name = ''; - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + this.color = new Color( color ); - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + this.near = near; + this.far = far; - this.flipY = false; + } - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + clone() { - this.generateMipmaps = false; + return new Fog( this.color, this.near, this.far ); } -} - -CompressedTexture.prototype.isCompressedTexture = true; + toJSON( /* meta */ ) { -class CanvasTexture extends Texture { + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; - constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + } - super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); +} - this.needsUpdate = true; +class Scene extends Object3D { - } + constructor() { -} + super(); -CanvasTexture.prototype.isCanvasTexture = true; + this.isScene = true; -class DepthTexture extends Texture { + this.type = 'Scene'; - constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + this.background = null; + this.environment = null; + this.fog = null; - format = format !== undefined ? format : DepthFormat; + this.overrideMaterial = null; - if ( format !== DepthFormat && format !== DepthStencilFormat ) { + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); } - if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; - if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; + } - super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + copy( source, recursive ) { - this.image = { width: width, height: height }; + super.copy( source, recursive ); - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); - this.flipY = false; - this.generateMipmaps = false; + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + return this; } + toJSON( meta ) { -} + const data = super.toJSON( meta ); -DepthTexture.prototype.isDepthTexture = true; + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); -class CircleGeometry extends BufferGeometry { + return data; - constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) { + } - super(); + // @deprecated - this.type = 'CircleGeometry'; + get autoUpdate() { - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + return this.matrixWorldAutoUpdate; - segments = Math.max( 3, segments ); + } - // buffers + set autoUpdate( value ) { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + this.matrixWorldAutoUpdate = value; - // helper variables + } - const vertex = new Vector3(); - const uv = new Vector2(); +} - // center point +class InterleavedBuffer { - vertices.push( 0, 0, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( 0.5, 0.5 ); + constructor( array, stride ) { - for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { + this.isInterleavedBuffer = true; - const segment = thetaStart + s / segments * thetaLength; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; - // vertex + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + this.version = 0; - vertices.push( vertex.x, vertex.y, vertex.z ); + this.uuid = generateUUID(); - // normal + } - normals.push( 0, 0, 1 ); + onUploadCallback() {} - // uvs + set needsUpdate( value ) { - uv.x = ( vertices[ i ] / radius + 1 ) / 2; - uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + if ( value === true ) this.version ++; - uvs.push( uv.x, uv.y ); + } - } + setUsage( value ) { - // indices + this.usage = value; - for ( let i = 1; i <= segments; i ++ ) { + return this; - indices.push( i, i + 1, 0 ); + } - } + copy( source ) { - // build geometry + this.array = new source.array.constructor( source.array ); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + return this; } -} + copyAt( index1, attribute, index2 ) { -class CylinderGeometry extends BufferGeometry { + index1 *= this.stride; + index2 *= attribute.stride; - constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + for ( let i = 0, l = this.stride; i < l; i ++ ) { - super(); - this.type = 'CylinderGeometry'; + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - const scope = this; + return this; - radialSegments = Math.floor( radialSegments ); - heightSegments = Math.floor( heightSegments ); + } - // buffers + set( value, offset = 0 ) { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + this.array.set( value, offset ); - // helper variables + return this; - let index = 0; - const indexArray = []; - const halfHeight = height / 2; - let groupStart = 0; + } - // generate geometry + clone( data ) { - generateTorso(); + if ( data.arrayBuffers === undefined ) { - if ( openEnded === false ) { + data.arrayBuffers = {}; - if ( radiusTop > 0 ) generateCap( true ); - if ( radiusBottom > 0 ) generateCap( false ); + } + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); } - // build geometry + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; - function generateTorso() { + } - const normal = new Vector3(); - const vertex = new Vector3(); + const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); - let groupCount = 0; + const ib = new this.constructor( array, this.stride ); + ib.setUsage( this.usage ); - // this will be used to calculate the normal - const slope = ( radiusBottom - radiusTop ) / height; + return ib; - // generate vertices, normals and uvs + } - for ( let y = 0; y <= heightSegments; y ++ ) { + onUpload( callback ) { - const indexRow = []; + this.onUploadCallback = callback; - const v = y / heightSegments; + return this; - // calculate the radius of the current row + } - const radius = v * ( radiusBottom - radiusTop ) + radiusTop; + toJSON( data ) { - for ( let x = 0; x <= radialSegments; x ++ ) { + if ( data.arrayBuffers === undefined ) { - const u = x / radialSegments; + data.arrayBuffers = {}; - const theta = u * thetaLength + thetaStart; + } - const sinTheta = Math.sin( theta ); - const cosTheta = Math.cos( theta ); + // generate UUID for array buffer if necessary - // vertex + if ( this.array.buffer._uuid === undefined ) { - vertex.x = radius * sinTheta; - vertex.y = - v * height + halfHeight; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + this.array.buffer._uuid = generateUUID(); - // normal + } - normal.set( sinTheta, slope, cosTheta ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { - // uv + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); - uvs.push( u, 1 - v ); + } - // save index of vertex in respective row + // - indexRow.push( index ++ ); + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; - } + } - // now save vertices of the row in our index array +} - indexArray.push( indexRow ); +const _vector$6 = /*@__PURE__*/ new Vector3(); - } +class InterleavedBufferAttribute { - // generate indices + constructor( interleavedBuffer, itemSize, offset, normalized = false ) { - for ( let x = 0; x < radialSegments; x ++ ) { + this.isInterleavedBufferAttribute = true; - for ( let y = 0; y < heightSegments; y ++ ) { + this.name = ''; - // we use the index array to access the correct indices + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; - const a = indexArray[ y ][ x ]; - const b = indexArray[ y + 1 ][ x ]; - const c = indexArray[ y + 1 ][ x + 1 ]; - const d = indexArray[ y ][ x + 1 ]; + this.normalized = normalized === true; - // faces + } - indices.push( a, b, d ); - indices.push( b, c, d ); + get count() { - // update group counter + return this.data.count; - groupCount += 6; + } - } + get array() { - } + return this.data.array; - // add a group to the geometry. this will ensure multi material support + } - scope.addGroup( groupStart, groupCount, 0 ); + set needsUpdate( value ) { - // calculate new start value for groups + this.data.needsUpdate = value; - groupStart += groupCount; + } - } + applyMatrix4( m ) { - function generateCap( top ) { + for ( let i = 0, l = this.data.count; i < l; i ++ ) { - // save the index of the first center vertex - const centerIndexStart = index; + _vector$6.fromBufferAttribute( this, i ); - const uv = new Vector2(); - const vertex = new Vector3(); + _vector$6.applyMatrix4( m ); - let groupCount = 0; + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); - const radius = ( top === true ) ? radiusTop : radiusBottom; - const sign = ( top === true ) ? 1 : - 1; + } - // 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 + return this; - for ( let x = 1; x <= radialSegments; x ++ ) { + } - // vertex + applyNormalMatrix( m ) { - vertices.push( 0, halfHeight * sign, 0 ); + for ( let i = 0, l = this.count; i < l; i ++ ) { - // normal + _vector$6.fromBufferAttribute( this, i ); - normals.push( 0, sign, 0 ); + _vector$6.applyNormalMatrix( m ); - // uv + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); - uvs.push( 0.5, 0.5 ); + } - // increase index + return this; - index ++; + } - } + transformDirection( m ) { - // save the index of the last center vertex - const centerIndexEnd = index; + for ( let i = 0, l = this.count; i < l; i ++ ) { - // now we generate the surrounding vertices, normals and uvs + _vector$6.fromBufferAttribute( this, i ); - for ( let x = 0; x <= radialSegments; x ++ ) { + _vector$6.transformDirection( m ); - const u = x / radialSegments; - const theta = u * thetaLength + thetaStart; + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); - const cosTheta = Math.cos( theta ); - const sinTheta = Math.sin( theta ); + } - // vertex + return this; - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // normal + setX( index, x ) { - normals.push( 0, sign, 0 ); + if ( this.normalized ) x = normalize( x, this.array ); - // uv + this.data.array[ index * this.data.stride + this.offset ] = x; - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.push( uv.x, uv.y ); + return this; - // increase index + } - index ++; + setY( index, y ) { - } + if ( this.normalized ) y = normalize( y, this.array ); - // generate indices + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; - for ( let x = 0; x < radialSegments; x ++ ) { + return this; - const c = centerIndexStart + x; - const i = centerIndexEnd + x; + } - if ( top === true ) { + setZ( index, z ) { - // face top + if ( this.normalized ) z = normalize( z, this.array ); - indices.push( i, i + 1, c ); + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; - } else { + return this; - // face bottom + } - indices.push( i + 1, i, c ); + setW( index, w ) { - } + if ( this.normalized ) w = normalize( w, this.array ); - groupCount += 3; + 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, top === true ? 1 : 2 ); + getX( index ) { - // calculate new start value for groups + let x = this.data.array[ index * this.data.stride + this.offset ]; - groupStart += groupCount; + if ( this.normalized ) x = denormalize( x, this.array ); - } + return x; } -} + getY( index ) { -class ConeGeometry extends CylinderGeometry { + let y = this.data.array[ index * this.data.stride + this.offset + 1 ]; - constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + if ( this.normalized ) y = denormalize( y, this.array ); - super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + return y; - this.type = 'ConeGeometry'; + } - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + getZ( index ) { - } + let z = this.data.array[ index * this.data.stride + this.offset + 2 ]; -} + if ( this.normalized ) z = denormalize( z, this.array ); -class PolyhedronGeometry extends BufferGeometry { + return z; - constructor( vertices, indices, radius = 1, detail = 0 ) { + } - super(); + getW( index ) { - this.type = 'PolyhedronGeometry'; + let w = this.data.array[ index * this.data.stride + this.offset + 3 ]; - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + if ( this.normalized ) w = denormalize( w, this.array ); - // default buffer data + return w; - const vertexBuffer = []; - const uvBuffer = []; + } - // the subdivision creates the vertex buffer data + setXY( index, x, y ) { - subdivide( detail ); + index = index * this.data.stride + this.offset; - // all vertices should lie on a conceptual sphere with a given radius + if ( this.normalized ) { - applyRadius( radius ); + x = normalize( x, this.array ); + y = normalize( y, this.array ); - // finally, create the uv data + } - generateUVs(); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; - // build non-indexed geometry + return this; - this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + } - if ( detail === 0 ) { + setXYZ( index, x, y, z ) { - this.computeVertexNormals(); // flat normals + index = index * this.data.stride + this.offset; - } else { + if ( this.normalized ) { - this.normalizeNormals(); // smooth normals + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); } - // helper functions + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; - function subdivide( detail ) { + return this; - const a = new Vector3(); - const b = new Vector3(); - const c = new Vector3(); + } - // iterate over all faces and apply a subdivison with the given detail value + setXYZW( index, x, y, z, w ) { - for ( let i = 0; i < indices.length; i += 3 ) { + index = index * this.data.stride + this.offset; - // get the vertices of the face + if ( this.normalized ) { - getVertexByIndex( indices[ i + 0 ], a ); - getVertexByIndex( indices[ i + 1 ], b ); - getVertexByIndex( indices[ i + 2 ], c ); + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); - // perform subdivision + } - subdivideFace( a, b, c, detail ); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; - } + return this; - } + } - function subdivideFace( a, b, c, detail ) { + clone( data ) { - const cols = detail + 1; + if ( data === undefined ) { - // we use this multidimensional array as a data structure for creating the subdivision + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.' ); - const v = []; + const array = []; - // construct all of the vertices for this subdivision + for ( let i = 0; i < this.count; i ++ ) { - for ( let i = 0; i <= cols; i ++ ) { + const index = i * this.data.stride + this.offset; - v[ i ] = []; + for ( let j = 0; j < this.itemSize; j ++ ) { - const aj = a.clone().lerp( c, i / cols ); - const bj = b.clone().lerp( c, i / cols ); + array.push( this.data.array[ index + j ] ); - const rows = cols - i; + } - for ( let j = 0; j <= rows; j ++ ) { + } - if ( j === 0 && i === cols ) { + return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); - v[ i ][ j ] = aj; + } else { - } else { + if ( data.interleavedBuffers === undefined ) { - v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); + data.interleavedBuffers = {}; - } + } - } + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); } - // construct all of the faces + return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); - for ( let i = 0; i < cols; i ++ ) { + } + + } + + toJSON( data ) { - for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + if ( data === undefined ) { - const k = Math.floor( j / 2 ); + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.' ); - if ( j % 2 === 0 ) { + const array = []; - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); - pushVertex( v[ i ][ k ] ); + for ( let i = 0; i < this.count; i ++ ) { - } else { + const index = i * this.data.stride + this.offset; - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); + for ( let j = 0; j < this.itemSize; j ++ ) { - } + array.push( this.data.array[ index + j ] ); } } - } + // deinterleave data and save it as an ordinary buffer attribute for now - function applyRadius( radius ) { + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: array, + normalized: this.normalized + }; - const vertex = new Vector3(); + } else { - // iterate over the entire buffer and apply the radius to each vertex + // save as true interleaved attribtue - for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + if ( data.interleavedBuffers === undefined ) { - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + data.interleavedBuffers = {}; - vertex.normalize().multiplyScalar( radius ); + } - vertexBuffer[ i + 0 ] = vertex.x; - vertexBuffer[ i + 1 ] = vertex.y; - vertexBuffer[ i + 2 ] = vertex.z; + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } - function generateUVs() { + } - const vertex = new Vector3(); +} - for ( let i = 0; i < vertexBuffer.length; i += 3 ) { +class SpriteMaterial extends Material { - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + constructor( parameters ) { - const u = azimuth( vertex ) / 2 / Math.PI + 0.5; - const v = inclination( vertex ) / Math.PI + 0.5; - uvBuffer.push( u, 1 - v ); + super(); - } + this.isSpriteMaterial = true; - correctUVs(); + this.type = 'SpriteMaterial'; - correctSeam(); + this.color = new Color( 0xffffff ); - } + this.map = null; - function correctSeam() { + this.alphaMap = null; - // handle case when face straddles the seam, see #3269 + this.rotation = 0; - for ( let i = 0; i < uvBuffer.length; i += 6 ) { + this.sizeAttenuation = true; - // uv data of a single face + this.transparent = true; - const x0 = uvBuffer[ i + 0 ]; - const x1 = uvBuffer[ i + 2 ]; - const x2 = uvBuffer[ i + 4 ]; + this.fog = true; - const max = Math.max( x0, x1, x2 ); - const min = Math.min( x0, x1, x2 ); + this.setValues( parameters ); - // 0.9 is somewhat arbitrary + } - if ( max > 0.9 && min < 0.1 ) { + copy( source ) { - if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; - if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; - if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; + super.copy( source ); - } + this.color.copy( source.color ); - } + this.map = source.map; - } + this.alphaMap = source.alphaMap; - function pushVertex( vertex ) { + this.rotation = source.rotation; - vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + this.sizeAttenuation = source.sizeAttenuation; - } + this.fog = source.fog; - function getVertexByIndex( index, vertex ) { + return this; - const stride = index * 3; + } - vertex.x = vertices[ stride + 0 ]; - vertex.y = vertices[ stride + 1 ]; - vertex.z = vertices[ stride + 2 ]; +} - } +let _geometry; - function correctUVs() { +const _intersectPoint = /*@__PURE__*/ new Vector3(); +const _worldScale = /*@__PURE__*/ new Vector3(); +const _mvPosition = /*@__PURE__*/ new Vector3(); - const a = new Vector3(); - const b = new Vector3(); - const c = new Vector3(); +const _alignedPosition = /*@__PURE__*/ new Vector2(); +const _rotatedPosition = /*@__PURE__*/ new Vector2(); +const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); - const centroid = new Vector3(); +const _vA = /*@__PURE__*/ new Vector3(); +const _vB = /*@__PURE__*/ new Vector3(); +const _vC = /*@__PURE__*/ new Vector3(); - const uvA = new Vector2(); - const uvB = new Vector2(); - const uvC = new Vector2(); +const _uvA = /*@__PURE__*/ new Vector2(); +const _uvB = /*@__PURE__*/ new Vector2(); +const _uvC = /*@__PURE__*/ new Vector2(); - for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { +class Sprite extends Object3D { - a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); - b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); - c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); + constructor( material ) { - uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); - uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); - uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); + super(); - centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + this.isSprite = true; - const azi = azimuth( centroid ); + this.type = 'Sprite'; - correctUV( uvA, j + 0, a, azi ); - correctUV( uvB, j + 2, b, azi ); - correctUV( uvC, j + 4, c, azi ); + if ( _geometry === undefined ) { - } + _geometry = new BufferGeometry(); - } + const float32Array = new Float32Array( [ + - 0.5, - 0.5, 0, 0, 0, + 0.5, - 0.5, 0, 1, 0, + 0.5, 0.5, 0, 1, 1, + - 0.5, 0.5, 0, 0, 1 + ] ); - function correctUV( uv, stride, vector, azimuth ) { + const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { + _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); + _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); + _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); - uvBuffer[ stride ] = uv.x - 1; + } - } + this.geometry = _geometry; + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + this.center = new Vector2( 0.5, 0.5 ); - uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + } - } + raycast( raycaster, intersects ) { + + if ( raycaster.camera === null ) { + + console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); } - // Angle around the Y axis, counter-clockwise when looking from above. + _worldScale.setFromMatrixScale( this.matrixWorld ); - function azimuth( vector ) { + _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); + this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); - return Math.atan2( vector.z, - vector.x ); + _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); - } + if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + _worldScale.multiplyScalar( - _mvPosition.z ); - // Angle above the XZ plane. + } - function inclination( vector ) { + const rotation = this.material.rotation; + let sin, cos; - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + if ( rotation !== 0 ) { + + cos = Math.cos( rotation ); + sin = Math.sin( rotation ); } - } + const center = this.center; -} + transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); -class DodecahedronGeometry extends PolyhedronGeometry { + _uvA.set( 0, 0 ); + _uvB.set( 1, 0 ); + _uvC.set( 1, 1 ); - constructor( radius = 1, detail = 0 ) { + // check first triangle + let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint ); - const t = ( 1 + Math.sqrt( 5 ) ) / 2; - const r = 1 / t; + if ( intersect === null ) { - const vertices = [ + // check second triangle + transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + _uvB.set( 0, 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, 1, + intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint ); + if ( intersect === null ) { - // (0, ±1/φ, ±φ) - 0, - r, - t, 0, - r, t, - 0, r, - t, 0, r, t, + return; - // (±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 - ]; + } - const 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 - ]; + const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); - super( vertices, indices, radius, detail ); + if ( distance < raycaster.near || distance > raycaster.far ) return; - this.type = 'DodecahedronGeometry'; + intersects.push( { - this.parameters = { - radius: radius, - detail: detail - }; + distance: distance, + point: _intersectPoint.clone(), + uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ), + face: null, + object: this + + } ); } -} + copy( source, recursive ) { -const _v0$2 = new Vector3(); -const _v1$5 = new Vector3(); -const _normal$1 = new Vector3(); -const _triangle = new Triangle(); + super.copy( source, recursive ); -class EdgesGeometry extends BufferGeometry { + if ( source.center !== undefined ) this.center.copy( source.center ); - constructor( geometry, thresholdAngle ) { + this.material = source.material; - super(); + return this; - this.type = 'EdgesGeometry'; + } - this.parameters = { - thresholdAngle: thresholdAngle - }; +} - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; +function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { - if ( geometry.isGeometry === true ) { + // compute position in camera space + _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); - console.error( 'THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - return; + // to check if rotation is not zero + if ( sin !== undefined ) { - } + _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); + _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); - const precisionPoints = 4; - const precision = Math.pow( 10, precisionPoints ); - const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle ); + } else { - const indexAttr = geometry.getIndex(); - const positionAttr = geometry.getAttribute( 'position' ); - const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + _rotatedPosition.copy( _alignedPosition ); - const indexArr = [ 0, 0, 0 ]; - const vertKeys = [ 'a', 'b', 'c' ]; - const hashes = new Array( 3 ); + } - const edgeData = {}; - const vertices = []; - for ( let i = 0; i < indexCount; i += 3 ) { - if ( indexAttr ) { + vertexPosition.copy( mvPosition ); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; - indexArr[ 0 ] = indexAttr.getX( i ); - indexArr[ 1 ] = indexAttr.getX( i + 1 ); - indexArr[ 2 ] = indexAttr.getX( i + 2 ); + // transform to world space + vertexPosition.applyMatrix4( _viewWorldMatrix ); - } else { +} - indexArr[ 0 ] = i; - indexArr[ 1 ] = i + 1; - indexArr[ 2 ] = i + 2; +const _v1$2 = /*@__PURE__*/ new Vector3(); +const _v2$1 = /*@__PURE__*/ new Vector3(); - } +class LOD extends Object3D { - const { a, b, c } = _triangle; - a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); - b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); - c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); - _triangle.getNormal( _normal$1 ); + constructor() { - // create hashes for the edge from the vertices - hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; - hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; - hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; + super(); - // skip degenerate triangles - if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { + this._currentLevel = 0; - continue; + this.type = 'LOD'; + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true, } + } ); - // iterate over every edge - for ( let j = 0; j < 3; j ++ ) { + this.autoUpdate = true; - // get the first and next vertex making up the edge - const jNext = ( j + 1 ) % 3; - const vecHash0 = hashes[ j ]; - const vecHash1 = hashes[ jNext ]; - const v0 = _triangle[ vertKeys[ j ] ]; - const v1 = _triangle[ vertKeys[ jNext ] ]; + } - const hash = `${ vecHash0 }_${ vecHash1 }`; - const reverseHash = `${ vecHash1 }_${ vecHash0 }`; + copy( source ) { - if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { + super.copy( source, false ); - // if we found a sibling edge add it into the vertex array if - // it meets the angle threshold and delete the edge from the map. - if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + const levels = source.levels; - vertices.push( v0.x, v0.y, v0.z ); - vertices.push( v1.x, v1.y, v1.z ); + for ( let i = 0, l = levels.length; i < l; i ++ ) { - } + const level = levels[ i ]; - edgeData[ reverseHash ] = null; + this.addLevel( level.object.clone(), level.distance ); - } else if ( ! ( hash in edgeData ) ) { + } - // if we've already got an edge here then skip adding a new one - edgeData[ hash ] = { + this.autoUpdate = source.autoUpdate; - index0: indexArr[ j ], - index1: indexArr[ jNext ], - normal: _normal$1.clone(), + return this; - }; + } - } + addLevel( object, distance = 0 ) { - } + distance = Math.abs( distance ); - } + const levels = this.levels; - // iterate over all remaining, unmatched edges and add them to the vertex array - for ( const key in edgeData ) { + let l; - if ( edgeData[ key ] ) { + for ( l = 0; l < levels.length; l ++ ) { - const { index0, index1 } = edgeData[ key ]; - _v0$2.fromBufferAttribute( positionAttr, index0 ); - _v1$5.fromBufferAttribute( positionAttr, index1 ); + if ( distance < levels[ l ].distance ) { - vertices.push( _v0$2.x, _v0$2.y, _v0$2.z ); - vertices.push( _v1$5.x, _v1$5.y, _v1$5.z ); + break; } } - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + levels.splice( l, 0, { distance: distance, object: object } ); - } + this.add( object ); -} + return this; -/** - * Port from https://github.com/mapbox/earcut (v2.2.2) - */ + } -const Earcut = { + getCurrentLevel() { - triangulate: function ( data, holeIndices, dim ) { + return this._currentLevel; - dim = dim || 2; + } - const hasHoles = holeIndices && holeIndices.length; - const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; - let outerNode = linkedList( data, 0, outerLen, dim, true ); - const triangles = []; + getObjectForDistance( distance ) { - if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + const levels = this.levels; - let minX, minY, maxX, maxY, x, y, invSize; + if ( levels.length > 0 ) { - if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + let i, l; - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if ( data.length > 80 * dim ) { + for ( i = 1, l = levels.length; i < l; i ++ ) { - minX = maxX = data[ 0 ]; - minY = maxY = data[ 1 ]; + if ( distance < levels[ i ].distance ) { - for ( let i = dim; i < outerLen; i += dim ) { + break; - x = data[ i ]; - y = data[ i + 1 ]; - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; + } } - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max( maxX - minX, maxY - minY ); - invSize = invSize !== 0 ? 1 / invSize : 0; + return levels[ i - 1 ].object; } - earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); - - return triangles; + return null; } -}; + raycast( raycaster, intersects ) { -// create a circular doubly linked list from polygon points in the specified winding order -function linkedList( data, start, end, dim, clockwise ) { + const levels = this.levels; - let i, last; + if ( levels.length > 0 ) { - if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { + _v1$2.setFromMatrixPosition( this.matrixWorld ); - for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + const distance = raycaster.ray.origin.distanceTo( _v1$2 ); - } else { + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + } } - if ( last && equals( last, last.next ) ) { + update( camera ) { - removeNode( last ); - last = last.next; + const levels = this.levels; - } + if ( levels.length > 1 ) { - return last; + _v1$2.setFromMatrixPosition( camera.matrixWorld ); + _v2$1.setFromMatrixPosition( this.matrixWorld ); -} + const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom; -// eliminate colinear or duplicate points -function filterPoints( start, end ) { + levels[ 0 ].object.visible = true; - if ( ! start ) return start; - if ( ! end ) end = start; + let i, l; - let p = start, - again; - do { + for ( i = 1, l = levels.length; i < l; i ++ ) { - again = false; + if ( distance >= levels[ i ].distance ) { - if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - removeNode( p ); - p = end = p.prev; - if ( p === p.next ) break; - again = true; + } else { - } else { + break; - p = p.next; + } - } + } - } while ( again || p !== end ); + this._currentLevel = i - 1; - return end; + for ( ; i < l; i ++ ) { -} + levels[ i ].object.visible = false; -// main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { + } - if ( ! ear ) return; + } - // interlink polygon nodes in z-order - if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); + } - let stop = ear, - prev, next; + toJSON( meta ) { - // iterate through ears, slicing them one by one - while ( ear.prev !== ear.next ) { + const data = super.toJSON( meta ); - prev = ear.prev; - next = ear.next; + if ( this.autoUpdate === false ) data.object.autoUpdate = false; - if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + data.object.levels = []; - // cut off the triangle - triangles.push( prev.i / dim ); - triangles.push( ear.i / dim ); - triangles.push( next.i / dim ); + const levels = this.levels; - removeNode( ear ); + for ( let i = 0, l = levels.length; i < l; i ++ ) { - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; + const level = levels[ i ]; - continue; + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); } - ear = next; - - // if we looped through the whole remaining polygon and can't find any more ears - if ( ear === stop ) { + return data; - // try filtering points and slicing again - if ( ! pass ) { + } - earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); +} - // if this didn't work, try curing all small self-intersections locally +const _basePosition = /*@__PURE__*/ new Vector3(); - } else if ( pass === 1 ) { +const _skinIndex = /*@__PURE__*/ new Vector4(); +const _skinWeight = /*@__PURE__*/ new Vector4(); - ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); - earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); +const _vector$5 = /*@__PURE__*/ new Vector3(); +const _matrix = /*@__PURE__*/ new Matrix4(); - // as a last resort, try splitting the remaining polygon into two +class SkinnedMesh extends Mesh { - } else if ( pass === 2 ) { + constructor( geometry, material ) { - splitEarcut( ear, triangles, dim, minX, minY, invSize ); + super( geometry, material ); - } + this.isSkinnedMesh = true; - break; + this.type = 'SkinnedMesh'; - } + this.bindMode = 'attached'; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); } -} - -// check whether a polygon node forms a valid ear with adjacent nodes -function isEar( ear ) { - - const a = ear.prev, - b = ear, - c = ear.next; - - if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - - // now make sure we don't have other points inside the potential ear - let p = ear.next.next; - - while ( p !== ear.prev ) { + copy( source, recursive ) { - if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) return false; - p = p.next; + super.copy( source, recursive ); - } + this.bindMode = source.bindMode; + this.bindMatrix.copy( source.bindMatrix ); + this.bindMatrixInverse.copy( source.bindMatrixInverse ); - return true; + this.skeleton = source.skeleton; -} + return this; -function isEarHashed( ear, minX, minY, invSize ) { + } - const a = ear.prev, - b = ear, - c = ear.next; + bind( skeleton, bindMatrix ) { - if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + this.skeleton = skeleton; - // triangle bbox; min & max are calculated like this for speed - const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), - minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), - maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), - maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); + if ( bindMatrix === undefined ) { - // z-order range for the current triangle bbox; - const minZ = zOrder( minTX, minTY, minX, minY, invSize ), - maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); + this.updateMatrixWorld( true ); - let p = ear.prevZ, - n = ear.nextZ; + this.skeleton.calculateInverses(); - // look for points inside the triangle in both directions - while ( p && p.z >= minZ && n && n.z <= maxZ ) { + bindMatrix = this.matrixWorld; - if ( p !== ear.prev && p !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) return false; - p = p.prevZ; + } - if ( n !== ear.prev && n !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && - area( n.prev, n, n.next ) >= 0 ) return false; - n = n.nextZ; + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.copy( bindMatrix ).invert(); } - // look for remaining points in decreasing z-order - while ( p && p.z >= minZ ) { + pose() { - if ( p !== ear.prev && p !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) return false; - p = p.prevZ; + this.skeleton.pose(); } - // look for remaining points in increasing z-order - while ( n && n.z <= maxZ ) { + normalizeSkinWeights() { - if ( n !== ear.prev && n !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && - area( n.prev, n, n.next ) >= 0 ) return false; - n = n.nextZ; + const vector = new Vector4(); - } + const skinWeight = this.geometry.attributes.skinWeight; - return true; + for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { -} + vector.fromBufferAttribute( skinWeight, i ); -// go through all polygon nodes and cure small local self-intersections -function cureLocalIntersections( start, triangles, dim ) { + const scale = 1.0 / vector.manhattanLength(); - let p = start; - do { + if ( scale !== Infinity ) { - const a = p.prev, - b = p.next.next; + vector.multiplyScalar( scale ); - if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + } else { - triangles.push( a.i / dim ); - triangles.push( p.i / dim ); - triangles.push( b.i / dim ); + vector.set( 1, 0, 0, 0 ); // do something reasonable - // remove two nodes involved - removeNode( p ); - removeNode( p.next ); + } - p = start = b; + skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); } - p = p.next; + } - } while ( p !== start ); + updateMatrixWorld( force ) { - return filterPoints( p ); + super.updateMatrixWorld( force ); -} + if ( this.bindMode === 'attached' ) { -// try splitting polygon into two and triangulate them independently -function splitEarcut( start, triangles, dim, minX, minY, invSize ) { + this.bindMatrixInverse.copy( this.matrixWorld ).invert(); - // look for a valid diagonal that divides the polygon into two - let a = start; - do { + } else if ( this.bindMode === 'detached' ) { - let b = a.next.next; - while ( b !== a.prev ) { + this.bindMatrixInverse.copy( this.bindMatrix ).invert(); - if ( a.i !== b.i && isValidDiagonal( a, b ) ) { + } else { - // split the polygon in two by the diagonal - let c = splitPolygon( a, b ); + console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); - // filter colinear points around the cuts - a = filterPoints( a, a.next ); - c = filterPoints( c, c.next ); + } - // run earcut on each half - earcutLinked( a, triangles, dim, minX, minY, invSize ); - earcutLinked( c, triangles, dim, minX, minY, invSize ); - return; + } - } + boneTransform( index, target ) { - b = b.next; + const skeleton = this.skeleton; + const geometry = this.geometry; - } + _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); + _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); - a = a.next; + _basePosition.copy( target ).applyMatrix4( this.bindMatrix ); - } while ( a !== start ); + target.set( 0, 0, 0 ); -} + for ( let i = 0; i < 4; i ++ ) { -// link every hole into the outer loop, producing a single-ring polygon without holes -function eliminateHoles( data, holeIndices, outerNode, dim ) { + const weight = _skinWeight.getComponent( i ); - const queue = []; - let i, len, start, end, list; + if ( weight !== 0 ) { - for ( i = 0, len = holeIndices.length; i < len; i ++ ) { + const boneIndex = _skinIndex.getComponent( i ); - start = holeIndices[ i ] * dim; - end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; - list = linkedList( data, start, end, dim, false ); - if ( list === list.next ) list.steiner = true; - queue.push( getLeftmost( list ) ); + _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); - } + target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight ); - queue.sort( compareX ); + } - // process holes from left to right - for ( i = 0; i < queue.length; i ++ ) { + } - eliminateHole( queue[ i ], outerNode ); - outerNode = filterPoints( outerNode, outerNode.next ); + return target.applyMatrix4( this.bindMatrixInverse ); } - return outerNode; - } -function compareX( a, b ) { +class Bone extends Object3D { - return a.x - b.x; + constructor() { + + super(); + + this.isBone = true; + + this.type = 'Bone'; + + } } -// find a bridge between vertices that connects hole with an outer ring and and link it -function eliminateHole( hole, outerNode ) { +class DataTexture extends Texture { - outerNode = findHoleBridge( hole, outerNode ); - if ( outerNode ) { + constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) { - const b = splitPolygon( outerNode, hole ); + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - // filter collinear points around the cuts - filterPoints( outerNode, outerNode.next ); - filterPoints( b, b.next ); + this.isDataTexture = true; + + this.image = { data: data, width: width, height: height }; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; } } -// David Eberly's algorithm for finding a bridge between hole and outer polygon -function findHoleBridge( hole, outerNode ) { +const _offsetMatrix = /*@__PURE__*/ new Matrix4(); +const _identityMatrix = /*@__PURE__*/ new Matrix4(); - let p = outerNode; - const hx = hole.x; - const hy = hole.y; - let qx = - Infinity, m; +class Skeleton { - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { + constructor( bones = [], boneInverses = [] ) { - if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { + this.uuid = generateUUID(); - const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); - if ( x <= hx && x > qx ) { + this.bones = bones.slice( 0 ); + this.boneInverses = boneInverses; + this.boneMatrices = null; - qx = x; - if ( x === hx ) { + this.boneTexture = null; + this.boneTextureSize = 0; - if ( hy === p.y ) return p; - if ( hy === p.next.y ) return p.next; + this.frame = - 1; - } + this.init(); - m = p.x < p.next.x ? p : p.next; + } - } + init() { - } + const bones = this.bones; + const boneInverses = this.boneInverses; - p = p.next; + this.boneMatrices = new Float32Array( bones.length * 16 ); - } while ( p !== outerNode ); + // calculate inverse bone matrices if necessary - if ( ! m ) return null; + if ( boneInverses.length === 0 ) { - if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint + this.calculateInverses(); - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point + } else { - const stop = m, - mx = m.x, - my = m.y; - let tanMin = Infinity, tan; + // handle special case - p = m; + if ( bones.length !== boneInverses.length ) { - do { + console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' ); - if ( hx >= p.x && p.x >= mx && hx !== p.x && - pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { + this.boneInverses = []; - tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { + this.boneInverses.push( new Matrix4() ); - m = p; - tanMin = tan; + } } } - p = p.next; - - } while ( p !== stop ); + } - return m; + calculateInverses() { -} + this.boneInverses.length = 0; -// whether sector in vertex m contains sector in vertex p in the same coordinates -function sectorContainsSector( m, p ) { + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; + const inverse = new Matrix4(); -} + if ( this.bones[ i ] ) { -// interlink polygon nodes in z-order -function indexCurve( start, minX, minY, invSize ) { + inverse.copy( this.bones[ i ].matrixWorld ).invert(); - let p = start; - do { + } - if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; + this.boneInverses.push( inverse ); - } while ( p !== start ); + } - p.prevZ.nextZ = null; - p.prevZ = null; + } - sortLinked( p ); + pose() { -} + // recover the bind-time world matrices -// Simon Tatham's linked list merge sort algorithm -// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html -function sortLinked( list ) { + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - let i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; + const bone = this.bones[ i ]; - do { + if ( bone ) { - p = list; - list = null; - tail = null; - numMerges = 0; + bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); - while ( p ) { + } - numMerges ++; - q = p; - pSize = 0; - for ( i = 0; i < inSize; i ++ ) { + } - pSize ++; - q = q.nextZ; - if ( ! q ) break; + // compute the local matrices, positions, rotations and scales - } + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - qSize = inSize; + const bone = this.bones[ i ]; - while ( pSize > 0 || ( qSize > 0 && q ) ) { + if ( bone ) { - if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { + if ( bone.parent && bone.parent.isBone ) { - e = p; - p = p.nextZ; - pSize --; + bone.matrix.copy( bone.parent.matrixWorld ).invert(); + bone.matrix.multiply( bone.matrixWorld ); } else { - e = q; - q = q.nextZ; - qSize --; + bone.matrix.copy( bone.matrixWorld ); } - if ( tail ) tail.nextZ = e; - else list = e; - - e.prevZ = tail; - tail = e; + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); } - p = q; - } - tail.nextZ = null; - inSize *= 2; + } - } while ( numMerges > 1 ); + update() { - return list; + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; -} + // flatten bone matrices to array -// z-order of a point given coords and inverse of the longer side of data bbox -function zOrder( x, y, minX, minY, invSize ) { + for ( let i = 0, il = bones.length; i < il; i ++ ) { - // coords are transformed into non-negative 15-bit integer range - x = 32767 * ( x - minX ) * invSize; - y = 32767 * ( y - minY ) * invSize; + // compute the offset between the current and the original transform - x = ( x | ( x << 8 ) ) & 0x00FF00FF; - x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; - x = ( x | ( x << 2 ) ) & 0x33333333; - x = ( x | ( x << 1 ) ) & 0x55555555; + const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; - y = ( y | ( y << 8 ) ) & 0x00FF00FF; - y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; - y = ( y | ( y << 2 ) ) & 0x33333333; - y = ( y | ( y << 1 ) ) & 0x55555555; + _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + _offsetMatrix.toArray( boneMatrices, i * 16 ); - return x | ( y << 1 ); + } -} + if ( boneTexture !== null ) { -// find the leftmost node of a polygon ring -function getLeftmost( start ) { + boneTexture.needsUpdate = true; - let p = start, - leftmost = start; - do { + } - if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; - p = p.next; + } - } while ( p !== start ); + clone() { - return leftmost; + return new Skeleton( this.bones, this.boneInverses ); -} + } -// check if a point lies within a convex triangle -function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { + computeBoneTexture() { - return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && - ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && - ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; + // 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) -} + let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = ceilPowerOfTwo( size ); + size = Math.max( size, 4 ); -// check if a diagonal between two polygon nodes is valid (lies in polygon interior) -function isValidDiagonal( a, b ) { + const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( this.boneMatrices ); // copy current values - return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges - ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible - ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors - equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + boneTexture.needsUpdate = true; -} + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + this.boneTextureSize = size; -// signed area of a triangle -function area( p, q, r ) { + return this; - return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); + } -} + getBoneByName( name ) { -// check if two points are equal -function equals( p1, p2 ) { + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - return p1.x === p2.x && p1.y === p2.y; + const bone = this.bones[ i ]; -} + if ( bone.name === name ) { -// check if two segments intersect -function intersects( p1, q1, p2, q2 ) { + return bone; - const o1 = sign( area( p1, q1, p2 ) ); - const o2 = sign( area( p1, q1, q2 ) ); - const o3 = sign( area( p2, q2, p1 ) ); - const o4 = sign( area( p2, q2, q1 ) ); + } - if ( o1 !== o2 && o3 !== o4 ) return true; // general case + } - if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 - if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 - if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 - if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + return undefined; - return false; + } -} + dispose( ) { -// for collinear points p, q, r, check if point q lies on segment pr -function onSegment( p, q, r ) { + if ( this.boneTexture !== null ) { - return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); + this.boneTexture.dispose(); -} + this.boneTexture = null; -function sign( num ) { + } - return num > 0 ? 1 : num < 0 ? - 1 : 0; + } -} + fromJSON( json, bones ) { -// check if a polygon diagonal intersects any polygon segments -function intersectsPolygon( a, b ) { + this.uuid = json.uuid; - let p = a; - do { + for ( let i = 0, l = json.bones.length; i < l; i ++ ) { - if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects( p, p.next, a, b ) ) return true; - p = p.next; + const uuid = json.bones[ i ]; + let bone = bones[ uuid ]; - } while ( p !== a ); + if ( bone === undefined ) { - return false; + console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid ); + bone = new Bone(); -} + } -// check if a polygon diagonal is locally inside the polygon -function locallyInside( a, b ) { + this.bones.push( bone ); + this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); - return area( a.prev, a, a.next ) < 0 ? - area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : - area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; + } -} + this.init(); -// check if the middle point of a polygon diagonal is inside the polygon -function middleInside( a, b ) { + return this; - let p = a, - inside = false; - const px = ( a.x + b.x ) / 2, - py = ( a.y + b.y ) / 2; - do { + } - if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && - ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) - inside = ! inside; - p = p.next; + toJSON() { - } while ( p !== a ); + const data = { + metadata: { + version: 4.5, + type: 'Skeleton', + generator: 'Skeleton.toJSON' + }, + bones: [], + boneInverses: [] + }; - return inside; + data.uuid = this.uuid; -} + const bones = this.bones; + const boneInverses = this.boneInverses; -// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; -// if one belongs to the outer ring and another to a hole, it merges it into a single ring -function splitPolygon( a, b ) { + for ( let i = 0, l = bones.length; i < l; i ++ ) { - const a2 = new Node( a.i, a.x, a.y ), - b2 = new Node( b.i, b.x, b.y ), - an = a.next, - bp = b.prev; + const bone = bones[ i ]; + data.bones.push( bone.uuid ); - a.next = b; - b.prev = a; + const boneInverse = boneInverses[ i ]; + data.boneInverses.push( boneInverse.toArray() ); - a2.next = an; - an.prev = a2; + } + + return data; + + } + +} - b2.next = a2; - a2.prev = b2; +class InstancedBufferAttribute extends BufferAttribute { - bp.next = b2; - b2.prev = bp; + constructor( array, itemSize, normalized, meshPerAttribute = 1 ) { - return b2; + super( array, itemSize, normalized ); -} + this.isInstancedBufferAttribute = true; -// create a node and optionally link it with previous one (in a circular doubly linked list) -function insertNode( i, x, y, last ) { + this.meshPerAttribute = meshPerAttribute; - const p = new Node( i, x, y ); + } - if ( ! last ) { + copy( source ) { - p.prev = p; - p.next = p; + super.copy( source ); - } else { + this.meshPerAttribute = source.meshPerAttribute; - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; + return this; } - return p; + toJSON() { -} + const data = super.toJSON(); -function removeNode( p ) { + data.meshPerAttribute = this.meshPerAttribute; - p.next.prev = p.prev; - p.prev.next = p.next; + data.isInstancedBufferAttribute = true; - if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; - if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; + return data; -} + } -function Node( i, x, y ) { +} - // vertex index in coordinates array - this.i = i; +const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); +const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); - // vertex coordinates - this.x = x; - this.y = y; +const _instanceIntersects = []; - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; +const _mesh = /*@__PURE__*/ new Mesh(); - // z-order curve value - this.z = null; +class InstancedMesh extends Mesh { - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; + constructor( geometry, material, count ) { - // indicates whether this is a steiner point - this.steiner = false; + super( geometry, material ); -} + this.isInstancedMesh = true; -function signedArea( data, start, end, dim ) { + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); + this.instanceColor = null; - let sum = 0; - for ( let i = start, j = end - dim; i < end; i += dim ) { + this.count = count; - sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); - j = i; + this.frustumCulled = false; } - return sum; + copy( source, recursive ) { -} + super.copy( source, recursive ); -const ShapeUtils = { + this.instanceMatrix.copy( source.instanceMatrix ); - // calculate area of the contour polygon + if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); - area: function ( contour ) { + this.count = source.count; - const n = contour.length; - let a = 0.0; + return this; - for ( let p = n - 1, q = 0; q < n; p = q ++ ) { + } - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + getColorAt( index, color ) { - } + color.fromArray( this.instanceColor.array, index * 3 ); - return a * 0.5; + } - }, + getMatrixAt( index, matrix ) { - isClockWise: function ( pts ) { + matrix.fromArray( this.instanceMatrix.array, index * 16 ); - return ShapeUtils.area( pts ) < 0; + } - }, + raycast( raycaster, intersects ) { - triangulateShape: function ( contour, holes ) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; - const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] - const holeIndices = []; // array of hole indices - const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + _mesh.geometry = this.geometry; + _mesh.material = this.material; - removeDupEndPts( contour ); - addContour( vertices, contour ); + if ( _mesh.material === undefined ) return; - // + for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { - let holeIndex = contour.length; + // calculate the world matrix for each instance - holes.forEach( removeDupEndPts ); + this.getMatrixAt( instanceId, _instanceLocalMatrix ); - for ( let i = 0; i < holes.length; i ++ ) { + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); - holeIndices.push( holeIndex ); - holeIndex += holes[ i ].length; - addContour( vertices, holes[ i ] ); + // the mesh represents this single instance - } + _mesh.matrixWorld = _instanceWorldMatrix; - // + _mesh.raycast( raycaster, _instanceIntersects ); - const triangles = Earcut.triangulate( vertices, holeIndices ); + // process the result of raycast - // + for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { - for ( let i = 0; i < triangles.length; i += 3 ) { + const intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); - faces.push( triangles.slice( i, i + 3 ) ); + } - } + _instanceIntersects.length = 0; - return faces; + } } -}; + setColorAt( index, color ) { -function removeDupEndPts( points ) { + if ( this.instanceColor === null ) { - const l = points.length; + this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 ); - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + } - points.pop(); + color.toArray( this.instanceColor.array, index * 3 ); } -} + setMatrixAt( index, matrix ) { -function addContour( vertices, contour ) { + matrix.toArray( this.instanceMatrix.array, index * 16 ); - for ( let i = 0; i < contour.length; i ++ ) { + } - vertices.push( contour[ i ].x ); - vertices.push( contour[ i ].y ); + updateMorphTargets() { } -} + dispose() { -/** - * 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 - * depth: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline (including bevelOffset) is bevel - * bevelOffset: , // how far from shape outline does bevel start - * bevelSegments: , // number of bevel layers - * - * extrudePath: // curve to extrude shape along - * - * UVGenerator: // object that provides UV generator functions - * - * } - */ + this.dispatchEvent( { type: 'dispose' } ); -class ExtrudeGeometry extends BufferGeometry { + } - constructor( shapes, options ) { +} + +class LineBasicMaterial extends Material { + + constructor( parameters ) { super(); - this.type = 'ExtrudeGeometry'; + this.isLineBasicMaterial = true; - this.parameters = { - shapes: shapes, - options: options - }; + this.type = 'LineBasicMaterial'; - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + this.color = new Color( 0xffffff ); - const scope = this; + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - const verticesArray = []; - const uvArray = []; + this.fog = true; - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + this.setValues( parameters ); - const shape = shapes[ i ]; - addShape( shape ); + } - } - // build geometry + copy( source ) { - this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + super.copy( source ); - this.computeVertexNormals(); + this.color.copy( source.color ); - // functions + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - function addShape( shape ) { + this.fog = source.fog; - const placeholder = []; + return this; - // options + } - const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - const steps = options.steps !== undefined ? options.steps : 1; - let depth = options.depth !== undefined ? options.depth : 100; +} - let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; - let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; - let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; - let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; - let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; +const _start$1 = /*@__PURE__*/ new Vector3(); +const _end$1 = /*@__PURE__*/ new Vector3(); +const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _ray$1 = /*@__PURE__*/ new Ray(); +const _sphere$1 = /*@__PURE__*/ new Sphere(); - const extrudePath = options.extrudePath; +class Line extends Object3D { - const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { - // deprecated options + super(); - if ( options.amount !== undefined ) { + this.isLine = true; - console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' ); - depth = options.amount; + this.type = 'Line'; - } + this.geometry = geometry; + this.material = material; - // + this.updateMorphTargets(); - let extrudePts, extrudeByPath = false; - let splineTube, binormal, normal, position2; + } - if ( extrudePath ) { + copy( source, recursive ) { - extrudePts = extrudePath.getSpacedPoints( steps ); + super.copy( source, recursive ); - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + this.material = source.material; + this.geometry = source.geometry; - // SETUP TNB variables + return this; - // TODO1 - have a .isClosed in spline? + } - splineTube = extrudePath.computeFrenetFrames( steps, false ); + computeLineDistances() { - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + const geometry = this.geometry; - binormal = new Vector3(); - normal = new Vector3(); - position2 = new Vector3(); + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - // Safeguards if bevels are not enabled + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; - if ( ! bevelEnabled ) { + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; - bevelOffset = 0; + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); } - // Variables initialization + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - const shapePoints = shape.extractPoints( curveSegments ); + } else { - let vertices = shapePoints.shape; - const holes = shapePoints.holes; + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); - const reverse = ! ShapeUtils.isClockWise( vertices ); + } - if ( reverse ) { + return this; - vertices = vertices.reverse(); + } - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + raycast( raycaster, intersects ) { - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; - const ahole = holes[ h ]; + // Checking boundingSphere distance to ray - if ( ShapeUtils.isClockWise( ahole ) ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - holes[ h ] = ahole.reverse(); + _sphere$1.copy( geometry.boundingSphere ); + _sphere$1.applyMatrix4( matrixWorld ); + _sphere$1.radius += threshold; - } + if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return; - } + // - } + _inverseMatrix$1.copy( matrixWorld ).invert(); + _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; - const faces = ShapeUtils.triangulateShape( vertices, holes ); + const vStart = new Vector3(); + const vEnd = new Vector3(); + const interSegment = new Vector3(); + const interRay = new Vector3(); + const step = this.isLineSegments ? 2 : 1; - /* Vertices */ + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - const contour = vertices; // vertices has all points but contour has only points of circumference + if ( index !== null ) { - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const ahole = holes[ h ]; + for ( let i = start, l = end - 1; i < l; i += step ) { - vertices = vertices.concat( ahole ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); - } + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - function scalePt2( pt, vec, size ) { + if ( distSq > localThresholdSq ) continue; - if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - return vec.clone().multiplyScalar( size ).add( pt ); + const distance = raycaster.ray.origin.distanceTo( interRay ); - } + if ( distance < raycaster.near || distance > raycaster.far ) continue; - const vlen = vertices.length, flen = faces.length; + intersects.push( { + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - // Find directions for point movement + } ); + } - function getBevelVec( inPt, inPrev, inNext ) { + } else { - // 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. + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + for ( let i = start, l = end - 1; i < l; i += step ) { - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); - const v_prev_x = inPt.x - inPrev.x, - v_prev_y = inPt.y - inPrev.y; - const v_next_x = inNext.x - inPt.x, - v_next_y = inNext.y - inPt.y; + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + if ( distSq > localThresholdSq ) continue; - // check for collinear edges - const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + const distance = raycaster.ray.origin.distanceTo( interRay ); - // not collinear + if ( distance < raycaster.near || distance > raycaster.far ) continue; - // length of vectors for normalizing + intersects.push( { - const v_prev_len = Math.sqrt( v_prev_lensq ); - const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + 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 - // shift adjacent points by unit vectors to the left + } ); - const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + } - const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + } - // scaling factor for v_prev to intersection point + } - const 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 ); + updateMorphTargets() { - // vector from inPt to intersection point + const geometry = this.geometry; - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); - if ( v_trans_lensq <= 2 ) { + if ( keys.length > 0 ) { - return new Vector2( v_trans_x, v_trans_y ); + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - } else { + if ( morphAttribute !== undefined ) { - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - } + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - } else { + const name = morphAttribute[ m ].name || String( m ); - // handle special case of collinear edges + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; - let direction_eq = false; // assumes: opposite + } - if ( v_prev_x > Number.EPSILON ) { + } - if ( v_next_x > Number.EPSILON ) { + } - direction_eq = true; + } - } +} - } else { +const _start = /*@__PURE__*/ new Vector3(); +const _end = /*@__PURE__*/ new Vector3(); - if ( v_prev_x < - Number.EPSILON ) { +class LineSegments extends Line { - if ( v_next_x < - Number.EPSILON ) { + constructor( geometry, material ) { - direction_eq = true; + super( geometry, material ); - } + this.isLineSegments = true; - } else { + this.type = 'LineSegments'; - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + } - direction_eq = true; + computeLineDistances() { - } + const geometry = this.geometry; - } + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - if ( direction_eq ) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; - // 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 ); + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { - } else { + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); - // 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 ); + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); - } + } - } + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + } else { - } + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + } - const contourMovements = []; + return this; - for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + } - if ( j === il ) j = 0; - if ( k === il ) k = 0; +} - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) +class LineLoop extends Line { - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + constructor( geometry, material ) { - } + super( geometry, material ); - const holesMovements = []; - let oneHoleMovements, verticesMovements = contourMovements.concat(); + this.isLineLoop = true; - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + this.type = 'LineLoop'; - const ahole = holes[ h ]; + } - oneHoleMovements = []; +} - for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { +class PointsMaterial extends Material { - if ( j === il ) j = 0; - if ( k === il ) k = 0; + constructor( parameters ) { - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + super(); - } + this.isPointsMaterial = true; - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + this.type = 'PointsMaterial'; - } + this.color = new Color( 0xffffff ); + this.map = null; - // Loop bevelSegments, 1 for the front, 1 for the back + this.alphaMap = null; - for ( let b = 0; b < bevelSegments; b ++ ) { + this.size = 1; + this.sizeAttenuation = true; - //for ( b = bevelSegments; b > 0; b -- ) { + this.fog = true; - const t = b / bevelSegments; - const z = bevelThickness * Math.cos( t * Math.PI / 2 ); - const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + this.setValues( parameters ); - // contract shape + } - for ( let i = 0, il = contour.length; i < il; i ++ ) { + copy( source ) { - const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + super.copy( source ); - v( vert.x, vert.y, - z ); + this.color.copy( source.color ); - } + this.map = source.map; - // expand holes + this.alphaMap = source.alphaMap; - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - const ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + this.fog = source.fog; - for ( let i = 0, il = ahole.length; i < il; i ++ ) { + return this; - const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + } - v( vert.x, vert.y, - z ); +} - } +const _inverseMatrix = /*@__PURE__*/ new Matrix4(); +const _ray = /*@__PURE__*/ new Ray(); +const _sphere = /*@__PURE__*/ new Sphere(); +const _position$2 = /*@__PURE__*/ new Vector3(); - } +class Points extends Object3D { - } + constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) { - const bs = bevelSize + bevelOffset; + super(); - // Back facing vertices + this.isPoints = true; - for ( let i = 0; i < vlen; i ++ ) { + this.type = 'Points'; - const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + this.geometry = geometry; + this.material = material; - if ( ! extrudeByPath ) { + this.updateMorphTargets(); - v( vert.x, vert.y, 0 ); + } - } else { + copy( source, recursive ) { - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + super.copy( source, recursive ); - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + this.material = source.material; + this.geometry = source.geometry; - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + return this; - v( position2.x, position2.y, position2.z ); + } - } + raycast( raycaster, intersects ) { - } + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; - // Add stepped vertices... - // Including front facing vertices + // Checking boundingSphere distance to ray - for ( let s = 1; s <= steps; s ++ ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - for ( let i = 0; i < vlen; i ++ ) { + _sphere.copy( geometry.boundingSphere ); + _sphere.applyMatrix4( matrixWorld ); + _sphere.radius += threshold; - const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; - if ( ! extrudeByPath ) { + // + + _inverseMatrix.copy( matrixWorld ).invert(); + _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); - v( vert.x, vert.y, depth / steps * s ); + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; - } else { + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + if ( index !== null ) { - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + for ( let i = start, il = end; i < il; i ++ ) { - v( position2.x, position2.y, position2.z ); + const a = index.getX( i ); - } + _position$2.fromBufferAttribute( positionAttribute, a ); - } + testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); } + } else { - // Add bevel segments planes - - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( let b = bevelSegments - 1; b >= 0; b -- ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - const t = b / bevelSegments; - const z = bevelThickness * Math.cos( t * Math.PI / 2 ); - const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + for ( let i = start, l = end; i < l; i ++ ) { - // contract shape + _position$2.fromBufferAttribute( positionAttribute, i ); - for ( let i = 0, il = contour.length; i < il; i ++ ) { + testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); - const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, depth + z ); + } - } + } - // expand holes + } - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + updateMorphTargets() { - const ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + const geometry = this.geometry; - for ( let i = 0, il = ahole.length; i < il; i ++ ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + if ( keys.length > 0 ) { - if ( ! extrudeByPath ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - v( vert.x, vert.y, depth + z ); + if ( morphAttribute !== undefined ) { - } else { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - } + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - /* Faces */ - - // Top and bottom faces - - buildLidFaces(); - - // Sides faces - - buildSideFaces(); + } + } - ///// Internal functions +} - function buildLidFaces() { +function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { - const start = verticesArray.length / 3; + const rayPointDistanceSq = _ray.distanceSqToPoint( point ); - if ( bevelEnabled ) { + if ( rayPointDistanceSq < localThresholdSq ) { - let layer = 0; // steps + 1 - let offset = vlen * layer; + const intersectPoint = new Vector3(); - // Bottom faces + _ray.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); - for ( let i = 0; i < flen; i ++ ) { + const distance = raycaster.ray.origin.distanceTo( intersectPoint ); - const face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + if ( distance < raycaster.near || distance > raycaster.far ) return; - } + intersects.push( { - layer = steps + bevelSegments * 2; - offset = vlen * layer; + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + object: object - // Top faces + } ); - for ( let i = 0; i < flen; i ++ ) { + } - const face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); +} - } +class VideoTexture extends Texture { - } else { + constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - // Bottom faces + super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - for ( let i = 0; i < flen; i ++ ) { + this.isVideoTexture = true; - const face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; - } + this.generateMipmaps = false; - // Top faces + const scope = this; - for ( let i = 0; i < flen; i ++ ) { + function updateVideo() { - const face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + scope.needsUpdate = true; + video.requestVideoFrameCallback( updateVideo ); - } + } - } + if ( 'requestVideoFrameCallback' in video ) { - scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + video.requestVideoFrameCallback( updateVideo ); - } + } - // Create faces for the z-sides of the shape + } - function buildSideFaces() { + clone() { - const start = verticesArray.length / 3; - let layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + return new this.constructor( this.image ).copy( this ); - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + } - const ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + update() { - //, true - layeroffset += ahole.length; + const video = this.image; + const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; - } + if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { + this.needsUpdate = true; - scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + } + } - } +} - function sidewalls( contour, layeroffset ) { +class FramebufferTexture extends Texture { - let i = contour.length; + constructor( width, height, format ) { - while ( -- i >= 0 ) { + super( { width, height } ); - const j = i; - let k = i - 1; - if ( k < 0 ) k = contour.length - 1; + this.isFramebufferTexture = true; - //console.log('b', i,j, i-1, k,vertices.length); + this.format = format; - for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; - const slen1 = vlen * s; - const slen2 = vlen * ( s + 1 ); + this.generateMipmaps = false; - const a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + this.needsUpdate = true; - f4( a, b, c, d ); + } - } +} - } +class CompressedTexture extends Texture { - } + constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - function v( x, y, z ) { + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - placeholder.push( x ); - placeholder.push( y ); - placeholder.push( z ); + this.isCompressedTexture = true; - } + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - function f3( a, b, c ) { + this.flipY = false; - addVertex( a ); - addVertex( b ); - addVertex( c ); + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files - const nextIndex = verticesArray.length / 3; - const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + this.generateMipmaps = false; - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); + } - } +} - function f4( a, b, c, d ) { +class CanvasTexture extends Texture { - addVertex( a ); - addVertex( b ); - addVertex( d ); + constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - addVertex( b ); - addVertex( c ); - addVertex( d ); + super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isCanvasTexture = true; - const nextIndex = verticesArray.length / 3; - const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + this.needsUpdate = true; - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 3 ] ); + } - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); - addUV( uvs[ 3 ] ); +} - } +/** + * Extensible curve object. + * + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following curves inherit from THREE.Curve: + * + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve + * + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * + * A series of curves can be represented as a THREE.CurvePath. + * + **/ - function addVertex( index ) { +class Curve { - verticesArray.push( placeholder[ index * 3 + 0 ] ); - verticesArray.push( placeholder[ index * 3 + 1 ] ); - verticesArray.push( placeholder[ index * 3 + 2 ] ); + constructor() { - } + this.type = 'Curve'; + this.arcLengthDivisions = 200; - function addUV( vector2 ) { + } - uvArray.push( vector2.x ); - uvArray.push( vector2.y ); + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] - } + getPoint( /* t, optionalTarget */ ) { - } + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; } - toJSON() { - - const data = BufferGeometry.prototype.toJSON.call( this ); + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - const shapes = this.parameters.shapes; - const options = this.parameters.options; + getPointAt( u, optionalTarget ) { - return toJSON( shapes, options, data ); + const t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); } -} + // Get sequence of points using getPoint( t ) -const WorldUVGenerator = { + getPoints( divisions = 5 ) { - generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + const points = []; - const a_x = vertices[ indexA * 3 ]; - const a_y = vertices[ indexA * 3 + 1 ]; - const b_x = vertices[ indexB * 3 ]; - const b_y = vertices[ indexB * 3 + 1 ]; - const c_x = vertices[ indexC * 3 ]; - const c_y = vertices[ indexC * 3 + 1 ]; + for ( let d = 0; d <= divisions; d ++ ) { - return [ - new Vector2( a_x, a_y ), - new Vector2( b_x, b_y ), - new Vector2( c_x, c_y ) - ]; + points.push( this.getPoint( d / divisions ) ); - }, + } - generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + return points; - const a_x = vertices[ indexA * 3 ]; - const a_y = vertices[ indexA * 3 + 1 ]; - const a_z = vertices[ indexA * 3 + 2 ]; - const b_x = vertices[ indexB * 3 ]; - const b_y = vertices[ indexB * 3 + 1 ]; - const b_z = vertices[ indexB * 3 + 2 ]; - const c_x = vertices[ indexC * 3 ]; - const c_y = vertices[ indexC * 3 + 1 ]; - const c_z = vertices[ indexC * 3 + 2 ]; - const d_x = vertices[ indexD * 3 ]; - const d_y = vertices[ indexD * 3 + 1 ]; - const d_z = vertices[ indexD * 3 + 2 ]; + } - if ( Math.abs( a_y - b_y ) < 0.01 ) { + // Get sequence of points using getPointAt( u ) - 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 ) - ]; + getSpacedPoints( divisions = 5 ) { - } else { + const points = []; - 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 ) - ]; + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPointAt( d / divisions ) ); } + return points; + } -}; + // Get total curve arc length -function toJSON( shapes, options, data ) { + getLength() { - data.shapes = []; + const lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - if ( Array.isArray( shapes ) ) { + } - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + // Get list of cumulative segment lengths - const shape = shapes[ i ]; + getLengths( divisions = this.arcLengthDivisions ) { - data.shapes.push( shape.uuid ); + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { + + return this.cacheArcLengths; } - } else { + this.needsUpdate = false; - data.shapes.push( shapes.uuid ); + const cache = []; + let current, last = this.getPoint( 0 ); + let sum = 0; - } + cache.push( 0 ); - if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); + for ( let p = 1; p <= divisions; p ++ ) { - return data; + current = this.getPoint( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; -} + } -class IcosahedronGeometry extends PolyhedronGeometry { + this.cacheArcLengths = cache; - constructor( radius = 1, detail = 0 ) { + return cache; // { sums: cache, sum: sum }; Sum is in the last element. - const t = ( 1 + Math.sqrt( 5 ) ) / 2; + } - const 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 - ]; + updateArcLengths() { - const 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 - ]; + this.needsUpdate = true; + this.getLengths(); - super( vertices, indices, radius, detail ); + } - this.type = 'IcosahedronGeometry'; + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - this.parameters = { - radius: radius, - detail: detail - }; + getUtoTmapping( u, distance ) { - } + const arcLengths = this.getLengths(); -} + let i = 0; + const il = arcLengths.length; -class LatheGeometry extends BufferGeometry { + let targetArcLength; // The targeted u distance value to get - constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { + if ( distance ) { - super(); + targetArcLength = distance; - this.type = 'LatheGeometry'; + } else { - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + targetArcLength = u * arcLengths[ il - 1 ]; - segments = Math.floor( segments ); + } - // clamp phiLength so it's in range of [ 0, 2PI ] + // binary search for the index with largest value smaller than target u distance - phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 ); + let low = 0, high = il - 1, comparison; - // buffers + while ( low <= high ) { - const indices = []; - const vertices = []; - const uvs = []; + 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 - // helper variables + comparison = arcLengths[ i ] - targetArcLength; - const inverseSegments = 1.0 / segments; - const vertex = new Vector3(); - const uv = new Vector2(); + if ( comparison < 0 ) { - // generate vertices and uvs + low = i + 1; - for ( let i = 0; i <= segments; i ++ ) { + } else if ( comparison > 0 ) { - const phi = phiStart + i * inverseSegments * phiLength; + high = i - 1; - const sin = Math.sin( phi ); - const cos = Math.cos( phi ); + } else { - for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { + high = i; + break; - // vertex + // DONE - vertex.x = points[ j ].x * sin; - vertex.y = points[ j ].y; - vertex.z = points[ j ].x * cos; + } - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // uv + i = high; - uv.x = i / segments; - uv.y = j / ( points.length - 1 ); + if ( arcLengths[ i ] === targetArcLength ) { - uvs.push( uv.x, uv.y ); + return i / ( il - 1 ); + } - } + // we could get finer grain at lengths, or use simple interpolation between two points - } + const lengthBefore = arcLengths[ i ]; + const lengthAfter = arcLengths[ i + 1 ]; - // indices + const segmentLength = lengthAfter - lengthBefore; - for ( let i = 0; i < segments; i ++ ) { + // determine where we are between the 'before' and 'after' points - for ( let j = 0; j < ( points.length - 1 ); j ++ ) { + const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - const base = j + i * points.length; + // add that fractional amount to t - const a = base; - const b = base + points.length; - const c = base + points.length + 1; - const d = base + 1; + const t = ( i + segmentFraction ) / ( il - 1 ); - // faces + return t; - indices.push( a, b, d ); - indices.push( b, c, d ); + } - } + // 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 - } + getTangent( t, optionalTarget ) { - // build geometry + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + // Capping in case of danger - // generate normals + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - this.computeVertexNormals(); + const pt1 = this.getPoint( t1 ); + const pt2 = this.getPoint( t2 ); - // 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). + const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + + tangent.copy( pt2 ).sub( pt1 ).normalize(); - if ( phiLength === Math.PI * 2 ) { + return tangent; - const normals = this.attributes.normal.array; - const n1 = new Vector3(); - const n2 = new Vector3(); - const n = new Vector3(); + } - // this is the buffer offset for the last line of vertices + getTangentAt( u, optionalTarget ) { - const base = segments * points.length * 3; + const t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); - for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) { + } - // select the normal of the vertex in the first line + computeFrenetFrames( segments, closed ) { - n1.x = normals[ j + 0 ]; - n1.y = normals[ j + 1 ]; - n1.z = normals[ j + 2 ]; + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf - // select the normal of the vertex in the last line + const normal = new Vector3(); - n2.x = normals[ base + j + 0 ]; - n2.y = normals[ base + j + 1 ]; - n2.z = normals[ base + j + 2 ]; + const tangents = []; + const normals = []; + const binormals = []; - // average normals + const vec = new Vector3(); + const mat = new Matrix4(); - n.addVectors( n1, n2 ).normalize(); + // compute the tangent vectors for each segment on the curve - // assign the new values to both normals + for ( let i = 0; i <= segments; i ++ ) { - 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; + const u = i / segments; - } + tangents[ i ] = this.getTangentAt( u, new Vector3() ); } - } + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component -} + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs( tangents[ 0 ].x ); + const ty = Math.abs( tangents[ 0 ].y ); + const tz = Math.abs( tangents[ 0 ].z ); -class OctahedronGeometry extends PolyhedronGeometry { + if ( tx <= min ) { - constructor( radius = 1, detail = 0 ) { + min = tx; + normal.set( 1, 0, 0 ); - const vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, - 0, - 1, 0, 0, 0, 1, 0, 0, - 1 - ]; + } - const 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 - ]; + if ( ty <= min ) { - super( vertices, indices, radius, detail ); + min = ty; + normal.set( 0, 1, 0 ); - this.type = 'OctahedronGeometry'; + } - this.parameters = { - radius: radius, - detail: detail - }; + if ( tz <= min ) { - } + normal.set( 0, 0, 1 ); -} + } -/** - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html - */ + vec.crossVectors( tangents[ 0 ], normal ).normalize(); -function ParametricGeometry( func, slices, stacks ) { + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - BufferGeometry.call( this ); - this.type = 'ParametricGeometry'; + // compute the slowly-varying normal and binormal vectors for each segment on the curve - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + for ( let i = 1; i <= segments; i ++ ) { - // buffers + normals[ i ] = normals[ i - 1 ].clone(); - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + binormals[ i ] = binormals[ i - 1 ].clone(); - const EPS = 0.00001; + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); - const normal = new Vector3(); + if ( vec.length() > Number.EPSILON ) { - const p0 = new Vector3(), p1 = new Vector3(); - const pu = new Vector3(), pv = new Vector3(); + vec.normalize(); - if ( func.length < 3 ) { + const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors - console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' ); + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - } + } - // generate vertices, normals and uvs + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - const sliceCount = slices + 1; + } - for ( let i = 0; i <= stacks; i ++ ) { + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - const v = i / stacks; + if ( closed === true ) { - for ( let j = 0; j <= slices; j ++ ) { + let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; - const u = j / slices; + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { - // vertex + theta = - theta; - func( u, v, p0 ); - vertices.push( p0.x, p0.y, p0.z ); + } - // normal + for ( let i = 1; i <= segments; i ++ ) { - // approximate tangent vectors via finite differences + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - if ( u - EPS >= 0 ) { + } - func( u - EPS, v, p1 ); - pu.subVectors( p0, p1 ); + } - } else { + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; - func( u + EPS, v, p1 ); - pu.subVectors( p1, p0 ); + } - } + clone() { - if ( v - EPS >= 0 ) { + return new this.constructor().copy( this ); - func( u, v - EPS, p1 ); - pv.subVectors( p0, p1 ); + } - } else { + copy( source ) { - func( u, v + EPS, p1 ); - pv.subVectors( p1, p0 ); + this.arcLengthDivisions = source.arcLengthDivisions; - } + return this; - // cross product of tangent vectors returns surface normal + } - normal.crossVectors( pu, pv ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + toJSON() { - // uv + const data = { + metadata: { + version: 4.5, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; - uvs.push( u, v ); + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; - } + return data; } - // generate indices - - for ( let i = 0; i < stacks; i ++ ) { + fromJSON( json ) { - for ( let j = 0; j < slices; j ++ ) { + this.arcLengthDivisions = json.arcLengthDivisions; - const a = i * sliceCount + j; - const b = i * sliceCount + j + 1; - const c = ( i + 1 ) * sliceCount + j + 1; - const d = ( i + 1 ) * sliceCount + j; + return this; - // faces one and two + } - indices.push( a, b, d ); - indices.push( b, c, d ); +} - } +class EllipseCurve extends Curve { - } + constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { - // build geometry + super(); - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.isEllipseCurve = true; -} + this.type = 'EllipseCurve'; -ParametricGeometry.prototype = Object.create( BufferGeometry.prototype ); -ParametricGeometry.prototype.constructor = ParametricGeometry; + this.aX = aX; + this.aY = aY; -class RingGeometry extends BufferGeometry { + this.xRadius = xRadius; + this.yRadius = yRadius; - constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; - super(); + this.aClockwise = aClockwise; - this.type = 'RingGeometry'; + this.aRotation = aRotation; - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - thetaSegments = Math.max( 3, thetaSegments ); - phiSegments = Math.max( 1, phiSegments ); + getPoint( t, optionalTarget ) { - // buffers + const point = optionalTarget || new Vector2(); - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - // some helper variables + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - let radius = innerRadius; - const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - const vertex = new Vector3(); - const uv = new Vector2(); + if ( deltaAngle < Number.EPSILON ) { - // generate vertices, normals and uvs + if ( samePoints ) { - for ( let j = 0; j <= phiSegments; j ++ ) { + deltaAngle = 0; - for ( let i = 0; i <= thetaSegments; i ++ ) { + } else { - // values are generate from the inside of the ring to the outside + deltaAngle = twoPi; - const segment = thetaStart + i / thetaSegments * thetaLength; + } - // vertex + } - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + if ( this.aClockwise === true && ! samePoints ) { - vertices.push( vertex.x, vertex.y, vertex.z ); + if ( deltaAngle === twoPi ) { - // normal + deltaAngle = - twoPi; - normals.push( 0, 0, 1 ); + } else { - // uv + deltaAngle = deltaAngle - twoPi; - uv.x = ( vertex.x / outerRadius + 1 ) / 2; - uv.y = ( vertex.y / outerRadius + 1 ) / 2; + } - uvs.push( uv.x, uv.y ); + } - } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos( angle ); + let y = this.aY + this.yRadius * Math.sin( angle ); - // increase the radius for next row of vertices + if ( this.aRotation !== 0 ) { - radius += radiusStep; + const cos = Math.cos( this.aRotation ); + const sin = Math.sin( this.aRotation ); - } + const tx = x - this.aX; + const ty = y - this.aY; - // indices + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; - for ( let j = 0; j < phiSegments; j ++ ) { + } - const thetaSegmentLevel = j * ( thetaSegments + 1 ); + return point.set( x, y ); - for ( let i = 0; i < thetaSegments; i ++ ) { + } - const segment = i + thetaSegmentLevel; + copy( source ) { - const a = segment; - const b = segment + thetaSegments + 1; - const c = segment + thetaSegments + 2; - const d = segment + 1; + super.copy( source ); - // faces + this.aX = source.aX; + this.aY = source.aY; - indices.push( a, b, d ); - indices.push( b, c, d ); + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; - } + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; - } + this.aClockwise = source.aClockwise; - // build geometry + this.aRotation = source.aRotation; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + return this; } -} - -class ShapeGeometry extends BufferGeometry { + toJSON() { - constructor( shapes, curveSegments = 12 ) { + const data = super.toJSON(); - super(); - this.type = 'ShapeGeometry'; + data.aX = this.aX; + data.aY = this.aY; - this.parameters = { - shapes: shapes, - curveSegments: curveSegments - }; + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; - // buffers + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + data.aClockwise = this.aClockwise; - // helper variables + data.aRotation = this.aRotation; - let groupStart = 0; - let groupCount = 0; + return data; - // allow single and array values for "shapes" parameter + } - if ( Array.isArray( shapes ) === false ) { + fromJSON( json ) { - addShape( shapes ); + super.fromJSON( json ); - } else { + this.aX = json.aX; + this.aY = json.aY; - for ( let i = 0; i < shapes.length; i ++ ) { + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; - addShape( shapes[ i ] ); + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; - this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + this.aClockwise = json.aClockwise; - groupStart += groupCount; - groupCount = 0; + this.aRotation = json.aRotation; - } + return this; - } + } - // build geometry +} - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); +class ArcCurve extends EllipseCurve { + constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - // helper functions + super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - function addShape( shape ) { + this.isArcCurve = true; - const indexOffset = vertices.length / 3; - const points = shape.extractPoints( curveSegments ); + this.type = 'ArcCurve'; - let shapeVertices = points.shape; - const shapeHoles = points.holes; + } - // check direction of vertices +} - if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { +/** + * 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 + */ - shapeVertices = shapeVertices.reverse(); - } +/* +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 - for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { +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. +*/ - const shapeHole = shapeHoles[ i ]; +function CubicPoly() { - if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; - shapeHoles[ i ] = shapeHole.reverse(); + /* + * 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. + */ + function init( x0, x1, t0, t1 ) { - } + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; - } + } - const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); + return { - // join vertices of inner and outer paths to a single array + initCatmullRom: function ( x0, x1, x2, x3, tension ) { - for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); - const shapeHole = shapeHoles[ i ]; - shapeVertices = shapeVertices.concat( shapeHole ); + }, - } + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { - // vertices, normals, uvs + // compute tangents when parameterized in [t1,t2] + let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; - const vertex = shapeVertices[ i ]; + init( x1, x2, t1, t2 ); - vertices.push( vertex.x, vertex.y, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( vertex.x, vertex.y ); // world uvs + }, - } + calc: function ( t ) { - // incides + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; - for ( let i = 0, l = faces.length; i < l; i ++ ) { + } - const face = faces[ i ]; + }; - const a = face[ 0 ] + indexOffset; - const b = face[ 1 ] + indexOffset; - const c = face[ 2 ] + indexOffset; +} - indices.push( a, b, c ); - groupCount += 3; +// - } +const tmp = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); - } +class CatmullRomCurve3 extends Curve { - } + constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { - toJSON() { + super(); - const data = BufferGeometry.prototype.toJSON.call( this ); + this.isCatmullRomCurve3 = true; - const shapes = this.parameters.shapes; + this.type = 'CatmullRomCurve3'; - return toJSON$1( shapes, data ); + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; } -} + getPoint( t, optionalTarget = new Vector3() ) { -function toJSON$1( shapes, data ) { + const point = optionalTarget; - data.shapes = []; + const points = this.points; + const l = points.length; - if ( Array.isArray( shapes ) ) { + const p = ( l - ( this.closed ? 0 : 1 ) ) * t; + let intPoint = Math.floor( p ); + let weight = p - intPoint; - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + if ( this.closed ) { - const shape = shapes[ i ]; + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; - data.shapes.push( shape.uuid ); + } else if ( weight === 0 && intPoint === l - 1 ) { - } + intPoint = l - 2; + weight = 1; - } else { + } - data.shapes.push( shapes.uuid ); + let p0, p3; // 4 points (p1 & p2 defined below) - } + if ( this.closed || intPoint > 0 ) { - return data; + p0 = points[ ( intPoint - 1 ) % l ]; -} + } else { -class SphereGeometry extends BufferGeometry { + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; - constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { + } - super(); - this.type = 'SphereGeometry'; + const p1 = points[ intPoint % l ]; + const p2 = points[ ( intPoint + 1 ) % l ]; - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + if ( this.closed || intPoint + 2 < l ) { - widthSegments = Math.max( 3, Math.floor( widthSegments ) ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) ); + p3 = points[ ( intPoint + 2 ) % l ]; - const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + } else { - let index = 0; - const grid = []; + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; - const vertex = new Vector3(); - const normal = new Vector3(); + } - // buffers + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + // init Centripetal / Chordal Catmull-Rom + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); - // generate vertices, normals and uvs + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; - for ( let iy = 0; iy <= heightSegments; iy ++ ) { + 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 ); - const verticesRow = []; + } else if ( this.curveType === 'catmullrom' ) { - const v = iy / heightSegments; + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); - // special case for the poles + } - let uOffset = 0; + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); - if ( iy == 0 && thetaStart == 0 ) { + return point; - uOffset = 0.5 / widthSegments; + } - } else if ( iy == heightSegments && thetaEnd == Math.PI ) { + copy( source ) { - uOffset = - 0.5 / widthSegments; + super.copy( source ); - } + this.points = []; - for ( let ix = 0; ix <= widthSegments; ix ++ ) { + for ( let i = 0, l = source.points.length; i < l; i ++ ) { - const u = ix / widthSegments; + const point = source.points[ i ]; - // vertex + this.points.push( point.clone() ); - vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); - vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + } - vertices.push( vertex.x, vertex.y, vertex.z ); + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; - // normal + return this; - normal.copy( vertex ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + } - // uv + toJSON() { - uvs.push( u + uOffset, 1 - v ); + const data = super.toJSON(); - verticesRow.push( index ++ ); + data.points = []; - } + for ( let i = 0, l = this.points.length; i < l; i ++ ) { - grid.push( verticesRow ); + const point = this.points[ i ]; + data.points.push( point.toArray() ); } - // indices + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; - for ( let iy = 0; iy < heightSegments; iy ++ ) { + return data; - for ( let ix = 0; ix < widthSegments; ix ++ ) { + } - const a = grid[ iy ][ ix + 1 ]; - const b = grid[ iy ][ ix ]; - const c = grid[ iy + 1 ][ ix ]; - const d = grid[ iy + 1 ][ ix + 1 ]; + fromJSON( json ) { - if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); - if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + super.fromJSON( json ); - } + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); } - // build geometry + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + return this; } } -class TetrahedronGeometry extends PolyhedronGeometry { - - constructor( radius = 1, detail = 0 ) { +/** + * Bezier Curves formulas obtained from + * https://en.wikipedia.org/wiki/B%C3%A9zier_curve + */ - const vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; +function CatmullRom( t, p0, p1, p2, p3 ) { - const indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + const v0 = ( p2 - p0 ) * 0.5; + const v1 = ( p3 - p1 ) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - super( vertices, indices, radius, detail ); +} - this.type = 'TetrahedronGeometry'; +// - this.parameters = { - radius: radius, - detail: detail - }; +function QuadraticBezierP0( t, p ) { - } + const k = 1 - t; + return k * k * p; } -/** - * 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 (including bevelOffset) is bevel - * bevelOffset: // how far from text outline does bevel start - * } - */ +function QuadraticBezierP1( t, p ) { -class TextGeometry extends ExtrudeGeometry { + return 2 * ( 1 - t ) * t * p; - constructor( text, parameters = {} ) { +} - const font = parameters.font; +function QuadraticBezierP2( t, p ) { - if ( ! ( font && font.isFont ) ) { + return t * t * p; - console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new BufferGeometry(); +} - } +function QuadraticBezier( t, p0, p1, p2 ) { - const shapes = font.generateShapes( text, parameters.size ); + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); - // translate parameters to ExtrudeGeometry API +} - parameters.depth = parameters.height !== undefined ? parameters.height : 50; +// - // defaults +function CubicBezierP0( t, p ) { - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + const k = 1 - t; + return k * k * k * p; - super( shapes, parameters ); +} - this.type = 'TextGeometry'; +function CubicBezierP1( t, p ) { - } + const k = 1 - t; + return 3 * k * k * t * p; } -class TorusGeometry extends BufferGeometry { +function CubicBezierP2( t, p ) { - constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) { + return 3 * ( 1 - t ) * t * t * p; - super(); - this.type = 'TorusGeometry'; +} - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; +function CubicBezierP3( t, p ) { - radialSegments = Math.floor( radialSegments ); - tubularSegments = Math.floor( tubularSegments ); + return t * t * t * p; - // buffers +} - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; +function CubicBezier( t, p0, p1, p2, p3 ) { - // helper variables + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); - const center = new Vector3(); - const vertex = new Vector3(); - const normal = new Vector3(); +} - // generate vertices, normals and uvs +class CubicBezierCurve extends Curve { - for ( let j = 0; j <= radialSegments; j ++ ) { + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { - for ( let i = 0; i <= tubularSegments; i ++ ) { + super(); - const u = i / tubularSegments * arc; - const v = j / radialSegments * Math.PI * 2; + this.isCubicBezierCurve = true; - // vertex + this.type = 'CubicBezierCurve'; - 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 ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // normal + getPoint( t, optionalTarget = new Vector2() ) { - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); - normal.subVectors( vertex, center ).normalize(); + const point = optionalTarget; - normals.push( normal.x, normal.y, normal.z ); + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - // uv + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + return point; - } + } - } + copy( source ) { - // generate indices + super.copy( source ); - for ( let j = 1; j <= radialSegments; j ++ ) { + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); - for ( let i = 1; i <= tubularSegments; i ++ ) { + return this; - // indices + } - const a = ( tubularSegments + 1 ) * j + i - 1; - const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; - const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; - const d = ( tubularSegments + 1 ) * j + i; + toJSON() { - // faces + const data = super.toJSON(); - indices.push( a, b, d ); - indices.push( b, c, d ); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - } + return data; - } + } - // build geometry + fromJSON( json ) { - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; } } -class TorusKnotGeometry extends BufferGeometry { +class CubicBezierCurve3 extends Curve { - constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { super(); - this.type = 'TorusKnotGeometry'; - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + this.isCubicBezierCurve3 = true; - tubularSegments = Math.floor( tubularSegments ); - radialSegments = Math.floor( radialSegments ); + this.type = 'CubicBezierCurve3'; - // buffers + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + } - // helper variables + getPoint( t, optionalTarget = new Vector3() ) { - const vertex = new Vector3(); - const normal = new Vector3(); + const point = optionalTarget; - const P1 = new Vector3(); - const P2 = new Vector3(); + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - const B = new Vector3(); - const T = new Vector3(); - const N = new Vector3(); + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); - // generate vertices, normals and uvs + return point; - for ( let i = 0; i <= tubularSegments; ++ i ) { + } - // the radian "u" is used to calculate the position on the torus curve of the current tubular segement + copy( source ) { - const u = i / tubularSegments * p * Math.PI * 2; + super.copy( source ); - // 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 + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); - calculatePositionOnCurve( u, p, q, radius, P1 ); - calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + return this; - // calculate orthonormal basis + } - T.subVectors( P2, P1 ); - N.addVectors( P2, P1 ); - B.crossVectors( T, N ); - N.crossVectors( B, T ); + toJSON() { - // normalize B, N. T can be ignored, we don't use it + const data = super.toJSON(); - B.normalize(); - N.normalize(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - for ( let j = 0; j <= radialSegments; ++ j ) { + return data; - // 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. + } - const v = j / radialSegments * Math.PI * 2; - const cx = - tube * Math.cos( v ); - const cy = tube * Math.sin( v ); + fromJSON( json ) { - // 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 + super.fromJSON( json ); - 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 ); + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + return this; - // 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.push( normal.x, normal.y, normal.z ); +class LineCurve extends Curve { - // uv + constructor( v1 = new Vector2(), v2 = new Vector2() ) { - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + super(); - } + this.isLineCurve = true; - } + this.type = 'LineCurve'; - // generate indices + this.v1 = v1; + this.v2 = v2; - for ( let j = 1; j <= tubularSegments; j ++ ) { + } - for ( let i = 1; i <= radialSegments; i ++ ) { + getPoint( t, optionalTarget = new Vector2() ) { - // indices + const point = optionalTarget; - const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - const b = ( radialSegments + 1 ) * j + ( i - 1 ); - const c = ( radialSegments + 1 ) * j + i; - const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + if ( t === 1 ) { - // faces + point.copy( this.v2 ); - indices.push( a, b, d ); - indices.push( b, c, d ); + } else { - } + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); } - // build geometry + return point; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + } - // this function calculates the current position on the torus curve + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { - function calculatePositionOnCurve( u, p, q, radius, position ) { + return this.getPoint( u, optionalTarget ); - const cu = Math.cos( u ); - const su = Math.sin( u ); - const quOverP = q / p * u; - const 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; + getTangent( t, optionalTarget ) { - } + const tangent = optionalTarget || new Vector2(); + + tangent.copy( this.v2 ).sub( this.v1 ).normalize(); + + return tangent; } -} + copy( source ) { -class TubeGeometry extends BufferGeometry { + super.copy( source ); - constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - super(); - this.type = 'TubeGeometry'; + return this; - this.parameters = { - path: path, - tubularSegments: tubularSegments, - radius: radius, - radialSegments: radialSegments, - closed: closed - }; + } - const frames = path.computeFrenetFrames( tubularSegments, closed ); + toJSON() { - // expose internals + const data = super.toJSON(); - this.tangents = frames.tangents; - this.normals = frames.normals; - this.binormals = frames.binormals; + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - // helper variables + return data; - const vertex = new Vector3(); - const normal = new Vector3(); - const uv = new Vector2(); - let P = new Vector3(); + } - // buffer + fromJSON( json ) { - const vertices = []; - const normals = []; - const uvs = []; - const indices = []; + super.fromJSON( json ); - // create buffer data + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - generateBufferData(); + return this; - // build geometry + } - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); +} - // functions +class LineCurve3 extends Curve { - function generateBufferData() { + constructor( v1 = new Vector3(), v2 = new Vector3() ) { - for ( let i = 0; i < tubularSegments; i ++ ) { + super(); - generateSegment( i ); + this.isLineCurve3 = true; - } + this.type = 'LineCurve3'; - // if the geometry is not closed, generate the last row of vertices and normals - // at the regular position on the given path - // - // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + this.v1 = v1; + this.v2 = v2; - generateSegment( ( closed === false ) ? tubularSegments : 0 ); + } + getPoint( t, optionalTarget = new Vector3() ) { - // uvs are generated in a separate function. - // this makes it easy compute correct values for closed geometries + const point = optionalTarget; - generateUVs(); + if ( t === 1 ) { - // finally create faces + point.copy( this.v2 ); - generateIndices(); + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); } - function generateSegment( i ) { + return point; - // we use getPointAt to sample evenly distributed points from the given path + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { - P = path.getPointAt( i / tubularSegments, P ); + return this.getPoint( u, optionalTarget ); - // retrieve corresponding normal and binormal + } + copy( source ) { - const N = frames.normals[ i ]; - const B = frames.binormals[ i ]; + super.copy( source ); - // generate normals and vertices for the current segment + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - for ( let j = 0; j <= radialSegments; j ++ ) { + return this; - const v = j / radialSegments * Math.PI * 2; + } + toJSON() { - const sin = Math.sin( v ); - const cos = - Math.cos( v ); + const data = super.toJSON(); - // normal + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - normal.x = ( cos * N.x + sin * B.x ); - normal.y = ( cos * N.y + sin * B.y ); - normal.z = ( cos * N.z + sin * B.z ); - normal.normalize(); + return data; - normals.push( normal.x, normal.y, normal.z ); + } + fromJSON( json ) { - // vertex + super.fromJSON( json ); - vertex.x = P.x + radius * normal.x; - vertex.y = P.y + radius * normal.y; - vertex.z = P.z + radius * normal.z; + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + return this; - } + } - } +} - function generateIndices() { +class QuadraticBezierCurve extends Curve { - for ( let j = 1; j <= tubularSegments; j ++ ) { + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { - for ( let i = 1; i <= radialSegments; i ++ ) { + super(); - const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - const b = ( radialSegments + 1 ) * j + ( i - 1 ); - const c = ( radialSegments + 1 ) * j + i; - const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + this.isQuadraticBezierCurve = true; - // faces + this.type = 'QuadraticBezierCurve'; - indices.push( a, b, d ); - indices.push( b, c, d ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - } + } - } + getPoint( t, optionalTarget = new Vector2() ) { - } + const point = optionalTarget; - function generateUVs() { + const v0 = this.v0, v1 = this.v1, v2 = this.v2; - for ( let i = 0; i <= tubularSegments; i ++ ) { + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); - for ( let j = 0; j <= radialSegments; j ++ ) { + return point; - uv.x = i / tubularSegments; - uv.y = j / radialSegments; + } - uvs.push( uv.x, uv.y ); + copy( source ) { - } + super.copy( source ); - } + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - } + return this; } + toJSON() { - const data = BufferGeometry.prototype.toJSON.call( this ); + const data = super.toJSON(); - data.path = this.parameters.path.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); return data; } -} + fromJSON( json ) { -class WireframeGeometry extends BufferGeometry { + super.fromJSON( json ); - constructor( geometry ) { + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - super(); - this.type = 'WireframeGeometry'; + return this; - if ( geometry.isGeometry === true ) { + } - console.error( 'THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - return; +} - } +class QuadraticBezierCurve3 extends Curve { - // buffer + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { - const vertices = []; + super(); - // helper variables + this.isQuadraticBezierCurve3 = true; - const edge = [ 0, 0 ], edges = {}; + this.type = 'QuadraticBezierCurve3'; - const vertex = new Vector3(); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - if ( geometry.index !== null ) { + } - // indexed BufferGeometry + getPoint( t, optionalTarget = new Vector3() ) { - const position = geometry.attributes.position; - const indices = geometry.index; - let groups = geometry.groups; + const point = optionalTarget; - if ( groups.length === 0 ) { + const v0 = this.v0, v1 = this.v1, v2 = this.v2; - groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); - } + return point; - // create a data structure that contains all eges without duplicates + } - for ( let o = 0, ol = groups.length; o < ol; ++ o ) { + copy( source ) { - const group = groups[ o ]; + super.copy( source ); - const start = group.start; - const count = group.count; + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - for ( let i = start, l = ( start + count ); i < l; i += 3 ) { + return this; - for ( let j = 0; j < 3; j ++ ) { + } - const edge1 = indices.getX( i + j ); - const edge2 = indices.getX( i + ( j + 1 ) % 3 ); - edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates - edge[ 1 ] = Math.max( edge1, edge2 ); + toJSON() { - const key = edge[ 0 ] + ',' + edge[ 1 ]; + const data = super.toJSON(); - if ( edges[ key ] === undefined ) { + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; + return data; - } + } - } + fromJSON( json ) { - } + super.fromJSON( json ); - } + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - // generate vertices + return this; - for ( const key in edges ) { + } - const e = edges[ key ]; +} - vertex.fromBufferAttribute( position, e.index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); +class SplineCurve extends Curve { - vertex.fromBufferAttribute( position, e.index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + constructor( points = [] ) { - } + super(); - } else { + this.isSplineCurve = true; - // non-indexed BufferGeometry + this.type = 'SplineCurve'; - const position = geometry.attributes.position; + this.points = points; - for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { + } - for ( let j = 0; j < 3; j ++ ) { + getPoint( t, optionalTarget = new Vector2() ) { - // three edges per triangle, an edge is represented as (index1, index2) - // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) + const point = optionalTarget; - const index1 = 3 * i + j; - vertex.fromBufferAttribute( position, index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + const points = this.points; + const p = ( points.length - 1 ) * t; - const index2 = 3 * i + ( ( j + 1 ) % 3 ); - vertex.fromBufferAttribute( position, index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + const intPoint = Math.floor( p ); + const weight = p - intPoint; - } + const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + const p1 = points[ intPoint ]; + const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - } + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); - } + return point; - // build geometry + } - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + copy( source ) { - } + super.copy( source ); -} + this.points = []; -var Geometries = /*#__PURE__*/Object.freeze({ - __proto__: null, - BoxGeometry: BoxGeometry, - BoxBufferGeometry: BoxGeometry, - CircleGeometry: CircleGeometry, - CircleBufferGeometry: CircleGeometry, - ConeGeometry: ConeGeometry, - ConeBufferGeometry: ConeGeometry, - CylinderGeometry: CylinderGeometry, - CylinderBufferGeometry: CylinderGeometry, - DodecahedronGeometry: DodecahedronGeometry, - DodecahedronBufferGeometry: DodecahedronGeometry, - EdgesGeometry: EdgesGeometry, - ExtrudeGeometry: ExtrudeGeometry, - ExtrudeBufferGeometry: ExtrudeGeometry, - IcosahedronGeometry: IcosahedronGeometry, - IcosahedronBufferGeometry: IcosahedronGeometry, - LatheGeometry: LatheGeometry, - LatheBufferGeometry: LatheGeometry, - OctahedronGeometry: OctahedronGeometry, - OctahedronBufferGeometry: OctahedronGeometry, - ParametricGeometry: ParametricGeometry, - ParametricBufferGeometry: ParametricGeometry, - PlaneGeometry: PlaneGeometry, - PlaneBufferGeometry: PlaneGeometry, - PolyhedronGeometry: PolyhedronGeometry, - PolyhedronBufferGeometry: PolyhedronGeometry, - RingGeometry: RingGeometry, - RingBufferGeometry: RingGeometry, - ShapeGeometry: ShapeGeometry, - ShapeBufferGeometry: ShapeGeometry, - SphereGeometry: SphereGeometry, - SphereBufferGeometry: SphereGeometry, - TetrahedronGeometry: TetrahedronGeometry, - TetrahedronBufferGeometry: TetrahedronGeometry, - TextGeometry: TextGeometry, - TextBufferGeometry: TextGeometry, - TorusGeometry: TorusGeometry, - TorusBufferGeometry: TorusGeometry, - TorusKnotGeometry: TorusKnotGeometry, - TorusKnotBufferGeometry: TorusKnotGeometry, - TubeGeometry: TubeGeometry, - TubeBufferGeometry: TubeGeometry, - WireframeGeometry: WireframeGeometry -}); + for ( let i = 0, l = source.points.length; i < l; i ++ ) { -/** - * parameters = { - * color: - * } - */ + const point = source.points[ i ]; -class ShadowMaterial extends Material { + this.points.push( point.clone() ); - constructor( parameters ) { + } - super(); + return this; - this.type = 'ShadowMaterial'; + } - this.color = new Color( 0x000000 ); - this.transparent = true; + toJSON() { - this.setValues( parameters ); + const data = super.toJSON(); - } + data.points = []; - copy( source ) { + for ( let i = 0, l = this.points.length; i < l; i ++ ) { - super.copy( source ); + const point = this.points[ i ]; + data.points.push( point.toArray() ); - this.color.copy( source.color ); + } - return this; + return data; } -} + fromJSON( json ) { -ShadowMaterial.prototype.isShadowMaterial = true; + super.fromJSON( json ); -class RawShaderMaterial extends ShaderMaterial { + this.points = []; - constructor( parameters ) { + for ( let i = 0, l = json.points.length; i < l; i ++ ) { - super( parameters ); + const point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); - this.type = 'RawShaderMaterial'; + } + + return this; } } -RawShaderMaterial.prototype.isRawShaderMaterial = true; - -/** - * 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( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * 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: , - * - * flatShading: - * } - */ +var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve +}); -function MeshStandardMaterial( parameters ) { +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - Material.call( this ); +class CurvePath extends Curve { - this.defines = { 'STANDARD': '' }; + constructor() { - this.type = 'MeshStandardMaterial'; + super(); - this.color = new Color( 0xffffff ); // diffuse - this.roughness = 1.0; - this.metalness = 0.0; + this.type = 'CurvePath'; - this.map = null; + this.curves = []; + this.autoClose = false; // Automatically closes the path - this.lightMap = null; - this.lightMapIntensity = 1.0; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + add( curve ) { - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + this.curves.push( curve ); - this.bumpMap = null; - this.bumpScale = 1; + } - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + closePath() { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + // Add a line curve if start and end of lines are not connected + const startPoint = this.curves[ 0 ].getPoint( 0 ); + const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); - this.roughnessMap = null; + if ( ! startPoint.equals( endPoint ) ) { - this.metalnessMap = null; + this.curves.push( new LineCurve( endPoint, startPoint ) ); - this.alphaMap = null; + } - this.envMap = null; - this.envMapIntensity = 1.0; + } - this.refractionRatio = 0.98; + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + getPoint( t, optionalTarget ) { - this.flatShading = false; + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; - this.vertexTangents = false; + // To think about boundaries points. - this.setValues( parameters ); + while ( i < curveLengths.length ) { -} + if ( curveLengths[ i ] >= d ) { -MeshStandardMaterial.prototype = Object.create( Material.prototype ); -MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; + const diff = curveLengths[ i ] - d; + const curve = this.curves[ i ]; -MeshStandardMaterial.prototype.isMeshStandardMaterial = true; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; -MeshStandardMaterial.prototype.copy = function ( source ) { + return curve.getPointAt( u, optionalTarget ); - Material.prototype.copy.call( this, source ); + } - this.defines = { 'STANDARD': '' }; + i ++; - this.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + } - this.map = source.map; + return null; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + // loop where sum != 0, sum > d , sum+1 , - * clearcoatMap: new THREE.Texture( ), - * clearcoatRoughness: , - * clearcoatRoughnessMap: new THREE.Texture( ), - * clearcoatNormalScale: , - * clearcoatNormalMap: new THREE.Texture( ), - * - * reflectivity: , - * ior: , - * - * sheen: , - * - * transmission: , - * transmissionMap: new THREE.Texture( ) - * } - */ + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { -function MeshPhysicalMaterial( parameters ) { + sums += this.curves[ i ].getLength(); + lengths.push( sums ); - MeshStandardMaterial.call( this ); + } - this.defines = { + this.cacheLengths = lengths; - 'STANDARD': '', - 'PHYSICAL': '' + return lengths; - }; + } - this.type = 'MeshPhysicalMaterial'; + getSpacedPoints( divisions = 40 ) { - this.clearcoat = 0.0; - this.clearcoatMap = null; - this.clearcoatRoughness = 0.0; - this.clearcoatRoughnessMap = null; - this.clearcoatNormalScale = new Vector2( 1, 1 ); - this.clearcoatNormalMap = null; + const points = []; - this.reflectivity = 0.5; // maps to F0 = 0.04 + for ( let i = 0; i <= divisions; i ++ ) { - Object.defineProperty( this, 'ior', { - get: function () { + points.push( this.getPoint( i / divisions ) ); - return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity ); + } - }, - set: function ( ior ) { + if ( this.autoClose ) { - this.reflectivity = MathUtils.clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 ); + points.push( points[ 0 ] ); } - } ); - this.sheen = null; // null will disable sheen bsdf + return points; - this.transmission = 0.0; - this.transmissionMap = null; + } - this.setValues( parameters ); + getPoints( divisions = 12 ) { -} + const points = []; + let last; -MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); -MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; + for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) { -MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; + const curve = curves[ i ]; + const resolution = curve.isEllipseCurve ? divisions * 2 + : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1 + : curve.isSplineCurve ? divisions * curve.points.length + : divisions; -MeshPhysicalMaterial.prototype.copy = function ( source ) { + const pts = curve.getPoints( resolution ); - MeshStandardMaterial.prototype.copy.call( this, source ); + for ( let j = 0; j < pts.length; j ++ ) { - this.defines = { + const point = pts[ j ]; - 'STANDARD': '', - 'PHYSICAL': '' + if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates - }; + points.push( point ); + last = point; - this.clearcoat = source.clearcoat; - this.clearcoatMap = source.clearcoatMap; - this.clearcoatRoughness = source.clearcoatRoughness; - this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; - this.clearcoatNormalMap = source.clearcoatNormalMap; - this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + } - this.reflectivity = source.reflectivity; + } - if ( source.sheen ) { + if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { - this.sheen = ( this.sheen || new Color() ).copy( source.sheen ); + points.push( points[ 0 ] ); - } else { + } - this.sheen = null; + return points; } - this.transmission = source.transmission; - this.transmissionMap = source.transmissionMap; + copy( source ) { - return this; + super.copy( source ); -}; + this.curves = []; -/** - * 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( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.MultiplyOperation, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * flatShading: - * } - */ + for ( let i = 0, l = source.curves.length; i < l; i ++ ) { -class MeshPhongMaterial extends Material { + const curve = source.curves[ i ]; - constructor( parameters ) { + this.curves.push( curve.clone() ); - super(); + } - this.type = 'MeshPhongMaterial'; + this.autoClose = source.autoClose; - this.color = new Color( 0xffffff ); // diffuse - this.specular = new Color( 0x111111 ); - this.shininess = 30; + return this; - this.map = null; + } - this.lightMap = null; - this.lightMapIntensity = 1.0; + toJSON() { - this.aoMap = null; - this.aoMapIntensity = 1.0; + const data = super.toJSON(); - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + data.autoClose = this.autoClose; + data.curves = []; - this.bumpMap = null; - this.bumpScale = 1; + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + const curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + } - this.specularMap = null; + return data; - this.alphaMap = null; + } - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + fromJSON( json ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + super.fromJSON( json ); - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.autoClose = json.autoClose; + this.curves = []; - this.flatShading = false; + for ( let i = 0, l = json.curves.length; i < l; i ++ ) { - this.setValues( parameters ); + const curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); - } + } - copy( source ) { + return this; - super.copy( source ); + } - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; +} - this.map = source.map; +class Path extends CurvePath { - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + constructor( points ) { - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + super(); - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + this.type = 'Path'; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + this.currentPoint = new Vector2(); - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + if ( points ) { - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + this.setFromPoints( points ); - this.specularMap = source.specularMap; + } - this.alphaMap = source.alphaMap; + } - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + setFromPoints( points ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + this.moveTo( points[ 0 ].x, points[ 0 ].y ); + + for ( let i = 1, l = points.length; i < l; i ++ ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.lineTo( points[ i ].x, points[ i ].y ); - this.flatShading = source.flatShading; + } return this; } -} + moveTo( x, y ) { -MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? -/** - * parameters = { - * color: , - * - * map: new THREE.Texture( ), - * gradientMap: 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( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * alphaMap: new THREE.Texture( ), - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + return this; -class MeshToonMaterial extends Material { + } - constructor( parameters ) { + lineTo( x, y ) { - super(); + const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - this.defines = { 'TOON': '' }; + this.currentPoint.set( x, y ); - this.type = 'MeshToonMaterial'; + return this; - this.color = new Color( 0xffffff ); + } - this.map = null; - this.gradientMap = null; + quadraticCurveTo( aCPx, aCPy, aX, aY ) { - this.lightMap = null; - this.lightMapIntensity = 1.0; + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - this.aoMap = null; - this.aoMapIntensity = 1.0; + this.curves.push( curve ); - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + this.currentPoint.set( aX, aY ); - this.bumpMap = null; - this.bumpScale = 1; + return this; - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + } - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - this.alphaMap = null; + const curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + this.curves.push( curve ); - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.currentPoint.set( aX, aY ); - this.setValues( parameters ); + return this; } - copy( source ) { + splineThru( pts /*Array of Vector*/ ) { - super.copy( source ); + const npts = [ this.currentPoint.clone() ].concat( pts ); - this.color.copy( source.color ); + const curve = new SplineCurve( npts ); + this.curves.push( curve ); - this.map = source.map; - this.gradientMap = source.gradientMap; + this.currentPoint.copy( pts[ pts.length - 1 ] ); - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + return this; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + } - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + return this; - this.alphaMap = source.alphaMap; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); return this; } -} + ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { -MeshToonMaterial.prototype.isMeshToonMaterial = true; + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; -/** - * parameters = { - * opacity: , - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * flatShading: - * } - */ + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); -class MeshNormalMaterial extends Material { + return this; - constructor( parameters ) { + } - super(); + absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - this.type = 'MeshNormalMaterial'; + const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - this.bumpMap = null; - this.bumpScale = 1; + if ( this.curves.length > 0 ) { - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + // if a previous curve is present, attempt to join + const firstPoint = curve.getPoint( 0 ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + if ( ! firstPoint.equals( this.currentPoint ) ) { - this.wireframe = false; - this.wireframeLinewidth = 1; + this.lineTo( firstPoint.x, firstPoint.y ); - this.fog = false; + } - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + } - this.flatShading = false; + this.curves.push( curve ); - this.setValues( parameters ); + const lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + return this; } @@ -31835,25 +32847,27 @@ class MeshNormalMaterial extends Material { super.copy( source ); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + this.currentPoint.copy( source.currentPoint ); - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + return this; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + toJSON() { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + const data = super.toJSON(); - this.flatShading = source.flatShading; + data.currentPoint = this.currentPoint.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.currentPoint.fromArray( json.currentPoint ); return this; @@ -31861,1292 +32875,1139 @@ class MeshNormalMaterial extends Material { } -MeshNormalMaterial.prototype.isMeshNormalMaterial = true; +class LatheGeometry extends BufferGeometry { -/** - * 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.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { -class MeshLambertMaterial extends Material { + super(); - constructor( parameters ) { + this.type = 'LatheGeometry'; - super(); + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; - this.type = 'MeshLambertMaterial'; + segments = Math.floor( segments ); - this.color = new Color( 0xffffff ); // diffuse + // clamp phiLength so it's in range of [ 0, 2PI ] - this.map = null; + phiLength = clamp( phiLength, 0, Math.PI * 2 ); - this.lightMap = null; - this.lightMapIntensity = 1.0; + // buffers - this.aoMap = null; - this.aoMapIntensity = 1.0; + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + // helper variables - this.specularMap = null; + const inverseSegments = 1.0 / segments; + const vertex = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; - this.alphaMap = null; + // pre-compute normals for initial "meridian" - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + switch ( j ) { - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + case 0: // special handling for 1st vertex on path - this.setValues( parameters ); + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; - } + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; - copy( source ) { + prevNormal.copy( normal ); - super.copy( source ); + normal.normalize(); - this.color.copy( source.color ); + initNormals.push( normal.x, normal.y, normal.z ); - this.map = source.map; + break; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + case ( points.length - 1 ): // special handling for last Vertex on path - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z ); - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + break; - this.specularMap = source.specularMap; + default: // default handling for all vertices in between - this.alphaMap = source.alphaMap; + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + curNormal.copy( normal ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; - return this; + normal.normalize(); - } + initNormals.push( normal.x, normal.y, normal.z ); -} + prevNormal.copy( curNormal ); -MeshLambertMaterial.prototype.isMeshLambertMaterial = true; + } -/** - * parameters = { - * color: , - * opacity: , - * - * matcap: new THREE.Texture( ), - * - * map: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * alphaMap: new THREE.Texture( ), - * - * skinning: , - * morphTargets: , - * morphNormals: - * - * flatShading: - * } - */ + } -class MeshMatcapMaterial extends Material { + // generate vertices, uvs and normals - constructor( parameters ) { + for ( let i = 0; i <= segments; i ++ ) { - super(); + const phi = phiStart + i * inverseSegments * phiLength; - this.defines = { 'MATCAP': '' }; + const sin = Math.sin( phi ); + const cos = Math.cos( phi ); - this.type = 'MeshMatcapMaterial'; + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { - this.color = new Color( 0xffffff ); // diffuse + // vertex - this.matcap = null; + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; - this.map = null; + vertices.push( vertex.x, vertex.y, vertex.z ); - this.bumpMap = null; - this.bumpScale = 1; + // uv - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + uvs.push( uv.x, uv.y ); - this.alphaMap = null; + // normal - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + const x = initNormals[ 3 * j + 0 ] * sin; + const y = initNormals[ 3 * j + 1 ]; + const z = initNormals[ 3 * j + 0 ] * cos; - this.flatShading = false; + normals.push( x, y, z ); - this.setValues( parameters ); + } - } + } + // indices - copy( source ) { + for ( let i = 0; i < segments; i ++ ) { - super.copy( source ); + for ( let j = 0; j < ( points.length - 1 ); j ++ ) { - this.defines = { 'MATCAP': '' }; + const base = j + i * points.length; - this.color.copy( source.color ); + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; - this.matcap = source.matcap; + // faces - this.map = source.map; + indices.push( a, b, d ); + indices.push( c, d, b ); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + } - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + } - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + // build geometry - this.alphaMap = source.alphaMap; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + } - this.flatShading = source.flatShading; + static fromJSON( data ) { - return this; + return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength ); } } -MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true; - -/** - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ - -class LineDashedMaterial extends LineBasicMaterial { +class CapsuleGeometry extends LatheGeometry { - constructor( parameters ) { + constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) { - super(); + const path = new Path(); + path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 ); + path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 ); - this.type = 'LineDashedMaterial'; + super( path.getPoints( capSegments ), radialSegments ); - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + this.type = 'CapsuleGeometry'; - this.setValues( parameters ); + this.parameters = { + radius: radius, + height: length, + capSegments: capSegments, + radialSegments: radialSegments, + }; } - copy( source ) { - - super.copy( source ); - - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + static fromJSON( data ) { - return this; + return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments ); } } -LineDashedMaterial.prototype.isLineDashedMaterial = true; +class CircleGeometry extends BufferGeometry { -var Materials = /*#__PURE__*/Object.freeze({ - __proto__: null, - ShadowMaterial: ShadowMaterial, - SpriteMaterial: SpriteMaterial, - RawShaderMaterial: RawShaderMaterial, - ShaderMaterial: ShaderMaterial, - PointsMaterial: PointsMaterial, - MeshPhysicalMaterial: MeshPhysicalMaterial, - MeshStandardMaterial: MeshStandardMaterial, - MeshPhongMaterial: MeshPhongMaterial, - MeshToonMaterial: MeshToonMaterial, - MeshNormalMaterial: MeshNormalMaterial, - MeshLambertMaterial: MeshLambertMaterial, - MeshDepthMaterial: MeshDepthMaterial, - MeshDistanceMaterial: MeshDistanceMaterial, - MeshBasicMaterial: MeshBasicMaterial, - MeshMatcapMaterial: MeshMatcapMaterial, - LineDashedMaterial: LineDashedMaterial, - LineBasicMaterial: LineBasicMaterial, - Material: Material -}); + constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) { -const AnimationUtils = { + super(); - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function ( array, from, to ) { + this.type = 'CircleGeometry'; - if ( AnimationUtils.isTypedArray( array ) ) { + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - // in ios9 array.subarray(from, undefined) will return empty array - // but array.subarray(from) or array.subarray(from, len) is correct - return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); + segments = Math.max( 3, segments ); - } + // buffers - return array.slice( from, to ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - }, + // helper variables - // converts an array to a specific type - convertArray: function ( array, type, forceClone ) { + const vertex = new Vector3(); + const uv = new Vector2(); - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) return array; + // center point - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); - return new type( array ); // create typed array + for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { - } + const segment = thetaStart + s / segments * thetaLength; - return Array.prototype.slice.call( array ); // create Array + // vertex - }, + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - isTypedArray: function ( object ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + // normal - }, + normals.push( 0, 0, 1 ); - // returns an array by which times and values can be sorted - getKeyframeOrder: function ( times ) { + // uvs - function compareTime( i, j ) { + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; - return times[ i ] - times[ j ]; + uvs.push( uv.x, uv.y ); } - const n = times.length; - const result = new Array( n ); - for ( let i = 0; i !== n; ++ i ) result[ i ] = i; - - result.sort( compareTime ); - - return result; - - }, - - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function ( values, stride, order ) { - - const nValues = values.length; - const result = new values.constructor( nValues ); - - for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - - const srcOffset = order[ i ] * stride; - - for ( let j = 0; j !== stride; ++ j ) { + // indices - result[ dstOffset ++ ] = values[ srcOffset + j ]; + for ( let i = 1; i <= segments; i ++ ) { - } + indices.push( i, i + 1, 0 ); } - return result; - - }, + // build geometry - // function for parsing AOS keyframe formats - flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) { + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - let i = 1, key = jsonKeys[ 0 ]; + } - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + static fromJSON( data ) { - key = jsonKeys[ i ++ ]; + return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength ); - } + } - if ( key === undefined ) return; // no data +} - let value = key[ valuePropertyName ]; - if ( value === undefined ) return; // no data +class CylinderGeometry extends BufferGeometry { - if ( Array.isArray( value ) ) { + constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { - do { + super(); - value = key[ valuePropertyName ]; + this.type = 'CylinderGeometry'; - if ( value !== undefined ) { + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - times.push( key.time ); - values.push.apply( values, value ); // push all elements + const scope = this; - } + radialSegments = Math.floor( radialSegments ); + heightSegments = Math.floor( heightSegments ); - key = jsonKeys[ i ++ ]; + // buffers - } while ( key !== undefined ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - } else if ( value.toArray !== undefined ) { + // helper variables - // ...assume THREE.Math-ish + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; - do { + // generate geometry - value = key[ valuePropertyName ]; + generateTorso(); - if ( value !== undefined ) { + if ( openEnded === false ) { - times.push( key.time ); - value.toArray( values, values.length ); + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); - } + } - key = jsonKeys[ i ++ ]; + // build geometry - } while ( key !== undefined ); + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } else { + function generateTorso() { - // otherwise push as-is + const normal = new Vector3(); + const vertex = new Vector3(); - do { + let groupCount = 0; - value = key[ valuePropertyName ]; + // this will be used to calculate the normal + const slope = ( radiusBottom - radiusTop ) / height; - if ( value !== undefined ) { + // generate vertices, normals and uvs - times.push( key.time ); - values.push( value ); + for ( let y = 0; y <= heightSegments; y ++ ) { - } + const indexRow = []; - key = jsonKeys[ i ++ ]; + const v = y / heightSegments; - } while ( key !== undefined ); + // calculate the radius of the current row - } + const radius = v * ( radiusBottom - radiusTop ) + radiusTop; - }, + for ( let x = 0; x <= radialSegments; x ++ ) { - subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) { + const u = x / radialSegments; - const clip = sourceClip.clone(); + const theta = u * thetaLength + thetaStart; - clip.name = name; + const sinTheta = Math.sin( theta ); + const cosTheta = Math.cos( theta ); - const tracks = []; + // vertex - for ( let i = 0; i < clip.tracks.length; ++ i ) { + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); - const track = clip.tracks[ i ]; - const valueSize = track.getValueSize(); + // normal - const times = []; - const values = []; + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - for ( let j = 0; j < track.times.length; ++ j ) { + // uv - const frame = track.times[ j ] * fps; + uvs.push( u, 1 - v ); - if ( frame < startFrame || frame >= endFrame ) continue; + // save index of vertex in respective row - times.push( track.times[ j ] ); + indexRow.push( index ++ ); - for ( let k = 0; k < valueSize; ++ k ) { + } - values.push( track.values[ j * valueSize + k ] ); + // now save vertices of the row in our index array - } + indexArray.push( indexRow ); } - if ( times.length === 0 ) continue; + // generate indices - track.times = AnimationUtils.convertArray( times, track.times.constructor ); - track.values = AnimationUtils.convertArray( values, track.values.constructor ); + for ( let x = 0; x < radialSegments; x ++ ) { - tracks.push( track ); + for ( let y = 0; y < heightSegments; y ++ ) { - } + // we use the index array to access the correct indices - clip.tracks = tracks; + const a = indexArray[ y ][ x ]; + const b = indexArray[ y + 1 ][ x ]; + const c = indexArray[ y + 1 ][ x + 1 ]; + const d = indexArray[ y ][ x + 1 ]; - // find minimum .times value across all tracks in the trimmed clip + // faces - let minStartTime = Infinity; + indices.push( a, b, d ); + indices.push( b, c, d ); - for ( let i = 0; i < clip.tracks.length; ++ i ) { + // update group counter - if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { + groupCount += 6; - minStartTime = clip.tracks[ i ].times[ 0 ]; + } } - } + // add a group to the geometry. this will ensure multi material support - // shift all tracks such that clip begins at t=0 + scope.addGroup( groupStart, groupCount, 0 ); - for ( let i = 0; i < clip.tracks.length; ++ i ) { + // calculate new start value for groups - clip.tracks[ i ].shift( - 1 * minStartTime ); + groupStart += groupCount; } - clip.resetDuration(); - - return clip; + function generateCap( top ) { - }, + // save the index of the first center vertex + const centerIndexStart = index; - makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { + const uv = new Vector2(); + const vertex = new Vector3(); - if ( fps <= 0 ) fps = 30; + let groupCount = 0; - const numTracks = referenceClip.tracks.length; - const referenceTime = referenceFrame / fps; + const radius = ( top === true ) ? radiusTop : radiusBottom; + const sign = ( top === true ) ? 1 : - 1; - // Make each track's values relative to the values at the reference frame - for ( let i = 0; i < numTracks; ++ 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 - const referenceTrack = referenceClip.tracks[ i ]; - const referenceTrackType = referenceTrack.ValueTypeName; + for ( let x = 1; x <= radialSegments; x ++ ) { - // Skip this track if it's non-numeric - if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; + // vertex - // Find the track in the target clip whose name and type matches the reference track - const targetTrack = targetClip.tracks.find( function ( track ) { + vertices.push( 0, halfHeight * sign, 0 ); - return track.name === referenceTrack.name - && track.ValueTypeName === referenceTrackType; + // normal - } ); + normals.push( 0, sign, 0 ); - if ( targetTrack === undefined ) continue; + // uv - let referenceOffset = 0; - const referenceValueSize = referenceTrack.getValueSize(); + uvs.push( 0.5, 0.5 ); - if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + // increase index - referenceOffset = referenceValueSize / 3; + index ++; } - let targetOffset = 0; - const targetValueSize = targetTrack.getValueSize(); - - if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + // save the index of the last center vertex + const centerIndexEnd = index; - targetOffset = targetValueSize / 3; + // now we generate the surrounding vertices, normals and uvs - } + for ( let x = 0; x <= radialSegments; x ++ ) { - const lastIndex = referenceTrack.times.length - 1; - let referenceValue; + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; - // Find the value to subtract out of the track - if ( referenceTime <= referenceTrack.times[ 0 ] ) { + const cosTheta = Math.cos( theta ); + const sinTheta = Math.sin( theta ); - // Reference frame is earlier than the first keyframe, so just use the first keyframe - const startIndex = referenceOffset; - const endIndex = referenceValueSize - referenceOffset; - referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex ); + // vertex - } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); - // Reference frame is after the last keyframe, so just use the last keyframe - const startIndex = lastIndex * referenceValueSize + referenceOffset; - const endIndex = startIndex + referenceValueSize - referenceOffset; - referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex ); + // normal - } else { + normals.push( 0, sign, 0 ); - // Interpolate to the reference value - const interpolant = referenceTrack.createInterpolant(); - const startIndex = referenceOffset; - const endIndex = referenceValueSize - referenceOffset; - interpolant.evaluate( referenceTime ); - referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex ); + // uv - } + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); - // Conjugate the quaternion - if ( referenceTrackType === 'quaternion' ) { + // increase index - const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); - referenceQuat.toArray( referenceValue ); + index ++; } - // Subtract the reference value from all of the track values - - const numTimes = targetTrack.times.length; - for ( let j = 0; j < numTimes; ++ j ) { + // generate indices - const valueStart = j * targetValueSize + targetOffset; + for ( let x = 0; x < radialSegments; x ++ ) { - if ( referenceTrackType === 'quaternion' ) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; - // Multiply the conjugate for quaternion track types - Quaternion.multiplyQuaternionsFlat( - targetTrack.values, - valueStart, - referenceValue, - 0, - targetTrack.values, - valueStart - ); + if ( top === true ) { - } else { + // face top - const valueEnd = targetValueSize - targetOffset * 2; + indices.push( i, i + 1, c ); - // Subtract each value for all other numeric track types - for ( let k = 0; k < valueEnd; ++ k ) { + } else { - targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; + // face bottom - } + indices.push( i + 1, i, c ); } + groupCount += 3; + } - } + // add a group to the geometry. this will ensure multi material support - targetClip.blendMode = AdditiveAnimationBlendMode; + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); - return targetClip; + // calculate new start value for groups - } + groupStart += groupCount; -}; + } -/** - * 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 - * - */ + } -function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + static fromJSON( data ) { - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + } } -Object.assign( Interpolant.prototype, { - - evaluate: function ( t ) { - - const pp = this.parameterPositions; - let i1 = this._cachedIndex, - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; - - validate_interval: { - - seek: { - - let right; +class ConeGeometry extends CylinderGeometry { - linear_scan: { + constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - for ( let giveUpAt = i1 + 2; ; ) { + this.type = 'ConeGeometry'; - if ( t1 === undefined ) { + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - if ( t < t0 ) break forward_scan; + } - // after end + static fromJSON( data ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); - } + } - if ( i1 === giveUpAt ) break; // this loop +} - t0 = t1; - t1 = pp[ ++ i1 ]; +class PolyhedronGeometry extends BufferGeometry { - if ( t < t1 ) { + constructor( vertices = [], indices = [], radius = 1, detail = 0 ) { - // we have arrived at the sought interval - break seek; + super(); - } + this.type = 'PolyhedronGeometry'; - } + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + // default buffer data - } + const vertexBuffer = []; + const uvBuffer = []; - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + // the subdivision creates the vertex buffer data - // looping? + subdivide( detail ); - const t1global = pp[ 1 ]; + // all vertices should lie on a conceptual sphere with a given radius - if ( t < t1global ) { + applyRadius( radius ); - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + // finally, create the uv data - } + generateUVs(); - // linear reverse scan + // build non-indexed geometry - for ( let giveUpAt = i1 - 2; ; ) { + this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); - if ( t0 === undefined ) { + if ( detail === 0 ) { - // before start + this.computeVertexNormals(); // flat normals - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + } else { - } + this.normalizeNormals(); // smooth normals - if ( i1 === giveUpAt ) break; // this loop + } - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + // helper functions - if ( t >= t0 ) { + function subdivide( detail ) { - // we have arrived at the sought interval - break seek; + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); - } + // iterate over all faces and apply a subdivison with the given detail value - } + for ( let i = 0; i < indices.length; i += 3 ) { - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + // get the vertices of the face - } + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); - // the interval is valid + // perform subdivision - break validate_interval; + subdivideFace( a, b, c, detail ); - } // linear scan + } - // binary search + } - while ( i1 < right ) { + function subdivideFace( a, b, c, detail ) { - const mid = ( i1 + right ) >>> 1; + const cols = detail + 1; - if ( t < pp[ mid ] ) { + // we use this multidimensional array as a data structure for creating the subdivision - right = mid; + const v = []; - } else { + // construct all of the vertices for this subdivision - i1 = mid + 1; + for ( let i = 0; i <= cols; i ++ ) { - } + v[ i ] = []; - } + const aj = a.clone().lerp( c, i / cols ); + const bj = b.clone().lerp( c, i / cols ); - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + const rows = cols - i; - // check boundary cases, again + for ( let j = 0; j <= rows; j ++ ) { - if ( t0 === undefined ) { + if ( j === 0 && i === cols ) { - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + v[ i ][ j ] = aj; - } + } else { - if ( t1 === undefined ) { + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + } } - } // seek - - this._cachedIndex = i1; - - this.intervalChanged_( i1, t0, t1 ); - - } // validate_interval - - return this.interpolate_( i1, t0, t, t1 ); - - }, + } - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + // construct all of the faces - // --- Protected interface + for ( let i = 0; i < cols; i ++ ) { - DefaultSettings_: {}, + for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - getSettings_: function () { + const k = Math.floor( j / 2 ); - return this.settings || this.DefaultSettings_; + if ( j % 2 === 0 ) { - }, + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); - copySampleValue_: function ( index ) { + } else { - // copies a sample value to the result buffer + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + } - for ( let i = 0; i !== stride; ++ i ) { + } - result[ i ] = values[ offset + i ]; + } } - return result; - - }, - - // Template methods for derived classes: - - interpolate_: function ( /* i1, t0, t, t1 */ ) { - - throw new Error( 'call to abstract method' ); - // implementations shall return this.resultBuffer - - }, - - intervalChanged_: function ( /* i1, t0, t1 */ ) { - - // empty - - } - -} ); + function applyRadius( radius ) { -// DECLARE ALIAS AFTER assign prototype -Object.assign( Interpolant.prototype, { + const vertex = new Vector3(); - //( 0, t, t0 ), returns this.resultBuffer - beforeStart_: Interpolant.prototype.copySampleValue_, + // iterate over the entire buffer and apply the radius to each vertex - //( N-1, tN-1, t ), returns this.resultBuffer - afterEnd_: Interpolant.prototype.copySampleValue_, + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { -} ); + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; -/** - * 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. - */ + vertex.normalize().multiplyScalar( radius ); -function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + } - this._weightPrev = - 0; - this._offsetPrev = - 0; - this._weightNext = - 0; - this._offsetNext = - 0; + } -} + function generateUVs() { -CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + const vertex = new Vector3(); - constructor: CubicInterpolant, + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { - DefaultSettings_: { + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding + const u = azimuth( vertex ) / 2 / Math.PI + 0.5; + const v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); - }, + } - intervalChanged_: function ( i1, t0, t1 ) { + correctUVs(); - const pp = this.parameterPositions; - let iPrev = i1 - 2, - iNext = i1 + 1, + correctSeam(); - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + } - if ( tPrev === undefined ) { + function correctSeam() { - switch ( this.getSettings_().endingStart ) { + // handle case when face straddles the seam, see #3269 - case ZeroSlopeEnding: + for ( let i = 0; i < uvBuffer.length; i += 6 ) { - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + // uv data of a single face - break; + const x0 = uvBuffer[ i + 0 ]; + const x1 = uvBuffer[ i + 2 ]; + const x2 = uvBuffer[ i + 4 ]; - case WrapAroundEnding: + const max = Math.max( x0, x1, x2 ); + const min = Math.min( x0, x1, x2 ); - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + // 0.9 is somewhat arbitrary - break; + if ( max > 0.9 && min < 0.1 ) { - default: // ZeroCurvatureEnding + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + } } } - if ( tNext === undefined ) { - - switch ( this.getSettings_().endingEnd ) { - - case ZeroSlopeEnding: - - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; - - break; - - case WrapAroundEnding: + function pushVertex( vertex ) { - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); - break; + } - default: // ZeroCurvatureEnding + function getVertexByIndex( index, vertex ) { - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + const stride = index * 3; - } + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; } - const halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; - - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + function correctUVs() { - }, + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); - interpolate_: function ( i1, t0, t, t1 ) { + const centroid = new Vector3(); - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); - // evaluate polynomials + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); - const sP = - wP * ppp + 2 * wP * pp - wP * p; - const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; - const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - const sN = wN * ppp - wN * pp; + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); - // combine data linearly + const azi = azimuth( centroid ); - for ( let i = 0; i !== stride; ++ i ) { + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; + } } - return result; + function correctUV( uv, stride, vector, azimuth ) { - } + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { -} ); + uvBuffer[ stride ] = uv.x - 1; -function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + } - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { -} + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; -LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + } - constructor: LinearInterpolant, + } - interpolate_: function ( i1, t0, t, t1 ) { + // Angle around the Y axis, counter-clockwise when looking from above. - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + function azimuth( vector ) { - offset1 = i1 * stride, - offset0 = offset1 - stride, + return Math.atan2( vector.z, - vector.x ); - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + } - for ( let i = 0; i !== stride; ++ i ) { - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + // Angle above the XZ plane. - } + function inclination( vector ) { - return result; + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - } + } -} ); + } -/** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - */ + static fromJSON( data ) { -function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details ); - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + } } -DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { +class DodecahedronGeometry extends PolyhedronGeometry { - constructor: DiscreteInterpolant, + constructor( radius = 1, detail = 0 ) { - interpolate_: function ( i1 /*, t0, t, t1 */ ) { + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + const r = 1 / t; - return this.copySampleValue_( i1 - 1 ); + const 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, -class KeyframeTrack { + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, - constructor( name, times, values, interpolation ) { + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; - if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); - if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); + const 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 + ]; - this.name = name; + super( vertices, indices, radius, detail ); - this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); + this.type = 'DodecahedronGeometry'; - this.setInterpolation( interpolation || this.DefaultInterpolation ); + this.parameters = { + radius: radius, + detail: detail + }; } - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): - - static toJSON( track ) { - - const trackType = track.constructor; - - let json; + static fromJSON( data ) { - // derived classes can define a static toJSON method - if ( trackType.toJSON !== this.toJSON ) { + return new DodecahedronGeometry( data.radius, data.detail ); - json = trackType.toJSON( track ); + } - } else { +} - // by default, we assume the data can be serialized as-is - json = { +const _v0 = /*@__PURE__*/ new Vector3(); +const _v1$1 = /*@__PURE__*/ new Vector3(); +const _normal = /*@__PURE__*/ new Vector3(); +const _triangle = /*@__PURE__*/ new Triangle(); - 'name': track.name, - 'times': AnimationUtils.convertArray( track.times, Array ), - 'values': AnimationUtils.convertArray( track.values, Array ) +class EdgesGeometry extends BufferGeometry { - }; + constructor( geometry = null, thresholdAngle = 1 ) { - const interpolation = track.getInterpolation(); + super(); - if ( interpolation !== track.DefaultInterpolation ) { + this.type = 'EdgesGeometry'; - json.interpolation = interpolation; + this.parameters = { + geometry: geometry, + thresholdAngle: thresholdAngle + }; - } + if ( geometry !== null ) { - } + const precisionPoints = 4; + const precision = Math.pow( 10, precisionPoints ); + const thresholdDot = Math.cos( DEG2RAD * thresholdAngle ); - json.type = track.ValueTypeName; // mandatory + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute( 'position' ); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; - return json; + const indexArr = [ 0, 0, 0 ]; + const vertKeys = [ 'a', 'b', 'c' ]; + const hashes = new Array( 3 ); - } + const edgeData = {}; + const vertices = []; + for ( let i = 0; i < indexCount; i += 3 ) { - InterpolantFactoryMethodDiscrete( result ) { + if ( indexAttr ) { - return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); + indexArr[ 0 ] = indexAttr.getX( i ); + indexArr[ 1 ] = indexAttr.getX( i + 1 ); + indexArr[ 2 ] = indexAttr.getX( i + 2 ); - } + } else { - InterpolantFactoryMethodLinear( result ) { + indexArr[ 0 ] = i; + indexArr[ 1 ] = i + 1; + indexArr[ 2 ] = i + 2; - return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); + } - } + const { a, b, c } = _triangle; + a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); + b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); + c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); + _triangle.getNormal( _normal ); - InterpolantFactoryMethodSmooth( result ) { + // create hashes for the edge from the vertices + hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; + hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; + hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; - return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + // skip degenerate triangles + if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { - } + continue; - setInterpolation( interpolation ) { + } - let factoryMethod; + // iterate over every edge + for ( let j = 0; j < 3; j ++ ) { - switch ( interpolation ) { + // get the first and next vertex making up the edge + const jNext = ( j + 1 ) % 3; + const vecHash0 = hashes[ j ]; + const vecHash1 = hashes[ jNext ]; + const v0 = _triangle[ vertKeys[ j ] ]; + const v1 = _triangle[ vertKeys[ jNext ] ]; - case InterpolateDiscrete: + const hash = `${ vecHash0 }_${ vecHash1 }`; + const reverseHash = `${ vecHash1 }_${ vecHash0 }`; - factoryMethod = this.InterpolantFactoryMethodDiscrete; + if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { - break; + // if we found a sibling edge add it into the vertex array if + // it meets the angle threshold and delete the edge from the map. + if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { - case InterpolateLinear: + vertices.push( v0.x, v0.y, v0.z ); + vertices.push( v1.x, v1.y, v1.z ); - factoryMethod = this.InterpolantFactoryMethodLinear; + } - break; + edgeData[ reverseHash ] = null; - case InterpolateSmooth: + } else if ( ! ( hash in edgeData ) ) { - factoryMethod = this.InterpolantFactoryMethodSmooth; + // if we've already got an edge here then skip adding a new one + edgeData[ hash ] = { - break; + index0: indexArr[ j ], + index1: indexArr[ jNext ], + normal: _normal.clone(), - } + }; - if ( factoryMethod === undefined ) { + } - const 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 ) { + // iterate over all remaining, unmatched edges and add them to the vertex array + for ( const key in edgeData ) { - this.setInterpolation( this.DefaultInterpolation ); + if ( edgeData[ key ] ) { - } else { + const { index0, index1 } = edgeData[ key ]; + _v0.fromBufferAttribute( positionAttr, index0 ); + _v1$1.fromBufferAttribute( positionAttr, index1 ); - throw new Error( message ); // fatal, in this case + vertices.push( _v0.x, _v0.y, _v0.z ); + vertices.push( _v1$1.x, _v1$1.y, _v1$1.z ); } } - console.warn( 'THREE.KeyframeTrack:', message ); - return this; + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); } - this.createInterpolant = factoryMethod; + } - return this; +} - } +class Shape extends Path { - getInterpolation() { + constructor( points ) { - switch ( this.createInterpolant ) { + super( points ); - case this.InterpolantFactoryMethodDiscrete: + this.uuid = generateUUID(); - return InterpolateDiscrete; + this.type = 'Shape'; - case this.InterpolantFactoryMethodLinear: + this.holes = []; - return InterpolateLinear; + } - case this.InterpolantFactoryMethodSmooth: + getPointsHoles( divisions ) { - return InterpolateSmooth; + const holesPts = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); } + return holesPts; + } - getValueSize() { + // get points of shape and holes (keypoints based on segments parameter) - return this.values.length / this.times.length; + extractPoints( divisions ) { + + return { + + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + + }; } - // move all keyframes either forwards or backwards in time - shift( timeOffset ) { + copy( source ) { - if ( timeOffset !== 0.0 ) { + super.copy( source ); - const times = this.times; + this.holes = []; - for ( let i = 0, n = times.length; i !== n; ++ i ) { + for ( let i = 0, l = source.holes.length; i < l; i ++ ) { - times[ i ] += timeOffset; + const hole = source.holes[ i ]; - } + this.holes.push( hole.clone() ); } @@ -33154,2658 +34015,2853 @@ class KeyframeTrack { } - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale( timeScale ) { - - if ( timeScale !== 1.0 ) { + toJSON() { - const times = this.times; + const data = super.toJSON(); - for ( let i = 0, n = times.length; i !== n; ++ i ) { + data.uuid = this.uuid; + data.holes = []; - times[ i ] *= timeScale; + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { - } + const hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); } - return this; + return data; } - // 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( startTime, endTime ) { + fromJSON( json ) { - const times = this.times, - nKeys = times.length; + super.fromJSON( json ); - let from = 0, - to = nKeys - 1; + this.uuid = json.uuid; + this.holes = []; - while ( from !== nKeys && times[ from ] < startTime ) { + for ( let i = 0, l = json.holes.length; i < l; i ++ ) { - ++ from; + const hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); } - while ( to !== - 1 && times[ to ] > endTime ) { + return this; - -- to; + } - } +} - ++ to; // inclusive -> exclusive bound +/** + * Port from https://github.com/mapbox/earcut (v2.2.2) + */ - if ( from !== 0 || to !== nKeys ) { +const Earcut = { - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) { + triangulate: function ( data, holeIndices, dim = 2 ) { - to = Math.max( to, 1 ); - from = to - 1; + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; + let outerNode = linkedList( data, 0, outerLen, dim, true ); + const triangles = []; + + if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + + let minX, minY, maxX, maxY, x, y, invSize; + + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if ( data.length > 80 * dim ) { + + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; + + for ( let i = dim; i < outerLen; i += dim ) { + + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; } - const stride = this.getValueSize(); - this.times = AnimationUtils.arraySlice( times, from, to ); - this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride ); + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 1 / invSize : 0; } - return this; + earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); + + return triangles; } - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate() { +}; - let valid = true; +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList( data, start, end, dim, clockwise ) { - const valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { + let i, last; - console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); - valid = false; + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { - } + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); - const times = this.times, - values = this.values, + } else { - nKeys = times.length; + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); - if ( nKeys === 0 ) { + } - console.error( 'THREE.KeyframeTrack: Track is empty.', this ); - valid = false; + if ( last && equals( last, last.next ) ) { - } + removeNode( last ); + last = last.next; - let prevTime = null; + } - for ( let i = 0; i !== nKeys; i ++ ) { + return last; - const currTime = times[ i ]; +} - if ( typeof currTime === 'number' && isNaN( currTime ) ) { +// eliminate colinear or duplicate points +function filterPoints( start, end ) { - console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); - valid = false; - break; + if ( ! start ) return start; + if ( ! end ) end = start; - } + let p = start, + again; + do { - if ( prevTime !== null && prevTime > currTime ) { + again = false; - console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); - valid = false; - break; + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { - } + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; - prevTime = currTime; + } else { + + p = p.next; } - if ( values !== undefined ) { + } while ( again || p !== end ); - if ( AnimationUtils.isTypedArray( values ) ) { + return end; - for ( let i = 0, n = values.length; i !== n; ++ i ) { +} - const value = values[ i ]; +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { - if ( isNaN( value ) ) { + if ( ! ear ) return; - console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); - valid = false; - break; + // interlink polygon nodes in z-order + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); - } + let stop = ear, + prev, next; - } + // iterate through ears, slicing them one by one + while ( ear.prev !== ear.next ) { - } + prev = ear.prev; + next = ear.next; + + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + + // cut off the triangle + triangles.push( prev.i / dim ); + triangles.push( ear.i / dim ); + triangles.push( next.i / dim ); + + removeNode( ear ); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; } - return valid; + ear = next; - } + // if we looped through the whole remaining polygon and can't find any more ears + if ( ear === stop ) { - // 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() { + // try filtering points and slicing again + if ( ! pass ) { - // times or values may be shared with other tracks, so overwriting is unsafe - const times = AnimationUtils.arraySlice( this.times ), - values = AnimationUtils.arraySlice( this.values ), - stride = this.getValueSize(), + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); - smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + // if this didn't work, try curing all small self-intersections locally - lastIndex = times.length - 1; + } else if ( pass === 1 ) { - let writeIndex = 1; + ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); - for ( let i = 1; i < lastIndex; ++ i ) { + // as a last resort, try splitting the remaining polygon into two - let keep = false; + } else if ( pass === 2 ) { - const time = times[ i ]; - const timeNext = times[ i + 1 ]; + splitEarcut( ear, triangles, dim, minX, minY, invSize ); - // remove adjacent keyframes scheduled at the same time + } - if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { + break; - if ( ! smoothInterpolation ) { + } - // remove unnecessary keyframes same as their neighbors + } - const offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; +} - for ( let j = 0; j !== stride; ++ j ) { +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar( ear ) { - const value = values[ offset + j ]; + const a = ear.prev, + b = ear, + c = ear.next; - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - keep = true; - break; + // now make sure we don't have other points inside the potential ear + let p = ear.next.next; - } + while ( p !== ear.prev ) { - } + if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.next; - } else { + } - keep = true; + return true; - } +} - } +function isEarHashed( ear, minX, minY, invSize ) { - // in-place compaction + const a = ear.prev, + b = ear, + c = ear.next; - if ( keep ) { + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - if ( i !== writeIndex ) { + // triangle bbox; min & max are calculated like this for speed + const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), + minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), + maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), + maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); - times[ writeIndex ] = times[ i ]; + // z-order range for the current triangle bbox; + const minZ = zOrder( minTX, minTY, minX, minY, invSize ), + maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); - const readOffset = i * stride, - writeOffset = writeIndex * stride; + let p = ear.prevZ, + n = ear.nextZ; - for ( let j = 0; j !== stride; ++ j ) { + // look for points inside the triangle in both directions + while ( p && p.z >= minZ && n && n.z <= maxZ ) { - values[ writeOffset + j ] = values[ readOffset + j ]; + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; - } + if ( n !== ear.prev && n !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && + area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; - } + } - ++ writeIndex; + // look for remaining points in decreasing z-order + while ( p && p.z >= minZ ) { - } + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; - } + } - // flush last keyframe (compaction looks ahead) + // look for remaining points in increasing z-order + while ( n && n.z <= maxZ ) { - if ( lastIndex > 0 ) { + if ( n !== ear.prev && n !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && + area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; - times[ writeIndex ] = times[ lastIndex ]; + } - for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { + return true; - values[ writeOffset + j ] = values[ readOffset + j ]; +} - } +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections( start, triangles, dim ) { - ++ writeIndex; + let p = start; + do { - } + const a = p.prev, + b = p.next.next; - if ( writeIndex !== times.length ) { + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { - this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + triangles.push( a.i / dim ); + triangles.push( p.i / dim ); + triangles.push( b.i / dim ); - } else { + // remove two nodes involved + removeNode( p ); + removeNode( p.next ); - this.times = times; - this.values = values; + p = start = b; } - return this; + p = p.next; - } + } while ( p !== start ); - clone() { + return filterPoints( p ); - const times = AnimationUtils.arraySlice( this.times, 0 ); - const values = AnimationUtils.arraySlice( this.values, 0 ); +} - const TypedKeyframeTrack = this.constructor; - const track = new TypedKeyframeTrack( this.name, times, values ); +// try splitting polygon into two and triangulate them independently +function splitEarcut( start, triangles, dim, minX, minY, invSize ) { - // Interpolant argument to constructor is not saved, so copy the factory method directly. - track.createInterpolant = this.createInterpolant; + // look for a valid diagonal that divides the polygon into two + let a = start; + do { - return track; + let b = a.next.next; + while ( b !== a.prev ) { - } + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { -} + // split the polygon in two by the diagonal + let c = splitPolygon( a, b ); -KeyframeTrack.prototype.TimeBufferType = Float32Array; -KeyframeTrack.prototype.ValueBufferType = Float32Array; -KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + // filter colinear points around the cuts + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); -/** - * A Track of Boolean keyframe values. - */ -class BooleanKeyframeTrack extends KeyframeTrack {} + // run earcut on each half + earcutLinked( a, triangles, dim, minX, minY, invSize ); + earcutLinked( c, triangles, dim, minX, minY, invSize ); + return; -BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; -BooleanKeyframeTrack.prototype.ValueBufferType = Array; -BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; -BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; -BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + } -/** - * A Track of keyframe values that represent color. - */ -class ColorKeyframeTrack extends KeyframeTrack {} + b = b.next; -ColorKeyframeTrack.prototype.ValueTypeName = 'color'; + } -/** - * A Track of numeric keyframe values. - */ -class NumberKeyframeTrack extends KeyframeTrack {} + a = a.next; -NumberKeyframeTrack.prototype.ValueTypeName = 'number'; + } while ( a !== start ); -/** - * Spherical linear unit quaternion interpolant. - */ +} -function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles( data, holeIndices, outerNode, dim ) { - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + const queue = []; + let i, len, start, end, list; -} + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { -QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); - constructor: QuaternionLinearInterpolant, + } - interpolate_: function ( i1, t0, t, t1 ) { + queue.sort( compareX ); - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { - alpha = ( t - t0 ) / ( t1 - t0 ); + eliminateHole( queue[ i ], outerNode ); + outerNode = filterPoints( outerNode, outerNode.next ); - let offset = i1 * stride; + } - for ( let end = offset + stride; offset !== end; offset += 4 ) { + return outerNode; - Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); +} - } +function compareX( a, b ) { - return result; + return a.x - b.x; - } +} -} ); +// find a bridge between vertices that connects hole with an outer ring and link it +function eliminateHole( hole, outerNode ) { -/** - * A Track of quaternion keyframe values. - */ -class QuaternionKeyframeTrack extends KeyframeTrack { + outerNode = findHoleBridge( hole, outerNode ); + if ( outerNode ) { - InterpolantFactoryMethodLinear( result ) { + const b = splitPolygon( outerNode, hole ); - return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); + // filter collinear points around the cuts + filterPoints( outerNode, outerNode.next ); + filterPoints( b, b.next ); } } -QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; -// ValueBufferType is inherited -QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; -QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - -/** - * A Track that interpolates Strings - */ -class StringKeyframeTrack extends KeyframeTrack {} +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge( hole, outerNode ) { -StringKeyframeTrack.prototype.ValueTypeName = 'string'; -StringKeyframeTrack.prototype.ValueBufferType = Array; -StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; -StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; -StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = - Infinity, m; -/** - * A Track of vectored keyframe values. - */ -class VectorKeyframeTrack extends KeyframeTrack {} + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { -VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { -class AnimationClip { + const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); + if ( x <= hx && x > qx ) { - constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) { + qx = x; + if ( x === hx ) { - this.name = name; - this.tracks = tracks; - this.duration = duration; - this.blendMode = blendMode; + if ( hy === p.y ) return p; + if ( hy === p.next.y ) return p.next; - this.uuid = MathUtils.generateUUID(); + } - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { + m = p.x < p.next.x ? p : p.next; - this.resetDuration(); + } } - } - + p = p.next; - static parse( json ) { + } while ( p !== outerNode ); - const tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); + if ( ! m ) return null; - for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { + if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint - tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point - } + const stop = m, + mx = m.x, + my = m.y; + let tanMin = Infinity, tan; - const clip = new this( json.name, json.duration, tracks, json.blendMode ); - clip.uuid = json.uuid; + p = m; - return clip; + do { - } + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { - static toJSON( clip ) { + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential - const tracks = [], - clipTracks = clip.tracks; + if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { - const json = { + m = p; + tanMin = tan; - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks, - 'uuid': clip.uuid, - 'blendMode': clip.blendMode + } - }; + } - for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { + p = p.next; - tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + } while ( p !== stop ); - } + return m; - return json; +} - } +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector( m, p ) { - static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { + return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; - const numMorphTargets = morphTargetSequence.length; - const tracks = []; +} - for ( let i = 0; i < numMorphTargets; i ++ ) { +// interlink polygon nodes in z-order +function indexCurve( start, minX, minY, invSize ) { - let times = []; - let values = []; + let p = start; + do { - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); + if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; - values.push( 0, 1, 0 ); + } while ( p !== start ); - const order = AnimationUtils.getKeyframeOrder( times ); - times = AnimationUtils.sortedArray( times, 1, order ); - values = AnimationUtils.sortedArray( values, 1, order ); + p.prevZ.nextZ = null; + p.prevZ = null; - // 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 ) { + sortLinked( p ); - times.push( numMorphTargets ); - values.push( values[ 0 ] ); +} - } +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked( list ) { - tracks.push( - new NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); + let i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; - } + do { - return new this( name, - 1, tracks ); + p = list; + list = null; + tail = null; + numMerges = 0; - } + while ( p ) { - static findByName( objectOrClipArray, name ) { + numMerges ++; + q = p; + pSize = 0; + for ( i = 0; i < inSize; i ++ ) { - let clipArray = objectOrClipArray; + pSize ++; + q = q.nextZ; + if ( ! q ) break; - if ( ! Array.isArray( objectOrClipArray ) ) { + } - const o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + qSize = inSize; - } + while ( pSize > 0 || ( qSize > 0 && q ) ) { - for ( let i = 0; i < clipArray.length; i ++ ) { + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { - if ( clipArray[ i ].name === name ) { + e = p; + p = p.nextZ; + pSize --; - return clipArray[ i ]; + } else { - } + e = q; + q = q.nextZ; + qSize --; - } + } - return null; + if ( tail ) tail.nextZ = e; + else list = e; - } + e.prevZ = tail; + tail = e; - static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { + } - const animationToMorphTargets = {}; + p = q; - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - const pattern = /^([\w-]*?)([\d]+)$/; + } - // sort morph target names into animation groups based - // patterns like Walk_001, Walk_002, Run_001, Run_002 - for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { + tail.nextZ = null; + inSize *= 2; - const morphTarget = morphTargets[ i ]; - const parts = morphTarget.name.match( pattern ); + } while ( numMerges > 1 ); - if ( parts && parts.length > 1 ) { + return list; - const name = parts[ 1 ]; +} - let animationMorphTargets = animationToMorphTargets[ name ]; +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder( x, y, minX, minY, invSize ) { - if ( ! animationMorphTargets ) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * ( x - minX ) * invSize; + y = 32767 * ( y - minY ) * invSize; - animationToMorphTargets[ name ] = animationMorphTargets = []; + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; - } + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; - animationMorphTargets.push( morphTarget ); + return x | ( y << 1 ); - } +} - } +// find the leftmost node of a polygon ring +function getLeftmost( start ) { - const clips = []; + let p = start, + leftmost = start; + do { - for ( const name in animationToMorphTargets ) { + if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; + p = p.next; - clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + } while ( p !== start ); - } + return leftmost; - return clips; +} - } +// check if a point lies within a convex triangle +function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { - // parse the animation.hierarchy format - static parseAnimation( animation, bones ) { + return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && + ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && + ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; - if ( ! animation ) { +} - console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); - return null; +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal( a, b ) { - } + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges + ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible + ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case - const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { +} - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { +// signed area of a triangle +function area( p, q, r ) { - const times = []; - const values = []; + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); - AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); +} - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { +// check if two points are equal +function equals( p1, p2 ) { - destTracks.push( new trackType( trackName, times, values ) ); + return p1.x === p2.x && p1.y === p2.y; - } +} - } +// check if two segments intersect +function intersects( p1, q1, p2, q2 ) { - }; + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); - const tracks = []; + if ( o1 !== o2 && o3 !== o4 ) return true; // general case - const clipName = animation.name || 'default'; - const fps = animation.fps || 30; - const blendMode = animation.blendMode; + if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 - // automatic length determination in AnimationClip. - let duration = animation.length || - 1; + return false; - const hierarchyTracks = animation.hierarchy || []; +} - for ( let h = 0; h < hierarchyTracks.length; h ++ ) { +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment( p, q, r ) { - const animationKeys = hierarchyTracks[ h ].keys; + return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); - // skip empty tracks - if ( ! animationKeys || animationKeys.length === 0 ) continue; +} - // process morph targets - if ( animationKeys[ 0 ].morphTargets ) { +function sign( num ) { - // figure out all morph targets used in this track - const morphTargetNames = {}; + return num > 0 ? 1 : num < 0 ? - 1 : 0; - let k; +} - for ( k = 0; k < animationKeys.length; k ++ ) { +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon( a, b ) { - if ( animationKeys[ k ].morphTargets ) { + let p = a; + do { - for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) return true; + p = p.next; - morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; + } while ( p !== a ); - } + return false; - } +} - } +// check if a polygon diagonal is locally inside the polygon +function locallyInside( a, b ) { - // create a track for each morph target with all zero - // morphTargetInfluences except for the keys in which - // the morphTarget is named. - for ( const morphTargetName in morphTargetNames ) { + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; - const times = []; - const values = []; +} - for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside( a, b ) { - const animationKey = animationKeys[ k ]; + let p = a, + inside = false; + const px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; + do { - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) + inside = ! inside; + p = p.next; - } + } while ( p !== a ); - tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + return inside; - } +} - duration = morphTargetNames.length * ( fps || 1.0 ); +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon( a, b ) { - } else { + const a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; - // ...assume skeletal animation + a.next = b; + b.prev = a; - const boneName = '.bones[' + bones[ h ].name + ']'; + a2.next = an; + an.prev = a2; - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + b2.next = a2; + a2.prev = b2; - addNonemptyTrack( - QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + bp.next = b2; + b2.prev = bp; - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + return b2; - } +} - } +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode( i, x, y, last ) { - if ( tracks.length === 0 ) { + const p = new Node( i, x, y ); - return null; + if ( ! last ) { - } + p.prev = p; + p.next = p; - const clip = new this( clipName, duration, tracks, blendMode ); + } else { - return clip; + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; } - resetDuration() { + return p; - const tracks = this.tracks; - let duration = 0; +} - for ( let i = 0, n = tracks.length; i !== n; ++ i ) { +function removeNode( p ) { - const track = this.tracks[ i ]; + p.next.prev = p.prev; + p.prev.next = p.next; - duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; - } +} - this.duration = duration; +function Node( i, x, y ) { - return this; + // vertex index in coordinates array + this.i = i; - } + // vertex coordinates + this.x = x; + this.y = y; - trim() { + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; - for ( let i = 0; i < this.tracks.length; i ++ ) { + // z-order curve value + this.z = null; - this.tracks[ i ].trim( 0, this.duration ); + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; - } + // indicates whether this is a steiner point + this.steiner = false; - return this; +} - } +function signedArea( data, start, end, dim ) { - validate() { + let sum = 0; + for ( let i = start, j = end - dim; i < end; i += dim ) { - let valid = true; + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; - for ( let i = 0; i < this.tracks.length; i ++ ) { + } - valid = valid && this.tracks[ i ].validate(); + return sum; - } +} - return valid; +class ShapeUtils { - } + // calculate area of the contour polygon - optimize() { + static area( contour ) { - for ( let i = 0; i < this.tracks.length; i ++ ) { + const n = contour.length; + let a = 0.0; - this.tracks[ i ].optimize(); + for ( let p = n - 1, q = 0; q < n; p = q ++ ) { + + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; } - return this; + return a * 0.5; } - clone() { + static isClockWise( pts ) { - const tracks = []; + return ShapeUtils.area( pts ) < 0; - for ( let i = 0; i < this.tracks.length; i ++ ) { + } - tracks.push( this.tracks[ i ].clone() ); + static triangulateShape( contour, holes ) { - } + const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + const holeIndices = []; // array of hole indices + const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] - return new this.constructor( this.name, this.duration, tracks, this.blendMode ); + removeDupEndPts( contour ); + addContour( vertices, contour ); - } + // - toJSON() { + let holeIndex = contour.length; - return this.constructor.toJSON( this ); + holes.forEach( removeDupEndPts ); - } + for ( let i = 0; i < holes.length; i ++ ) { -} + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); -function getTrackTypeForValueTypeName( typeName ) { + } - switch ( typeName.toLowerCase() ) { + // - case 'scalar': - case 'double': - case 'float': - case 'number': - case 'integer': + const triangles = Earcut.triangulate( vertices, holeIndices ); - return NumberKeyframeTrack; + // - case 'vector': - case 'vector2': - case 'vector3': - case 'vector4': + for ( let i = 0; i < triangles.length; i += 3 ) { - return VectorKeyframeTrack; + faces.push( triangles.slice( i, i + 3 ) ); - case 'color': + } - return ColorKeyframeTrack; + return faces; - case 'quaternion': + } - return QuaternionKeyframeTrack; +} - case 'bool': - case 'boolean': +function removeDupEndPts( points ) { - return BooleanKeyframeTrack; + const l = points.length; - case 'string': + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - return StringKeyframeTrack; + points.pop(); } - throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); - } -function parseKeyframeTrack( json ) { +function addContour( vertices, contour ) { - if ( json.type === undefined ) { + for ( let i = 0; i < contour.length; i ++ ) { - throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); } - const trackType = getTrackTypeForValueTypeName( json.type ); +} - if ( json.times === undefined ) { +/** + * 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 + * depth: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline (including bevelOffset) is bevel + * bevelOffset: , // how far from shape outline does bevel start + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ - const times = [], values = []; +class ExtrudeGeometry extends BufferGeometry { - AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) { - json.times = times; - json.values = values; + super(); - } + this.type = 'ExtrudeGeometry'; - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { + this.parameters = { + shapes: shapes, + options: options + }; - return trackType.parse( json ); + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - } else { + const scope = this; - // by default, we assume a constructor compatible with the base - return new trackType( json.name, json.times, json.values, json.interpolation ); + const verticesArray = []; + const uvArray = []; - } + for ( let i = 0, l = shapes.length; i < l; i ++ ) { -} + const shape = shapes[ i ]; + addShape( shape ); -const Cache = { + } - enabled: false, + // build geometry - files: {}, + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); - add: function ( key, file ) { + this.computeVertexNormals(); - if ( this.enabled === false ) return; + // functions - // console.log( 'THREE.Cache', 'Adding key:', key ); + function addShape( shape ) { - this.files[ key ] = file; + const placeholder = []; - }, + // options - get: function ( key ) { + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; - if ( this.enabled === false ) return; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - // console.log( 'THREE.Cache', 'Checking key:', key ); + const extrudePath = options.extrudePath; - return this.files[ key ]; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; - }, + // - remove: function ( key ) { + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; - delete this.files[ key ]; + if ( extrudePath ) { - }, + extrudePts = extrudePath.getSpacedPoints( steps ); - clear: function () { + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - this.files = {}; + // SETUP TNB variables - } + // TODO1 - have a .isClosed in spline? -}; + splineTube = extrudePath.computeFrenetFrames( steps, false ); -function LoadingManager( onLoad, onProgress, onError ) { + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - const scope = this; + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + + } - let isLoading = false; - let itemsLoaded = 0; - let itemsTotal = 0; - let urlModifier = undefined; - const handlers = []; + // Safeguards if bevels are not enabled - // Refer to #5689 for the reason why we don't set .onStart - // in the constructor + if ( ! bevelEnabled ) { - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; - this.itemStart = function ( url ) { + } - itemsTotal ++; + // Variables initialization - if ( isLoading === false ) { + const shapePoints = shape.extractPoints( curveSegments ); - if ( scope.onStart !== undefined ) { + let vertices = shapePoints.shape; + const holes = shapePoints.holes; - scope.onStart( url, itemsLoaded, itemsTotal ); + const reverse = ! ShapeUtils.isClockWise( vertices ); - } + if ( reverse ) { - } + vertices = vertices.reverse(); - isLoading = true; + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - }; + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - this.itemEnd = function ( url ) { + const ahole = holes[ h ]; - itemsLoaded ++; + if ( ShapeUtils.isClockWise( ahole ) ) { - if ( scope.onProgress !== undefined ) { + holes[ h ] = ahole.reverse(); - scope.onProgress( url, itemsLoaded, itemsTotal ); + } - } + } - if ( itemsLoaded === itemsTotal ) { + } - isLoading = false; - if ( scope.onLoad !== undefined ) { + const faces = ShapeUtils.triangulateShape( vertices, holes ); - scope.onLoad(); + /* Vertices */ - } + const contour = vertices; // vertices has all points but contour has only points of circumference - } + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - }; + const ahole = holes[ h ]; - this.itemError = function ( url ) { + vertices = vertices.concat( ahole ); - if ( scope.onError !== undefined ) { + } - scope.onError( url ); - } + function scalePt2( pt, vec, size ) { - }; + if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); - this.resolveURL = function ( url ) { + return vec.clone().multiplyScalar( size ).add( pt ); - if ( urlModifier ) { + } - return urlModifier( url ); + const vlen = vertices.length, flen = faces.length; - } - return url; + // Find directions for point movement - }; - this.setURLModifier = function ( transform ) { + function getBevelVec( inPt, inPrev, inNext ) { - urlModifier = transform; + // 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. - return this; + let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt - }; + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - this.addHandler = function ( regex, loader ) { + const v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; - handlers.push( regex, loader ); + const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - return this; + // check for collinear edges + const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - }; + if ( Math.abs( collinear0 ) > Number.EPSILON ) { - this.removeHandler = function ( regex ) { + // not collinear - const index = handlers.indexOf( regex ); + // length of vectors for normalizing - if ( index !== - 1 ) { + const v_prev_len = Math.sqrt( v_prev_lensq ); + const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - handlers.splice( index, 2 ); + // shift adjacent points by unit vectors to the left - } + const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - return this; + const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - }; + // scaling factor for v_prev to intersection point + + const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + // vector from inPt to intersection point - this.getHandler = function ( file ) { + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - for ( let i = 0, l = handlers.length; i < l; i += 2 ) { + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { - const regex = handlers[ i ]; - const loader = handlers[ i + 1 ]; + return new Vector2( v_trans_x, v_trans_y ); - if ( regex.global ) regex.lastIndex = 0; // see #17920 + } else { - if ( regex.test( file ) ) { + shrink_by = Math.sqrt( v_trans_lensq / 2 ); - return loader; + } - } + } else { - } + // handle special case of collinear edges - return null; + let direction_eq = false; // assumes: opposite - }; + if ( v_prev_x > Number.EPSILON ) { -} + if ( v_next_x > Number.EPSILON ) { -const DefaultLoadingManager = new LoadingManager(); + direction_eq = true; -function Loader( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + } else { - this.crossOrigin = 'anonymous'; - this.withCredentials = false; - this.path = ''; - this.resourcePath = ''; - this.requestHeader = {}; + if ( v_prev_x < - Number.EPSILON ) { -} + if ( v_next_x < - Number.EPSILON ) { -Object.assign( Loader.prototype, { + direction_eq = true; - load: function ( /* url, onLoad, onProgress, onError */ ) {}, + } - loadAsync: function ( url, onProgress ) { + } else { - const scope = this; + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { - return new Promise( function ( resolve, reject ) { + direction_eq = true; - scope.load( url, resolve, onProgress, reject ); + } - } ); + } - }, + } - parse: function ( /* data */ ) {}, + if ( direction_eq ) { - setCrossOrigin: function ( crossOrigin ) { + // 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 ); - this.crossOrigin = crossOrigin; - return this; + } 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 ); - setWithCredentials: function ( value ) { + } - this.withCredentials = value; - return this; + } - }, + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - setPath: function ( path ) { + } - this.path = path; - return this; - }, + const contourMovements = []; - setResourcePath: function ( resourcePath ) { + for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - this.resourcePath = resourcePath; - return this; + if ( j === il ) j = 0; + if ( k === il ) k = 0; - }, + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) - setRequestHeader: function ( requestHeader ) { + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - this.requestHeader = requestHeader; - return this; + } - } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); -} ); + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { -const loading = {}; + const ahole = holes[ h ]; -function FileLoader( manager ) { + oneHoleMovements = []; - Loader.call( this, manager ); + for ( let 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; -FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - constructor: FileLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - if ( url === undefined ) url = ''; + } - if ( this.path !== undefined ) url = this.path + url; - url = this.manager.resolveURL( url ); + // Loop bevelSegments, 1 for the front, 1 for the back - const scope = this; + for ( let b = 0; b < bevelSegments; b ++ ) { - const cached = Cache.get( url ); + //for ( b = bevelSegments; b > 0; b -- ) { - if ( cached !== undefined ) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; - scope.manager.itemStart( url ); + // contract shape - setTimeout( function () { + for ( let i = 0, il = contour.length; i < il; i ++ ) { - if ( onLoad ) onLoad( cached ); + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - scope.manager.itemEnd( url ); + v( vert.x, vert.y, - z ); - }, 0 ); + } - return cached; + // expand holes - } + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - // Check if request is duplicate + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - if ( loading[ url ] !== undefined ) { + for ( let i = 0, il = ahole.length; i < il; i ++ ) { - loading[ url ].push( { + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - onLoad: onLoad, - onProgress: onProgress, - onError: onError + v( vert.x, vert.y, - z ); - } ); + } - return; + } - } + } - // Check for data: URI - const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/; - const dataUriRegexResult = url.match( dataUriRegex ); - let request; + const bs = bevelSize + bevelOffset; - // Safari can not handle Data URIs through XMLHttpRequest so process manually - if ( dataUriRegexResult ) { + // Back facing vertices - const mimeType = dataUriRegexResult[ 1 ]; - const isBase64 = !! dataUriRegexResult[ 2 ]; + for ( let i = 0; i < vlen; i ++ ) { - let data = dataUriRegexResult[ 3 ]; - data = decodeURIComponent( data ); + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - if ( isBase64 ) data = atob( data ); + if ( ! extrudeByPath ) { - try { + v( vert.x, vert.y, 0 ); - let response; - const responseType = ( this.responseType || '' ).toLowerCase(); + } else { - switch ( responseType ) { + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - case 'arraybuffer': - case 'blob': + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - const view = new Uint8Array( data.length ); + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - for ( let i = 0; i < data.length; i ++ ) { + v( position2.x, position2.y, position2.z ); - view[ i ] = data.charCodeAt( i ); + } - } + } - if ( responseType === 'blob' ) { + // Add stepped vertices... + // Including front facing vertices - response = new Blob( [ view.buffer ], { type: mimeType } ); + for ( let s = 1; s <= steps; s ++ ) { - } else { + for ( let i = 0; i < vlen; i ++ ) { - response = view.buffer; + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - } + if ( ! extrudeByPath ) { - break; + v( vert.x, vert.y, depth / steps * s ); - case 'document': + } else { - const parser = new DOMParser(); - response = parser.parseFromString( data, mimeType ); + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - break; + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - case 'json': + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); - response = JSON.parse( data ); + v( position2.x, position2.y, position2.z ); - break; + } - default: // 'text' or other + } - response = data; + } - break; - } + // Add bevel segments planes - // Wait for next browser tick like standard XMLHttpRequest event dispatching does - setTimeout( function () { + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( let b = bevelSegments - 1; b >= 0; b -- ) { - if ( onLoad ) onLoad( response ); + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; - scope.manager.itemEnd( url ); + // contract shape - }, 0 ); + for ( let i = 0, il = contour.length; i < il; i ++ ) { - } catch ( error ) { + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); - // Wait for next browser tick like standard XMLHttpRequest event dispatching does - setTimeout( function () { + } - if ( onError ) onError( error ); + // expand holes - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - }, 0 ); + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - } + for ( let i = 0, il = ahole.length; i < il; i ++ ) { - } else { + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - // Initialise array for duplicate requests + if ( ! extrudeByPath ) { - loading[ url ] = []; + v( vert.x, vert.y, depth + z ); - loading[ url ].push( { + } else { - onLoad: onLoad, - onProgress: onProgress, - onError: onError + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - } ); + } - request = new XMLHttpRequest(); + } - request.open( 'GET', url, true ); + } - request.addEventListener( 'load', function ( event ) { + } - const response = this.response; + /* Faces */ - const callbacks = loading[ url ]; + // Top and bottom faces - delete loading[ url ]; + buildLidFaces(); - if ( this.status === 200 || this.status === 0 ) { + // Sides faces - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + buildSideFaces(); - if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); - // Add to cache only on HTTP success, so that we do not cache - // error response bodies as proper responses to requests. - Cache.add( url, response ); + ///// Internal functions - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + function buildLidFaces() { - const callback = callbacks[ i ]; - if ( callback.onLoad ) callback.onLoad( response ); + const start = verticesArray.length / 3; - } + if ( bevelEnabled ) { - scope.manager.itemEnd( url ); + let layer = 0; // steps + 1 + let offset = vlen * layer; - } else { + // Bottom faces - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + for ( let i = 0; i < flen; i ++ ) { - const callback = callbacks[ i ]; - if ( callback.onError ) callback.onError( event ); + const face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); } - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + layer = steps + bevelSegments * 2; + offset = vlen * layer; - } + // Top faces - }, false ); + for ( let i = 0; i < flen; i ++ ) { - request.addEventListener( 'progress', function ( event ) { + const face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - const callbacks = loading[ url ]; + } - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + } else { - const callback = callbacks[ i ]; - if ( callback.onProgress ) callback.onProgress( event ); + // Bottom faces - } + for ( let i = 0; i < flen; i ++ ) { - }, false ); + const face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - request.addEventListener( 'error', function ( event ) { + } - const callbacks = loading[ url ]; + // Top faces - delete loading[ url ]; + for ( let i = 0; i < flen; i ++ ) { - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + const face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - const callback = callbacks[ i ]; - if ( callback.onError ) callback.onError( event ); + } } - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); - - }, false ); - - request.addEventListener( 'abort', function ( event ) { + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); - const callbacks = loading[ url ]; + } - delete loading[ url ]; + // Create faces for the z-sides of the shape - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + function buildSideFaces() { - const callback = callbacks[ i ]; - if ( callback.onError ) callback.onError( event ); + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - } + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + const ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - }, false ); + //, true + layeroffset += ahole.length; - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + } - if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); - for ( const header in this.requestHeader ) { + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); - request.setRequestHeader( header, this.requestHeader[ header ] ); } - request.send( null ); + function sidewalls( contour, layeroffset ) { - } + let i = contour.length; - scope.manager.itemStart( url ); + while ( -- i >= 0 ) { - return request; + const j = i; + let k = i - 1; + if ( k < 0 ) k = contour.length - 1; - }, + //console.log('b', i,j, i-1, k,vertices.length); - setResponseType: function ( value ) { + for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { - this.responseType = value; - return this; + const slen1 = vlen * s; + const slen2 = vlen * ( s + 1 ); - }, + const a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; - setMimeType: function ( value ) { + f4( a, b, c, d ); - this.mimeType = value; - return this; + } - } + } -} ); + } -class AnimationLoader extends Loader { + function v( x, y, z ) { - constructor( manager ) { + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); - super( manager ); + } - } - load( url, onLoad, onProgress, onError ) { + function f3( a, b, c ) { - const scope = this; + addVertex( a ); + addVertex( b ); + addVertex( c ); - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); - try { + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); - onLoad( scope.parse( JSON.parse( text ) ) ); + } - } catch ( e ) { + function f4( a, b, c, d ) { - if ( onError ) { + addVertex( a ); + addVertex( b ); + addVertex( d ); - onError( e ); + addVertex( b ); + addVertex( c ); + addVertex( d ); - } else { - console.error( e ); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); - } + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); - scope.manager.itemError( url ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); } - }, onProgress, onError ); + function addVertex( index ) { - } + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); - parse( json ) { + } - const animations = []; - for ( let i = 0; i < json.length; i ++ ) { + function addUV( vector2 ) { - const clip = AnimationClip.parse( json[ i ] ); + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); - animations.push( clip ); + } } - return animations; - } -} - -/** - * Abstract Base class to block based textures loader (dds, pvr, ...) - * - * Sub classes have to implement the parse() method which will be used in load(). - */ - -function CompressedTextureLoader( manager ) { + toJSON() { - Loader.call( this, manager ); + const data = super.toJSON(); -} + const shapes = this.parameters.shapes; + const options = this.parameters.options; -CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + return toJSON$1( shapes, options, data ); - constructor: CompressedTextureLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + static fromJSON( data, shapes ) { - const scope = this; + const geometryShapes = []; - const images = []; + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { - const texture = new CompressedTexture(); + const shape = shapes[ data.shapes[ j ] ]; - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); + geometryShapes.push( shape ); - let loaded = 0; + } - function loadTexture( i ) { + const extrudePath = data.options.extrudePath; - loader.load( url[ i ], function ( buffer ) { + if ( extrudePath !== undefined ) { - const texDatas = scope.parse( buffer, true ); + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + } - loaded += 1; + return new ExtrudeGeometry( geometryShapes, data.options ); - if ( loaded === 6 ) { + } - if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; +} - texture.image = images; - texture.format = texDatas.format; - texture.needsUpdate = true; +const WorldUVGenerator = { - if ( onLoad ) onLoad( texture ); + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { - } + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; - }, onProgress, onError ); + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; - } + }, - if ( Array.isArray( url ) ) { + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { - for ( let i = 0, il = url.length; i < il; ++ i ) { + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const a_z = vertices[ indexA * 3 + 2 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const b_z = vertices[ indexB * 3 + 2 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + const c_z = vertices[ indexC * 3 + 2 ]; + const d_x = vertices[ indexD * 3 ]; + const d_y = vertices[ indexD * 3 + 1 ]; + const d_z = vertices[ indexD * 3 + 2 ]; - loadTexture( i ); + if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) { - } + 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 ) + ]; } else { - // compressed cubemap texture stored in a single DDS file - - loader.load( url, function ( buffer ) { - - const texDatas = scope.parse( buffer, true ); + 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 ) + ]; - if ( texDatas.isCubemap ) { + } - const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + } - for ( let f = 0; f < faces; f ++ ) { +}; - images[ f ] = { mipmaps: [] }; +function toJSON$1( shapes, options, data ) { - for ( let i = 0; i < texDatas.mipmapCount; i ++ ) { + data.shapes = []; - 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; + if ( Array.isArray( shapes ) ) { - } + for ( let i = 0, l = shapes.length; i < l; i ++ ) { - } + const shape = shapes[ i ]; - texture.image = images; + data.shapes.push( shape.uuid ); - } else { + } - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + } else { - } + data.shapes.push( shapes.uuid ); - if ( texDatas.mipmapCount === 1 ) { + } - texture.minFilter = LinearFilter; + data.options = Object.assign( {}, options ); - } + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); - texture.format = texDatas.format; - texture.needsUpdate = true; + return data; - if ( onLoad ) onLoad( texture ); +} - }, onProgress, onError ); +class IcosahedronGeometry extends PolyhedronGeometry { - } + constructor( radius = 1, detail = 0 ) { - return texture; + const t = ( 1 + Math.sqrt( 5 ) ) / 2; - } + const 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 + ]; -} ); + const 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 + ]; -class ImageLoader extends Loader { + super( vertices, indices, radius, detail ); - constructor( manager ) { + this.type = 'IcosahedronGeometry'; - super( manager ); + this.parameters = { + radius: radius, + detail: detail + }; } - load( url, onLoad, onProgress, onError ) { - - if ( this.path !== undefined ) url = this.path + url; - - url = this.manager.resolveURL( url ); + static fromJSON( data ) { - const scope = this; + return new IcosahedronGeometry( data.radius, data.detail ); - const cached = Cache.get( url ); + } - if ( cached !== undefined ) { +} - scope.manager.itemStart( url ); +class OctahedronGeometry extends PolyhedronGeometry { - setTimeout( function () { + constructor( radius = 1, detail = 0 ) { - if ( onLoad ) onLoad( cached ); + const vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, + 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; - scope.manager.itemEnd( url ); + const 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 + ]; - }, 0 ); + super( vertices, indices, radius, detail ); - return cached; + this.type = 'OctahedronGeometry'; - } + this.parameters = { + radius: radius, + detail: detail + }; - const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + } - function onImageLoad() { + static fromJSON( data ) { - image.removeEventListener( 'load', onImageLoad, false ); - image.removeEventListener( 'error', onImageError, false ); + return new OctahedronGeometry( data.radius, data.detail ); - Cache.add( url, this ); + } - if ( onLoad ) onLoad( this ); +} - scope.manager.itemEnd( url ); +class RingGeometry extends BufferGeometry { - } + constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { - function onImageError( event ) { + super(); - image.removeEventListener( 'load', onImageLoad, false ); - image.removeEventListener( 'error', onImageError, false ); + this.type = 'RingGeometry'; - if ( onError ) onError( event ); + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + thetaSegments = Math.max( 3, thetaSegments ); + phiSegments = Math.max( 1, phiSegments ); - } + // buffers - image.addEventListener( 'load', onImageLoad, false ); - image.addEventListener( 'error', onImageError, false ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - if ( url.substr( 0, 5 ) !== 'data:' ) { + // some helper variables - if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + let radius = innerRadius; + const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + const vertex = new Vector3(); + const uv = new Vector2(); - } + // generate vertices, normals and uvs - scope.manager.itemStart( url ); + for ( let j = 0; j <= phiSegments; j ++ ) { - image.src = url; + for ( let i = 0; i <= thetaSegments; i ++ ) { - return image; + // values are generate from the inside of the ring to the outside - } + const segment = thetaStart + i / thetaSegments * thetaLength; -} + // vertex -class CubeTextureLoader extends Loader { + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - constructor( manager ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - super( manager ); + // normal - } + normals.push( 0, 0, 1 ); - load( urls, onLoad, onProgress, onError ) { + // uv - const texture = new CubeTexture(); + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; - const loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + uvs.push( uv.x, uv.y ); - let loaded = 0; + } - function loadTexture( i ) { + // increase the radius for next row of vertices - loader.load( urls[ i ], function ( image ) { + radius += radiusStep; - texture.images[ i ] = image; + } - loaded ++; + // indices - if ( loaded === 6 ) { + for ( let j = 0; j < phiSegments; j ++ ) { - texture.needsUpdate = true; + const thetaSegmentLevel = j * ( thetaSegments + 1 ); - if ( onLoad ) onLoad( texture ); + for ( let i = 0; i < thetaSegments; i ++ ) { - } + const segment = i + thetaSegmentLevel; - }, undefined, onError ); + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; - } + // faces - for ( let i = 0; i < urls.length; ++ i ) { + indices.push( a, b, d ); + indices.push( b, c, d ); - loadTexture( i ); + } } - return texture; + // build geometry - } + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); -} + } -/** - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - * - * Sub classes have to implement the parse() method which will be used in load(). - */ + static fromJSON( data ) { -function DataTextureLoader( manager ) { + return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength ); - Loader.call( this, manager ); + } } -DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: DataTextureLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - const scope = this; - - const texture = new DataTexture(); +class ShapeGeometry extends BufferGeometry { - const loader = new FileLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.setRequestHeader( this.requestHeader ); - loader.setPath( this.path ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( buffer ) { + constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) { - const texData = scope.parse( buffer ); + super(); - if ( ! texData ) return; + this.type = 'ShapeGeometry'; - if ( texData.image !== undefined ) { + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; - texture.image = texData.image; + // buffers - } else if ( texData.data !== undefined ) { + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + // helper variables - } + let groupStart = 0; + let groupCount = 0; - texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; - texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + // allow single and array values for "shapes" parameter - texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; - texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + if ( Array.isArray( shapes ) === false ) { - texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + addShape( shapes ); - if ( texData.encoding !== undefined ) { + } else { - texture.encoding = texData.encoding; + for ( let i = 0; i < shapes.length; i ++ ) { - } + addShape( shapes[ i ] ); - if ( texData.flipY !== undefined ) { + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support - texture.flipY = texData.flipY; + groupStart += groupCount; + groupCount = 0; } - if ( texData.format !== undefined ) { + } - texture.format = texData.format; + // build geometry - } + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - if ( texData.type !== undefined ) { - texture.type = texData.type; + // helper functions - } + function addShape( shape ) { - if ( texData.mipmaps !== undefined ) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints( curveSegments ); - texture.mipmaps = texData.mipmaps; - texture.minFilter = LinearMipmapLinearFilter; // presumably... + let shapeVertices = points.shape; + const shapeHoles = points.holes; - } + // check direction of vertices - if ( texData.mipmapCount === 1 ) { + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { - texture.minFilter = LinearFilter; + shapeVertices = shapeVertices.reverse(); } - texture.needsUpdate = true; + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { - if ( onLoad ) onLoad( texture, texData ); + const shapeHole = shapeHoles[ i ]; - }, onProgress, onError ); + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + shapeHoles[ i ] = shapeHole.reverse(); - return texture; + } - } + } -} ); + const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); -function TextureLoader( manager ) { + // join vertices of inner and outer paths to a single array - Loader.call( this, manager ); + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { -} + const shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); -TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + } - constructor: TextureLoader, + // vertices, normals, uvs - load: function ( url, onLoad, onProgress, onError ) { + for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { - const texture = new Texture(); + const vertex = shapeVertices[ i ]; - const loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs - loader.load( url, function ( image ) { + } - texture.image = image; + // incides - // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. - const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; + for ( let i = 0, l = faces.length; i < l; i ++ ) { - texture.format = isJPEG ? RGBFormat : RGBAFormat; - texture.needsUpdate = true; + const face = faces[ i ]; - if ( onLoad !== undefined ) { + const a = face[ 0 ] + indexOffset; + const b = face[ 1 ] + indexOffset; + const c = face[ 2 ] + indexOffset; - onLoad( texture ); + indices.push( a, b, c ); + groupCount += 3; } - }, onProgress, onError ); - - return texture; + } } -} ); + toJSON() { -/** - * Extensible curve object. - * - * Some common of curve methods: - * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) - * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following curves inherit from THREE.Curve: - * - * -- 2D curves -- - * THREE.ArcCurve - * THREE.CubicBezierCurve - * THREE.EllipseCurve - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.SplineCurve - * - * -- 3D curves -- - * THREE.CatmullRomCurve3 - * THREE.CubicBezierCurve3 - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * - * A series of curves can be represented as a THREE.CurvePath. - * - **/ + const data = super.toJSON(); -function Curve() { + const shapes = this.parameters.shapes; - this.type = 'Curve'; + return toJSON( shapes, data ); - this.arcLengthDivisions = 200; + } -} + static fromJSON( data, shapes ) { -Object.assign( Curve.prototype, { + const geometryShapes = []; - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { - getPoint: function ( /* t, optionalTarget */ ) { + const shape = shapes[ data.shapes[ j ] ]; - console.warn( 'THREE.Curve: .getPoint() not implemented.' ); - return null; + geometryShapes.push( shape ); - }, + } - // Get point at relative position in curve according to arc length - // - u [0 .. 1] + return new ShapeGeometry( geometryShapes, data.curveSegments ); - getPointAt: function ( u, optionalTarget ) { + } - const t = this.getUtoTmapping( u ); - return this.getPoint( t, optionalTarget ); +} - }, +function toJSON( shapes, data ) { - // Get sequence of points using getPoint( t ) + data.shapes = []; - getPoints: function ( divisions = 5 ) { + if ( Array.isArray( shapes ) ) { - const points = []; + for ( let i = 0, l = shapes.length; i < l; i ++ ) { - for ( let d = 0; d <= divisions; d ++ ) { + const shape = shapes[ i ]; - points.push( this.getPoint( d / divisions ) ); + data.shapes.push( shape.uuid ); } - return points; - - }, - - // Get sequence of points using getPointAt( u ) + } else { - getSpacedPoints: function ( divisions = 5 ) { + data.shapes.push( shapes.uuid ); - const points = []; + } - for ( let d = 0; d <= divisions; d ++ ) { + return data; - points.push( this.getPointAt( d / divisions ) ); +} - } +class SphereGeometry extends BufferGeometry { - return points; + constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { - }, + super(); - // Get total curve arc length + this.type = 'SphereGeometry'; - getLength: function () { + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - const lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; + widthSegments = Math.max( 3, Math.floor( widthSegments ) ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) ); - }, + const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); - // Get list of cumulative segment lengths + let index = 0; + const grid = []; - getLengths: function ( divisions ) { + const vertex = new Vector3(); + const normal = new Vector3(); - if ( divisions === undefined ) divisions = this.arcLengthDivisions; + // buffers - if ( this.cacheArcLengths && - ( this.cacheArcLengths.length === divisions + 1 ) && - ! this.needsUpdate ) { + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - return this.cacheArcLengths; + // generate vertices, normals and uvs - } + for ( let iy = 0; iy <= heightSegments; iy ++ ) { - this.needsUpdate = false; + const verticesRow = []; - const cache = []; - let current, last = this.getPoint( 0 ); - let sum = 0; + const v = iy / heightSegments; - cache.push( 0 ); + // special case for the poles - for ( let p = 1; p <= divisions; p ++ ) { + let uOffset = 0; - current = this.getPoint( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + if ( iy == 0 && thetaStart == 0 ) { - } + uOffset = 0.5 / widthSegments; - this.cacheArcLengths = cache; + } else if ( iy == heightSegments && thetaEnd == Math.PI ) { - return cache; // { sums: cache, sum: sum }; Sum is in the last element. + uOffset = - 0.5 / widthSegments; - }, + } - updateArcLengths: function () { + for ( let ix = 0; ix <= widthSegments; ix ++ ) { - this.needsUpdate = true; - this.getLengths(); + const u = ix / widthSegments; - }, + // vertex - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - getUtoTmapping: function ( u, distance ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - const arcLengths = this.getLengths(); + // normal - let i = 0; - const il = arcLengths.length; + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - let targetArcLength; // The targeted u distance value to get + // uv - if ( distance ) { + uvs.push( u + uOffset, 1 - v ); - targetArcLength = distance; + verticesRow.push( index ++ ); - } else { + } - targetArcLength = u * arcLengths[ il - 1 ]; + grid.push( verticesRow ); } - // binary search for the index with largest value smaller than target u distance + // indices - let low = 0, high = il - 1, comparison; + for ( let iy = 0; iy < heightSegments; iy ++ ) { - while ( low <= high ) { + for ( let ix = 0; ix < widthSegments; ix ++ ) { - 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 + const a = grid[ iy ][ ix + 1 ]; + const b = grid[ iy ][ ix ]; + const c = grid[ iy + 1 ][ ix ]; + const d = grid[ iy + 1 ][ ix + 1 ]; - comparison = arcLengths[ i ] - targetArcLength; + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); - if ( comparison < 0 ) { + } - low = i + 1; + } - } else if ( comparison > 0 ) { + // build geometry - high = i - 1; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } else { + } - high = i; - break; + static fromJSON( data ) { - // DONE + return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); - } + } - } +} - i = high; +class TetrahedronGeometry extends PolyhedronGeometry { - if ( arcLengths[ i ] === targetArcLength ) { + constructor( radius = 1, detail = 0 ) { - return i / ( il - 1 ); + const vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - } + const indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; - // we could get finer grain at lengths, or use simple interpolation between two points + super( vertices, indices, radius, detail ); - const lengthBefore = arcLengths[ i ]; - const lengthAfter = arcLengths[ i + 1 ]; + this.type = 'TetrahedronGeometry'; - const segmentLength = lengthAfter - lengthBefore; + this.parameters = { + radius: radius, + detail: detail + }; - // determine where we are between the 'before' and 'after' points + } - const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + static fromJSON( data ) { - // add that fractional amount to t + return new TetrahedronGeometry( data.radius, data.detail ); - const t = ( i + segmentFraction ) / ( il - 1 ); + } - return t; +} - }, +class TorusGeometry extends BufferGeometry { - // 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 + constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) { - getTangent: function ( t, optionalTarget ) { + super(); - const delta = 0.0001; - let t1 = t - delta; - let t2 = t + delta; + this.type = 'TorusGeometry'; - // Capping in case of danger + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; + radialSegments = Math.floor( radialSegments ); + tubularSegments = Math.floor( tubularSegments ); - const pt1 = this.getPoint( t1 ); - const pt2 = this.getPoint( t2 ); + // buffers - const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - tangent.copy( pt2 ).sub( pt1 ).normalize(); + // helper variables - return tangent; + const center = new Vector3(); + const vertex = new Vector3(); + const normal = new Vector3(); - }, + // generate vertices, normals and uvs - getTangentAt: function ( u, optionalTarget ) { + for ( let j = 0; j <= radialSegments; j ++ ) { - const t = this.getUtoTmapping( u ); - return this.getTangent( t, optionalTarget ); + for ( let i = 0; i <= tubularSegments; i ++ ) { - }, + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; - computeFrenetFrames: function ( segments, closed ) { + // vertex - // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + 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 ); - const normal = new Vector3(); + vertices.push( vertex.x, vertex.y, vertex.z ); - const tangents = []; - const normals = []; - const binormals = []; + // normal - const vec = new Vector3(); - const mat = new Matrix4(); + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); - // compute the tangent vectors for each segment on the curve + normals.push( normal.x, normal.y, normal.z ); - for ( let i = 0; i <= segments; i ++ ) { + // uv - const u = i / segments; + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - tangents[ i ] = this.getTangentAt( u, new Vector3() ); - tangents[ i ].normalize(); + } } - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the minimum tangent xyz component + // generate indices - normals[ 0 ] = new Vector3(); - binormals[ 0 ] = new Vector3(); - let min = Number.MAX_VALUE; - const tx = Math.abs( tangents[ 0 ].x ); - const ty = Math.abs( tangents[ 0 ].y ); - const tz = Math.abs( tangents[ 0 ].z ); + for ( let j = 1; j <= radialSegments; j ++ ) { - if ( tx <= min ) { + for ( let i = 1; i <= tubularSegments; i ++ ) { - min = tx; - normal.set( 1, 0, 0 ); + // indices - } + const a = ( tubularSegments + 1 ) * j + i - 1; + const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + const d = ( tubularSegments + 1 ) * j + i; - if ( ty <= min ) { + // faces - min = ty; - normal.set( 0, 1, 0 ); + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry - } + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - if ( tz <= min ) { + } - normal.set( 0, 0, 1 ); + static fromJSON( data ) { - } + return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc ); - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + } - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); +} +class TorusKnotGeometry extends BufferGeometry { - // compute the slowly-varying normal and binormal vectors for each segment on the curve + constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { - for ( let i = 1; i <= segments; i ++ ) { + super(); - normals[ i ] = normals[ i - 1 ].clone(); + this.type = 'TorusKnotGeometry'; - binormals[ i ] = binormals[ i - 1 ].clone(); + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + tubularSegments = Math.floor( tubularSegments ); + radialSegments = Math.floor( radialSegments ); - if ( vec.length() > Number.EPSILON ) { + // buffers - vec.normalize(); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + // helper variables - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + const vertex = new Vector3(); + const normal = new Vector3(); - } + const P1 = new Vector3(); + const P2 = new Vector3(); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + const B = new Vector3(); + const T = new Vector3(); + const N = new Vector3(); - } + // generate vertices, normals and uvs - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + for ( let i = 0; i <= tubularSegments; ++ i ) { - if ( closed === true ) { + // the radian "u" is used to calculate the position on the torus curve of the current tubular segment - let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); - theta /= segments; + const u = i / tubularSegments * p * Math.PI * 2; - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + // 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 - theta = - theta; + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); - } + // calculate orthonormal basis - for ( let i = 1; i <= segments; i ++ ) { + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + // normalize B, N. T can be ignored, we don't use it - } + B.normalize(); + N.normalize(); - } + for ( let j = 0; j <= radialSegments; ++ j ) { - return { - tangents: tangents, - normals: normals, - binormals: binormals - }; + // 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. - }, + const v = j / radialSegments * Math.PI * 2; + const cx = - tube * Math.cos( v ); + const cy = tube * Math.sin( v ); - clone: function () { + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve - return new this.constructor().copy( this ); + 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 ); - }, + vertices.push( vertex.x, vertex.y, vertex.z ); - copy: function ( source ) { + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) - this.arcLengthDivisions = source.arcLengthDivisions; + normal.subVectors( vertex, P1 ).normalize(); - return this; + normals.push( normal.x, normal.y, normal.z ); - }, + // uv - toJSON: function () { + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - const data = { - metadata: { - version: 4.5, - type: 'Curve', - generator: 'Curve.toJSON' } - }; - data.arcLengthDivisions = this.arcLengthDivisions; - data.type = this.type; + } - return data; + // generate indices - }, + for ( let j = 1; j <= tubularSegments; j ++ ) { - fromJSON: function ( json ) { + for ( let i = 1; i <= radialSegments; i ++ ) { - this.arcLengthDivisions = json.arcLengthDivisions; + // indices - return this; + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; - } + // faces -} ); + indices.push( a, b, d ); + indices.push( b, c, d ); -class EllipseCurve extends Curve { + } - constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { + } - super(); + // build geometry - this.type = 'EllipseCurve'; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - this.aX = aX; - this.aY = aY; + // this function calculates the current position on the torus curve - this.xRadius = xRadius; - this.yRadius = yRadius; + function calculatePositionOnCurve( u, p, q, radius, position ) { - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + const cu = Math.cos( u ); + const su = Math.sin( u ); + const quOverP = q / p * u; + const cs = Math.cos( quOverP ); - this.aClockwise = aClockwise; + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; - this.aRotation = aRotation; + } } - getPoint( t, optionalTarget ) { + static fromJSON( data ) { - const point = optionalTarget || new Vector2(); + return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q ); - const twoPi = Math.PI * 2; - let deltaAngle = this.aEndAngle - this.aStartAngle; - const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + } - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) deltaAngle += twoPi; - while ( deltaAngle > twoPi ) deltaAngle -= twoPi; +} - if ( deltaAngle < Number.EPSILON ) { +class TubeGeometry extends BufferGeometry { - if ( samePoints ) { + constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { - deltaAngle = 0; + super(); - } else { + this.type = 'TubeGeometry'; - deltaAngle = twoPi; + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; - } + const frames = path.computeFrenetFrames( tubularSegments, closed ); - } + // expose internals - if ( this.aClockwise === true && ! samePoints ) { + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; - if ( deltaAngle === twoPi ) { + // helper variables - deltaAngle = - twoPi; + const vertex = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); - } else { + // buffer - deltaAngle = deltaAngle - twoPi; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; - } + // create buffer data - } + generateBufferData(); - const angle = this.aStartAngle + t * deltaAngle; - let x = this.aX + this.xRadius * Math.cos( angle ); - let y = this.aY + this.yRadius * Math.sin( angle ); + // build geometry - if ( this.aRotation !== 0 ) { + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - const cos = Math.cos( this.aRotation ); - const sin = Math.sin( this.aRotation ); + // functions - const tx = x - this.aX; - const ty = y - this.aY; + function generateBufferData() { - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + for ( let i = 0; i < tubularSegments; i ++ ) { - } + generateSegment( i ); - return point.set( x, y ); + } - } + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) - copy( source ) { + generateSegment( ( closed === false ) ? tubularSegments : 0 ); - super.copy( source ); + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries - this.aX = source.aX; - this.aY = source.aY; + generateUVs(); - this.xRadius = source.xRadius; - this.yRadius = source.yRadius; + // finally create faces - this.aStartAngle = source.aStartAngle; - this.aEndAngle = source.aEndAngle; + generateIndices(); - this.aClockwise = source.aClockwise; + } - this.aRotation = source.aRotation; + function generateSegment( i ) { - return this; + // we use getPointAt to sample evenly distributed points from the given path - } + P = path.getPointAt( i / tubularSegments, P ); - toJSON() { + // retrieve corresponding normal and binormal - const data = super.toJSON(); + const N = frames.normals[ i ]; + const B = frames.binormals[ i ]; - data.aX = this.aX; - data.aY = this.aY; + // generate normals and vertices for the current segment - data.xRadius = this.xRadius; - data.yRadius = this.yRadius; + for ( let j = 0; j <= radialSegments; j ++ ) { - data.aStartAngle = this.aStartAngle; - data.aEndAngle = this.aEndAngle; + const v = j / radialSegments * Math.PI * 2; - data.aClockwise = this.aClockwise; + const sin = Math.sin( v ); + const cos = - Math.cos( v ); - data.aRotation = this.aRotation; + // normal - return data; + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); - } + normals.push( normal.x, normal.y, normal.z ); - fromJSON( json ) { + // vertex - super.fromJSON( json ); + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; - this.aX = json.aX; - this.aY = json.aY; + vertices.push( vertex.x, vertex.y, vertex.z ); - this.xRadius = json.xRadius; - this.yRadius = json.yRadius; + } - this.aStartAngle = json.aStartAngle; - this.aEndAngle = json.aEndAngle; + } - this.aClockwise = json.aClockwise; + function generateIndices() { - this.aRotation = json.aRotation; + for ( let j = 1; j <= tubularSegments; j ++ ) { - return this; + for ( let i = 1; i <= radialSegments; i ++ ) { - } + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; -} + // faces -EllipseCurve.prototype.isEllipseCurve = true; + indices.push( a, b, d ); + indices.push( b, c, d ); -class ArcCurve extends EllipseCurve { + } - constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + } - super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + } - this.type = 'ArcCurve'; + function generateUVs() { - } + for ( let i = 0; i <= tubularSegments; i ++ ) { -} + for ( let j = 0; j <= radialSegments; j ++ ) { -ArcCurve.prototype.isArcCurve = true; + uv.x = i / tubularSegments; + uv.y = j / radialSegments; -/** - * 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 - */ + uvs.push( uv.x, uv.y ); + } -/* -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. -*/ + } -function CubicPoly() { + } - let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + toJSON() { - /* - * 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. - */ - function init( x0, x1, t0, t1 ) { + const data = super.toJSON(); - c0 = x0; - c1 = t0; - c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; - c3 = 2 * x0 - 2 * x1 + t0 + t1; + data.path = this.parameters.path.toJSON(); - } + return data; - return { + } - initCatmullRom: function ( x0, x1, x2, x3, tension ) { + static fromJSON( data ) { - init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + // This only works for built-in curves (e.g. CatmullRomCurve3). + // User defined curves or instances of CurvePath will not be deserialized. + return new TubeGeometry( + new Curves[ data.path.type ]().fromJSON( data.path ), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); - }, + } - initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { +} - // compute tangents when parameterized in [t1,t2] - let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; - let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; +class WireframeGeometry extends BufferGeometry { - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; + constructor( geometry = null ) { - init( x1, x2, t1, t2 ); + super(); - }, + this.type = 'WireframeGeometry'; - calc: function ( t ) { + this.parameters = { + geometry: geometry + }; - const t2 = t * t; - const t3 = t2 * t; - return c0 + c1 * t + c2 * t2 + c3 * t3; + if ( geometry !== null ) { - } + // buffer - }; + const vertices = []; + const edges = new Set(); -} + // helper variables -// + const start = new Vector3(); + const end = new Vector3(); -const tmp = new Vector3(); -const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); + if ( geometry.index !== null ) { -class CatmullRomCurve3 extends Curve { + // indexed BufferGeometry - constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; - super(); + if ( groups.length === 0 ) { - this.type = 'CatmullRomCurve3'; + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; - this.points = points; - this.closed = closed; - this.curveType = curveType; - this.tension = tension; + } - } + // create a data structure that contains all edges without duplicates - getPoint( t, optionalTarget = new Vector3() ) { + for ( let o = 0, ol = groups.length; o < ol; ++ o ) { - const point = optionalTarget; + const group = groups[ o ]; - const points = this.points; - const l = points.length; + const groupStart = group.start; + const groupCount = group.count; - const p = ( l - ( this.closed ? 0 : 1 ) ) * t; - let intPoint = Math.floor( p ); - let weight = p - intPoint; + for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) { - if ( this.closed ) { + for ( let j = 0; j < 3; j ++ ) { - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + const index1 = indices.getX( i + j ); + const index2 = indices.getX( i + ( j + 1 ) % 3 ); - } else if ( weight === 0 && intPoint === l - 1 ) { + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); - intPoint = l - 2; - weight = 1; + if ( isUniqueEdge( start, end, edges ) === true ) { - } + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); - let p0, p3; // 4 points (p1 & p2 defined below) + } - if ( this.closed || intPoint > 0 ) { + } - p0 = points[ ( intPoint - 1 ) % l ]; + } - } else { + } - // extrapolate first point - tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); - p0 = tmp; + } else { - } + // non-indexed BufferGeometry - const p1 = points[ intPoint % l ]; - const p2 = points[ ( intPoint + 1 ) % l ]; + const position = geometry.attributes.position; - if ( this.closed || intPoint + 2 < l ) { + for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { - p3 = points[ ( intPoint + 2 ) % l ]; + for ( let j = 0; j < 3; j ++ ) { - } else { + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) - // extrapolate last point - tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); - p3 = tmp; + const index1 = 3 * i + j; + const index2 = 3 * i + ( ( j + 1 ) % 3 ); - } + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); - if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + if ( isUniqueEdge( start, end, edges ) === true ) { - // init Centripetal / Chordal Catmull-Rom - const pow = this.curveType === 'chordal' ? 0.5 : 0.25; - let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); - let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); - let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); - // safety check for repeated points - if ( dt1 < 1e-4 ) dt1 = 1.0; - if ( dt0 < 1e-4 ) dt0 = dt1; - if ( dt2 < 1e-4 ) dt2 = dt1; + } - 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.curveType === 'catmullrom' ) { + } - px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); - py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); - pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + } - } + // build geometry - point.set( - px.calc( weight ), - py.calc( weight ), - pz.calc( weight ) - ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - return point; + } } - copy( source ) { +} - super.copy( source ); +function isUniqueEdge( start, end, edges ) { - this.points = []; + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge - for ( let i = 0, l = source.points.length; i < l; i ++ ) { + if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) { - const point = source.points[ i ]; + return false; - this.points.push( point.clone() ); + } else { - } + edges.add( hash1 ); + edges.add( hash2 ); + return true; - this.closed = source.closed; - this.curveType = source.curveType; - this.tension = source.tension; + } - return this; +} - } +var Geometries = /*#__PURE__*/Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry, + CapsuleGeometry: CapsuleGeometry, + CircleGeometry: CircleGeometry, + ConeGeometry: ConeGeometry, + CylinderGeometry: CylinderGeometry, + DodecahedronGeometry: DodecahedronGeometry, + EdgesGeometry: EdgesGeometry, + ExtrudeGeometry: ExtrudeGeometry, + IcosahedronGeometry: IcosahedronGeometry, + LatheGeometry: LatheGeometry, + OctahedronGeometry: OctahedronGeometry, + PlaneGeometry: PlaneGeometry, + PolyhedronGeometry: PolyhedronGeometry, + RingGeometry: RingGeometry, + ShapeGeometry: ShapeGeometry, + SphereGeometry: SphereGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TorusGeometry: TorusGeometry, + TorusKnotGeometry: TorusKnotGeometry, + TubeGeometry: TubeGeometry, + WireframeGeometry: WireframeGeometry +}); - toJSON() { +class ShadowMaterial extends Material { - const data = super.toJSON(); + constructor( parameters ) { - data.points = []; + super(); - for ( let i = 0, l = this.points.length; i < l; i ++ ) { + this.isShadowMaterial = true; - const point = this.points[ i ]; - data.points.push( point.toArray() ); + this.type = 'ShadowMaterial'; - } + this.color = new Color( 0x000000 ); + this.transparent = true; - data.closed = this.closed; - data.curveType = this.curveType; - data.tension = this.tension; + this.fog = true; - return data; + this.setValues( parameters ); } - fromJSON( json ) { - - super.fromJSON( json ); - - this.points = []; - - for ( let i = 0, l = json.points.length; i < l; i ++ ) { + copy( source ) { - const point = json.points[ i ]; - this.points.push( new Vector3().fromArray( point ) ); + super.copy( source ); - } + this.color.copy( source.color ); - this.closed = json.closed; - this.curveType = json.curveType; - this.tension = json.tension; + this.fog = source.fog; return this; @@ -35813,279 +36869,276 @@ class CatmullRomCurve3 extends Curve { } -CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; - -/** - * Bezier Curves formulas obtained from - * http://en.wikipedia.org/wiki/Bézier_curve - */ - -function CatmullRom( t, p0, p1, p2, p3 ) { +class RawShaderMaterial extends ShaderMaterial { - const v0 = ( p2 - p0 ) * 0.5; - const v1 = ( p3 - p1 ) * 0.5; - const t2 = t * t; - const t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + constructor( parameters ) { -} + super( parameters ); -// + this.isRawShaderMaterial = true; -function QuadraticBezierP0( t, p ) { + this.type = 'RawShaderMaterial'; - const k = 1 - t; - return k * k * p; + } } -function QuadraticBezierP1( t, p ) { +class MeshStandardMaterial extends Material { - return 2 * ( 1 - t ) * t * p; + constructor( parameters ) { -} + super(); -function QuadraticBezierP2( t, p ) { + this.isMeshStandardMaterial = true; - return t * t * p; + this.defines = { 'STANDARD': '' }; -} + this.type = 'MeshStandardMaterial'; -function QuadraticBezier( t, p0, p1, p2 ) { + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 1.0; + this.metalness = 0.0; - return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + - QuadraticBezierP2( t, p2 ); + this.map = null; -} + this.lightMap = null; + this.lightMapIntensity = 1.0; -// + this.aoMap = null; + this.aoMapIntensity = 1.0; -function CubicBezierP0( t, p ) { + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - const k = 1 - t; - return k * k * k * p; + this.bumpMap = null; + this.bumpScale = 1; -} + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); -function CubicBezierP1( t, p ) { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - const k = 1 - t; - return 3 * k * k * t * p; + this.roughnessMap = null; -} + this.metalnessMap = null; -function CubicBezierP2( t, p ) { + this.alphaMap = null; - return 3 * ( 1 - t ) * t * t * p; + this.envMap = null; + this.envMapIntensity = 1.0; -} + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; -function CubicBezierP3( t, p ) { + this.flatShading = false; - return t * t * t * p; + this.fog = true; -} + this.setValues( parameters ); -function CubicBezier( t, p0, p1, p2, p3 ) { + } - return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + - CubicBezierP3( t, p3 ); + copy( source ) { -} + super.copy( source ); -class CubicBezierCurve extends Curve { + this.defines = { 'STANDARD': '' }; - constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; - super(); + this.map = source.map; - this.type = 'CubicBezierCurve'; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - } + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - getPoint( t, optionalTarget = new Vector2() ) { + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - const point = optionalTarget; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - point.set( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) - ); + this.roughnessMap = source.roughnessMap; - return point; + this.metalnessMap = source.metalnessMap; - } + this.alphaMap = source.alphaMap; - copy( source ) { + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; - super.copy( source ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - this.v3.copy( source.v3 ); + this.flatShading = source.flatShading; + + this.fog = source.fog; return this; } - toJSON() { +} - const data = super.toJSON(); +class MeshPhysicalMaterial extends MeshStandardMaterial { - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); + constructor( parameters ) { - return data; + super(); - } + this.isMeshPhysicalMaterial = true; - fromJSON( json ) { + this.defines = { - super.fromJSON( json ); + 'STANDARD': '', + 'PHYSICAL': '' - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); - this.v3.fromArray( json.v3 ); + }; - return this; + this.type = 'MeshPhysicalMaterial'; - } + this.clearcoatMap = null; + this.clearcoatRoughness = 0.0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2( 1, 1 ); + this.clearcoatNormalMap = null; -} + this.ior = 1.5; -CubicBezierCurve.prototype.isCubicBezierCurve = true; + Object.defineProperty( this, 'reflectivity', { + get: function () { -class CubicBezierCurve3 extends Curve { + return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) ); - constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { + }, + set: function ( reflectivity ) { - super(); + this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity ); - this.type = 'CubicBezierCurve3'; + } + } ); - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; - } + this.sheenColor = new Color( 0x000000 ); + this.sheenColorMap = null; + this.sheenRoughness = 1.0; + this.sheenRoughnessMap = null; - getPoint( t, optionalTarget = new Vector3() ) { + this.transmissionMap = null; - const point = optionalTarget; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = 0.0; + this.attenuationColor = new Color( 1, 1, 1 ); - const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + this.specularIntensity = 1.0; + this.specularIntensityMap = null; + this.specularColor = new Color( 1, 1, 1 ); + this.specularColorMap = null; - point.set( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), - CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) - ); + this._sheen = 0.0; + this._clearcoat = 0; + this._iridescence = 0; + this._transmission = 0; - return point; + this.setValues( parameters ); } - copy( source ) { - - super.copy( source ); - - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - this.v3.copy( source.v3 ); + get sheen() { - return this; + return this._sheen; } - toJSON() { - - const data = super.toJSON(); + set sheen( value ) { - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); + if ( this._sheen > 0 !== value > 0 ) { - return data; + this.version ++; - } + } - fromJSON( json ) { + this._sheen = value; - super.fromJSON( json ); + } - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); - this.v3.fromArray( json.v3 ); + get clearcoat() { - return this; + return this._clearcoat; } -} - -CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; - -class LineCurve extends Curve { + set clearcoat( value ) { - constructor( v1 = new Vector2(), v2 = new Vector2() ) { + if ( this._clearcoat > 0 !== value > 0 ) { - super(); + this.version ++; - this.type = 'LineCurve'; + } - this.v1 = v1; - this.v2 = v2; + this._clearcoat = value; } - getPoint( t, optionalTarget = new Vector2() ) { + get iridescence() { - const point = optionalTarget; + return this._iridescence; - if ( t === 1 ) { + } - point.copy( this.v2 ); + set iridescence( value ) { - } else { + if ( this._iridescence > 0 !== value > 0 ) { - point.copy( this.v2 ).sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + this.version ++; } - return point; + this._iridescence = value; } - // Line curve is linear, so we can overwrite default getPointAt - getPointAt( u, optionalTarget ) { + get transmission() { - return this.getPoint( u, optionalTarget ); + return this._transmission; } - getTangent( t, optionalTarget ) { + set transmission( value ) { - const tangent = optionalTarget || new Vector2(); + if ( this._transmission > 0 !== value > 0 ) { - tangent.copy( this.v2 ).sub( this.v1 ).normalize(); + this.version ++; - return tangent; + } + + this._transmission = value; } @@ -36093,30 +37146,46 @@ class LineCurve extends Curve { super.copy( source ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - - return this; + this.defines = { - } + 'STANDARD': '', + 'PHYSICAL': '' - toJSON() { + }; - const data = super.toJSON(); + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.ior = source.ior; - return data; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; - } + this.sheen = source.sheen; + this.sheenColor.copy( source.sheenColor ); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; - fromJSON( json ) { + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; - super.fromJSON( json ); + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy( source.attenuationColor ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy( source.specularColor ); + this.specularColorMap = source.specularColorMap; return this; @@ -36124,71 +37193,113 @@ class LineCurve extends Curve { } -LineCurve.prototype.isLineCurve = true; - -class LineCurve3 extends Curve { +class MeshPhongMaterial extends Material { - constructor( v1 = new Vector3(), v2 = new Vector3() ) { + constructor( parameters ) { super(); - this.type = 'LineCurve3'; - this.isLineCurve3 = true; + this.isMeshPhongMaterial = true; - this.v1 = v1; - this.v2 = v2; + this.type = 'MeshPhongMaterial'; - } - getPoint( t, optionalTarget = new Vector3() ) { + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; - const point = optionalTarget; + this.map = null; - if ( t === 1 ) { + this.lightMap = null; + this.lightMapIntensity = 1.0; - point.copy( this.v2 ); + this.aoMap = null; + this.aoMapIntensity = 1.0; - } else { + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - point.copy( this.v2 ).sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + this.bumpMap = null; + this.bumpScale = 1; - } + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - return point; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - } - // Line curve is linear, so we can overwrite default getPointAt - getPointAt( u, optionalTarget ) { + this.specularMap = null; - return this.getPoint( u, optionalTarget ); + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); } + copy( source ) { super.copy( source ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; - return this; + this.map = source.map; - } - toJSON() { + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - const data = super.toJSON(); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - return data; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - } - fromJSON( json ) { + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - super.fromJSON( json ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + 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.flatShading = source.flatShading; + + this.fog = source.fog; return this; @@ -36196,32 +37307,54 @@ class LineCurve3 extends Curve { } -class QuadraticBezierCurve extends Curve { +class MeshToonMaterial extends Material { - constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { + constructor( parameters ) { super(); - this.type = 'QuadraticBezierCurve'; + this.isMeshToonMaterial = true; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + this.defines = { 'TOON': '' }; - } + this.type = 'MeshToonMaterial'; - getPoint( t, optionalTarget = new Vector2() ) { + this.color = new Color( 0xffffff ); - const point = optionalTarget; + this.map = null; + this.gradientMap = null; - const v0 = this.v0, v1 = this.v1, v2 = this.v2; + this.lightMap = null; + this.lightMapIntensity = 1.0; - point.set( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ) - ); + this.aoMap = null; + this.aoMapIntensity = 1.0; - return point; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); } @@ -36229,33 +37362,40 @@ class QuadraticBezierCurve extends Curve { super.copy( source ); - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); + this.color.copy( source.color ); - return this; + this.map = source.map; + this.gradientMap = source.gradientMap; - } + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - toJSON() { + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - const data = super.toJSON(); + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - return data; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - } + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - fromJSON( json ) { + this.alphaMap = source.alphaMap; - super.fromJSON( json ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + this.fog = source.fog; return this; @@ -36263,35 +37403,33 @@ class QuadraticBezierCurve extends Curve { } -QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; - -class QuadraticBezierCurve3 extends Curve { +class MeshNormalMaterial extends Material { - constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { + constructor( parameters ) { super(); - this.type = 'QuadraticBezierCurve3'; + this.isMeshNormalMaterial = true; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + this.type = 'MeshNormalMaterial'; - } + this.bumpMap = null; + this.bumpScale = 1; - getPoint( t, optionalTarget = new Vector3() ) { + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - const point = optionalTarget; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - const v0 = this.v0, v1 = this.v1, v2 = this.v2; + this.wireframe = false; + this.wireframeLinewidth = 1; - point.set( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ), - QuadraticBezier( t, v0.z, v1.z, v2.z ) - ); + this.flatShading = false; - return point; + this.setValues( parameters ); } @@ -36299,75 +37437,82 @@ class QuadraticBezierCurve3 extends Curve { super.copy( source ); - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - - return this; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - } + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - toJSON() { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - const data = super.toJSON(); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.flatShading = source.flatShading; - return data; + return this; } - fromJSON( json ) { +} - super.fromJSON( json ); +class MeshLambertMaterial extends Material { - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + constructor( parameters ) { - return this; + super(); - } + this.isMeshLambertMaterial = true; -} + this.type = 'MeshLambertMaterial'; -QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true; + this.color = new Color( 0xffffff ); // diffuse -class SplineCurve extends Curve { + this.map = null; - constructor( points = [] ) { + this.lightMap = null; + this.lightMapIntensity = 1.0; - super(); + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.type = 'SplineCurve'; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - this.points = points; + this.bumpMap = null; + this.bumpScale = 1; - } + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - getPoint( t, optionalTarget = new Vector2() ) { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - const point = optionalTarget; + this.specularMap = null; - const points = this.points; - const p = ( points.length - 1 ) * t; + this.alphaMap = null; - const intPoint = Math.floor( p ); - const weight = p - intPoint; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; - const p1 = points[ intPoint ]; - const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - point.set( - CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), - CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) - ); + this.flatShading = false; - return point; + this.fog = true; + + this.setValues( parameters ); } @@ -36375,1389 +37520,1387 @@ class SplineCurve extends Curve { super.copy( source ); - this.points = []; + this.color.copy( source.color ); - for ( let i = 0, l = source.points.length; i < l; i ++ ) { + this.map = source.map; - const point = source.points[ i ]; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.points.push( point.clone() ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - } + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - return this; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - } + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - toJSON() { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - const data = super.toJSON(); + this.specularMap = source.specularMap; - data.points = []; + this.alphaMap = source.alphaMap; - for ( let i = 0, l = this.points.length; i < l; i ++ ) { + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - const point = this.points[ i ]; - data.points.push( point.toArray() ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.flatShading = source.flatShading; - return data; + this.fog = source.fog; + + return this; } - fromJSON( json ) { +} - super.fromJSON( json ); +class MeshMatcapMaterial extends Material { - this.points = []; + constructor( parameters ) { - for ( let i = 0, l = json.points.length; i < l; i ++ ) { + super(); - const point = json.points[ i ]; - this.points.push( new Vector2().fromArray( point ) ); + this.isMeshMatcapMaterial = true; - } + this.defines = { 'MATCAP': '' }; - return this; + this.type = 'MeshMatcapMaterial'; - } + this.color = new Color( 0xffffff ); // diffuse -} + this.matcap = null; -SplineCurve.prototype.isSplineCurve = true; + this.map = null; -var Curves = /*#__PURE__*/Object.freeze({ - __proto__: null, - ArcCurve: ArcCurve, - CatmullRomCurve3: CatmullRomCurve3, - CubicBezierCurve: CubicBezierCurve, - CubicBezierCurve3: CubicBezierCurve3, - EllipseCurve: EllipseCurve, - LineCurve: LineCurve, - LineCurve3: LineCurve3, - QuadraticBezierCurve: QuadraticBezierCurve, - QuadraticBezierCurve3: QuadraticBezierCurve3, - SplineCurve: SplineCurve -}); + this.bumpMap = null; + this.bumpScale = 1; -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); -class CurvePath extends Curve { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - constructor() { + this.alphaMap = null; - super(); + this.flatShading = false; - this.type = 'CurvePath'; + this.fog = true; - this.curves = []; - this.autoClose = false; // Automatically closes the path + this.setValues( parameters ); } - add( curve ) { - - this.curves.push( curve ); - } + copy( source ) { - closePath() { + super.copy( source ); - // Add a line curve if start and end of lines are not connected - const startPoint = this.curves[ 0 ].getPoint( 0 ); - const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + this.defines = { 'MATCAP': '' }; - if ( ! startPoint.equals( endPoint ) ) { + this.color.copy( source.color ); - this.curves.push( new LineCurve( endPoint, startPoint ) ); + this.matcap = source.matcap; - } + this.map = source.map; - } + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - // 1. Length of each sub path have to be known - // 2. Locate and identify type of curve - // 3. Get t for the curve - // 4. Return curve.getPointAt(t') + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - getPoint( t ) { + this.alphaMap = source.alphaMap; - const d = t * this.getLength(); - const curveLengths = this.getCurveLengths(); - let i = 0; + this.flatShading = source.flatShading; - // To think about boundaries points. + this.fog = source.fog; - while ( i < curveLengths.length ) { + return this; - if ( curveLengths[ i ] >= d ) { + } - const diff = curveLengths[ i ] - d; - const curve = this.curves[ i ]; +} - const segmentLength = curve.getLength(); - const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; +class LineDashedMaterial extends LineBasicMaterial { - return curve.getPointAt( u ); + constructor( parameters ) { - } + super(); - i ++; + this.isLineDashedMaterial = true; - } + this.type = 'LineDashedMaterial'; - return null; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; - // loop where sum != 0, sum > d , sum+1 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { + } - points.push( points[ 0 ] ); + return result; - } +} - return points; +// function for parsing AOS keyframe formats +function flattenJSON( jsonKeys, times, values, valuePropertyName ) { - } + let i = 1, key = jsonKeys[ 0 ]; - copy( source ) { + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { - super.copy( source ); + key = jsonKeys[ i ++ ]; - this.curves = []; + } - for ( let i = 0, l = source.curves.length; i < l; i ++ ) { + if ( key === undefined ) return; // no data - const curve = source.curves[ i ]; + let value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - this.curves.push( curve.clone() ); + if ( Array.isArray( value ) ) { - } + do { - this.autoClose = source.autoClose; + value = key[ valuePropertyName ]; - return this; + if ( value !== undefined ) { - } + times.push( key.time ); + values.push.apply( values, value ); // push all elements - toJSON() { + } - const data = super.toJSON(); + key = jsonKeys[ i ++ ]; - data.autoClose = this.autoClose; - data.curves = []; + } while ( key !== undefined ); - for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + } else if ( value.toArray !== undefined ) { - const curve = this.curves[ i ]; - data.curves.push( curve.toJSON() ); + // ...assume THREE.Math-ish - } + do { - return data; + value = key[ valuePropertyName ]; - } + if ( value !== undefined ) { - fromJSON( json ) { + times.push( key.time ); + value.toArray( values, values.length ); - super.fromJSON( json ); + } - this.autoClose = json.autoClose; - this.curves = []; + key = jsonKeys[ i ++ ]; - for ( let i = 0, l = json.curves.length; i < l; i ++ ) { + } while ( key !== undefined ); - const curve = json.curves[ i ]; - this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + } else { - } + // otherwise push as-is - return this; + do { - } + value = key[ valuePropertyName ]; -} + if ( value !== undefined ) { -class Path extends CurvePath { + times.push( key.time ); + values.push( value ); - constructor( points ) { + } - super(); - this.type = 'Path'; + key = jsonKeys[ i ++ ]; - this.currentPoint = new Vector2(); + } while ( key !== undefined ); - if ( points ) { + } - this.setFromPoints( points ); +} - } +function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) { - } + const clip = sourceClip.clone(); - setFromPoints( points ) { + clip.name = name; - this.moveTo( points[ 0 ].x, points[ 0 ].y ); + const tracks = []; - for ( let i = 1, l = points.length; i < l; i ++ ) { + for ( let i = 0; i < clip.tracks.length; ++ i ) { - this.lineTo( points[ i ].x, points[ i ].y ); + const track = clip.tracks[ i ]; + const valueSize = track.getValueSize(); - } + const times = []; + const values = []; - return this; + for ( let j = 0; j < track.times.length; ++ j ) { - } + const frame = track.times[ j ] * fps; - moveTo( x, y ) { + if ( frame < startFrame || frame >= endFrame ) continue; - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + times.push( track.times[ j ] ); - return this; + for ( let k = 0; k < valueSize; ++ k ) { - } + values.push( track.values[ j * valueSize + k ] ); - lineTo( x, y ) { + } - const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); - this.curves.push( curve ); + } - this.currentPoint.set( x, y ); + if ( times.length === 0 ) continue; - return this; + track.times = convertArray( times, track.times.constructor ); + track.values = convertArray( values, track.values.constructor ); + + tracks.push( track ); } - quadraticCurveTo( aCPx, aCPy, aX, aY ) { + clip.tracks = tracks; - const curve = new QuadraticBezierCurve( - this.currentPoint.clone(), - new Vector2( aCPx, aCPy ), - new Vector2( aX, aY ) - ); + // find minimum .times value across all tracks in the trimmed clip - this.curves.push( curve ); + let minStartTime = Infinity; - this.currentPoint.set( aX, aY ); + for ( let i = 0; i < clip.tracks.length; ++ i ) { - return this; + if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { - } + minStartTime = clip.tracks[ i ].times[ 0 ]; - bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + } - const curve = new CubicBezierCurve( - this.currentPoint.clone(), - new Vector2( aCP1x, aCP1y ), - new Vector2( aCP2x, aCP2y ), - new Vector2( aX, aY ) - ); + } - this.curves.push( curve ); + // shift all tracks such that clip begins at t=0 - this.currentPoint.set( aX, aY ); + for ( let i = 0; i < clip.tracks.length; ++ i ) { - return this; + clip.tracks[ i ].shift( - 1 * minStartTime ); } - splineThru( pts /*Array of Vector*/ ) { + clip.resetDuration(); - const npts = [ this.currentPoint.clone() ].concat( pts ); + return clip; - const curve = new SplineCurve( npts ); - this.curves.push( curve ); +} - this.currentPoint.copy( pts[ pts.length - 1 ] ); +function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { - return this; + if ( fps <= 0 ) fps = 30; - } + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; - arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + // Make each track's values relative to the values at the reference frame + for ( let i = 0; i < numTracks; ++ i ) { - const x0 = this.currentPoint.x; - const y0 = this.currentPoint.y; + const referenceTrack = referenceClip.tracks[ i ]; + const referenceTrackType = referenceTrack.ValueTypeName; - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + // Skip this track if it's non-numeric + if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; - return this; + // Find the track in the target clip whose name and type matches the reference track + const targetTrack = targetClip.tracks.find( function ( track ) { - } + return track.name === referenceTrack.name + && track.ValueTypeName === referenceTrackType; - absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + } ); - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + if ( targetTrack === undefined ) continue; - return this; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); - } + if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { - ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + referenceOffset = referenceValueSize / 3; - const x0 = this.currentPoint.x; - const y0 = this.currentPoint.y; + } - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); - return this; + if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { - } + targetOffset = targetValueSize / 3; - absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + } - const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; - if ( this.curves.length > 0 ) { + // Find the value to subtract out of the track + if ( referenceTime <= referenceTrack.times[ 0 ] ) { - // if a previous curve is present, attempt to join - const firstPoint = curve.getPoint( 0 ); + // Reference frame is earlier than the first keyframe, so just use the first keyframe + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); - if ( ! firstPoint.equals( this.currentPoint ) ) { + } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { - this.lineTo( firstPoint.x, firstPoint.y ); + // Reference frame is after the last keyframe, so just use the last keyframe + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); - } + } else { - } + // Interpolate to the reference value + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate( referenceTime ); + referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex ); - this.curves.push( curve ); + } - const lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + // Conjugate the quaternion + if ( referenceTrackType === 'quaternion' ) { - return this; + const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); + referenceQuat.toArray( referenceValue ); - } + } - copy( source ) { + // Subtract the reference value from all of the track values - super.copy( source ); + const numTimes = targetTrack.times.length; + for ( let j = 0; j < numTimes; ++ j ) { - this.currentPoint.copy( source.currentPoint ); + const valueStart = j * targetValueSize + targetOffset; - return this; + if ( referenceTrackType === 'quaternion' ) { - } + // Multiply the conjugate for quaternion track types + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); - toJSON() { + } else { - const data = super.toJSON(); + const valueEnd = targetValueSize - targetOffset * 2; - data.currentPoint = this.currentPoint.toArray(); + // Subtract each value for all other numeric track types + for ( let k = 0; k < valueEnd; ++ k ) { - return data; + targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; - } + } - fromJSON( json ) { + } - super.fromJSON( json ); + } - this.currentPoint.fromArray( json.currentPoint ); + } - return this; + targetClip.blendMode = AdditiveAnimationBlendMode; - } + return targetClip; } -class Shape extends Path { +var AnimationUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + arraySlice: arraySlice, + convertArray: convertArray, + isTypedArray: isTypedArray, + getKeyframeOrder: getKeyframeOrder, + sortedArray: sortedArray, + flattenJSON: flattenJSON, + subclip: subclip, + makeClipAdditive: makeClipAdditive +}); + +/** + * 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 + * + */ - constructor( points ) { +class Interpolant { - super( points ); + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - this.uuid = MathUtils.generateUUID(); + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; - this.type = 'Shape'; + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; - this.holes = []; + this.settings = null; + this.DefaultSettings_ = {}; } - getPointsHoles( divisions ) { + evaluate( t ) { - const holesPts = []; + const pp = this.parameterPositions; + let i1 = this._cachedIndex, + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + validate_interval: { - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + seek: { - } + let right; - return holesPts; + linear_scan: { - } + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - // get points of shape and holes (keypoints based on segments parameter) + for ( let giveUpAt = i1 + 2; ; ) { - extractPoints( divisions ) { + if ( t1 === undefined ) { - return { + if ( t < t0 ) break forward_scan; - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + // after end - }; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); - } + } - copy( source ) { + if ( i1 === giveUpAt ) break; // this loop - super.copy( source ); + t0 = t1; + t1 = pp[ ++ i1 ]; - this.holes = []; + if ( t < t1 ) { - for ( let i = 0, l = source.holes.length; i < l; i ++ ) { + // we have arrived at the sought interval + break seek; - const hole = source.holes[ i ]; + } - this.holes.push( hole.clone() ); + } - } + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - return this; + } - } + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - toJSON() { + // looping? - const data = super.toJSON(); + const t1global = pp[ 1 ]; - data.uuid = this.uuid; - data.holes = []; + if ( t < t1global ) { - for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - const hole = this.holes[ i ]; - data.holes.push( hole.toJSON() ); + } - } + // linear reverse scan - return data; + for ( let giveUpAt = i1 - 2; ; ) { - } + if ( t0 === undefined ) { - fromJSON( json ) { + // before start - super.fromJSON( json ); + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); - this.uuid = json.uuid; - this.holes = []; + } - for ( let i = 0, l = json.holes.length; i < l; i ++ ) { + if ( i1 === giveUpAt ) break; // this loop - const hole = json.holes[ i ]; - this.holes.push( new Path().fromJSON( hole ) ); + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - } + if ( t >= t0 ) { - return this; + // we have arrived at the sought interval + break seek; - } + } -} + } -class Light extends Object3D { + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - constructor( color, intensity = 1 ) { + } - super(); + // the interval is valid - this.type = 'Light'; + break validate_interval; - this.color = new Color( color ); - this.intensity = intensity; + } // linear scan - } + // binary search - copy( source ) { + while ( i1 < right ) { - super.copy( source ); + const mid = ( i1 + right ) >>> 1; - this.color.copy( source.color ); - this.intensity = source.intensity; + if ( t < pp[ mid ] ) { - return this; + right = mid; - } + } else { - toJSON( meta ) { + i1 = mid + 1; - const data = super.toJSON( meta ); + } - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + } - if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - 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; + // check boundary cases, again - if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); + if ( t0 === undefined ) { - return data; + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); - } + } -} + if ( t1 === undefined ) { -Light.prototype.isLight = true; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); -class HemisphereLight extends Light { + } - constructor( skyColor, groundColor, intensity ) { + } // seek - super( skyColor, intensity ); + this._cachedIndex = i1; - this.type = 'HemisphereLight'; + this.intervalChanged_( i1, t0, t1 ); - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + } // validate_interval - this.groundColor = new Color( groundColor ); + return this.interpolate_( i1, t0, t, t1 ); } - copy( source ) { + getSettings_() { - Light.prototype.copy.call( this, source ); + return this.settings || this.DefaultSettings_; - this.groundColor.copy( source.groundColor ); + } - return this; + copySampleValue_( index ) { - } + // copies a sample value to the result buffer -} + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; -HemisphereLight.prototype.isHemisphereLight = true; + for ( let i = 0; i !== stride; ++ i ) { -const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); -const _lightPositionWorld = /*@__PURE__*/ new Vector3(); -const _lookTarget = /*@__PURE__*/ new Vector3(); + result[ i ] = values[ offset + i ]; -class LightShadow { + } - constructor( camera ) { + return result; - this.camera = camera; + } - this.bias = 0; - this.normalBias = 0; - this.radius = 1; + // Template methods for derived classes: - this.mapSize = new Vector2( 512, 512 ); + interpolate_( /* i1, t0, t, t1 */ ) { - this.map = null; - this.mapPass = null; - this.matrix = new Matrix4(); + throw new Error( 'call to abstract method' ); + // implementations shall return this.resultBuffer - this.autoUpdate = true; - this.needsUpdate = false; + } - this._frustum = new Frustum(); - this._frameExtents = new Vector2( 1, 1 ); + intervalChanged_( /* i1, t0, t1 */ ) { - this._viewportCount = 1; + // empty - this._viewports = [ + } - new Vector4( 0, 0, 1, 1 ) +} - ]; +/** + * 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. + */ - } +class CubicInterpolant extends Interpolant { - getViewportCount() { + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - return this._viewportCount; + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - } + this._weightPrev = - 0; + this._offsetPrev = - 0; + this._weightNext = - 0; + this._offsetNext = - 0; - getFrustum() { + this.DefaultSettings_ = { - return this._frustum; + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - } + }; - updateMatrices( light ) { + } - const shadowCamera = this.camera; - const shadowMatrix = this.matrix; + intervalChanged_( i1, t0, t1 ) { - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( _lightPositionWorld ); + const pp = this.parameterPositions; + let iPrev = i1 - 2, + iNext = i1 + 1, - _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _lookTarget ); - shadowCamera.updateMatrixWorld(); + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - this._frustum.setFromProjectionMatrix( _projScreenMatrix ); + if ( tPrev === undefined ) { - 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 - ); + switch ( this.getSettings_().endingStart ) { - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + case ZeroSlopeEnding: - } + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; - getViewport( viewportIndex ) { + break; - return this._viewports[ viewportIndex ]; + case WrapAroundEnding: - } + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - getFrameExtents() { + break; - return this._frameExtents; + default: // ZeroCurvatureEnding - } + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; - copy( source ) { + } - this.camera = source.camera.clone(); + } - this.bias = source.bias; - this.radius = source.radius; + if ( tNext === undefined ) { - this.mapSize.copy( source.mapSize ); + switch ( this.getSettings_().endingEnd ) { - return this; + case ZeroSlopeEnding: - } + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - clone() { + break; - return new this.constructor().copy( this ); + case WrapAroundEnding: - } + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - toJSON() { + break; - const object = {}; + default: // ZeroCurvatureEnding - if ( this.bias !== 0 ) object.bias = this.bias; - if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; - if ( this.radius !== 1 ) object.radius = this.radius; - if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; - object.camera = this.camera.toJSON( false ).object; - delete object.camera.matrix; + } - return object; + } - } + const halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; -} + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; -class SpotLightShadow extends LightShadow { + } - constructor() { + interpolate_( i1, t0, t, t1 ) { - super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - this.focus = 1; + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - } + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - updateMatrices( light ) { + // evaluate polynomials - const camera = this.camera; + const sP = - wP * ppp + 2 * wP * pp - wP * p; + const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; + const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; - const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus; - const aspect = this.mapSize.width / this.mapSize.height; - const far = light.distance || camera.far; + // combine data linearly - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + for ( let i = 0; i !== stride; ++ i ) { - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; } - super.updateMatrices( light ); + return result; } } -SpotLightShadow.prototype.isSpotLightShadow = true; +class LinearInterpolant extends Interpolant { -class SpotLight extends Light { + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) { + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - super( color, intensity ); + } - this.type = 'SpotLight'; + interpolate_( i1, t0, t, t1 ) { - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - this.target = new Object3D(); + offset1 = i1 * stride, + offset0 = offset1 - stride, - this.distance = distance; - this.angle = angle; - this.penumbra = penumbra; - this.decay = decay; // for physically correct lights, should be 2. + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - this.shadow = new SpotLightShadow(); + for ( let i = 0; i !== stride; ++ i ) { - } + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - get power() { + } - // intensity = power per solid angle. - // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - return this.intensity * Math.PI; + return result; } - set power( power ) { - - // intensity = power per solid angle. - // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - this.intensity = power / Math.PI; +} - } +/** + * + * Interpolant that evaluates to the sample value at the position preceding + * the parameter. + */ - copy( source ) { +class DiscreteInterpolant extends Interpolant { - super.copy( source ); + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - this.target = source.target.clone(); + } - this.shadow = source.shadow.clone(); + interpolate_( i1 /*, t0, t, t1 */ ) { - return this; + return this.copySampleValue_( i1 - 1 ); } } -SpotLight.prototype.isSpotLight = true; +class KeyframeTrack { -const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); -const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); -const _lookTarget$1 = /*@__PURE__*/ new Vector3(); + constructor( name, times, values, interpolation ) { -class PointLightShadow extends LightShadow { + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); - constructor() { + this.name = name; - super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + this.times = convertArray( times, this.TimeBufferType ); + this.values = convertArray( values, this.ValueBufferType ); - this._frameExtents = new Vector2( 4, 2 ); + this.setInterpolation( interpolation || this.DefaultInterpolation ); - this._viewportCount = 6; + } - this._viewports = [ - // 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 + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - // positive X - new Vector4( 2, 1, 1, 1 ), - // negative X - new Vector4( 0, 1, 1, 1 ), - // positive Z - new Vector4( 3, 1, 1, 1 ), - // negative Z - new Vector4( 1, 1, 1, 1 ), - // positive Y - new Vector4( 3, 0, 1, 1 ), - // negative Y - new Vector4( 1, 0, 1, 1 ) - ]; + static toJSON( track ) { - this._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 ) - ]; + const trackType = track.constructor; - this._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 ) - ]; + let json; - } + // derived classes can define a static toJSON method + if ( trackType.toJSON !== this.toJSON ) { - updateMatrices( light, viewportIndex = 0 ) { + json = trackType.toJSON( track ); - const camera = this.camera; - const shadowMatrix = this.matrix; + } else { - _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); - camera.position.copy( _lightPositionWorld$1 ); + // by default, we assume the data can be serialized as-is + json = { - _lookTarget$1.copy( camera.position ); - _lookTarget$1.add( this._cubeDirections[ viewportIndex ] ); - camera.up.copy( this._cubeUps[ viewportIndex ] ); - camera.lookAt( _lookTarget$1 ); - camera.updateMatrixWorld(); + 'name': track.name, + 'times': convertArray( track.times, Array ), + 'values': convertArray( track.values, Array ) - shadowMatrix.makeTranslation( - _lightPositionWorld$1.x, - _lightPositionWorld$1.y, - _lightPositionWorld$1.z ); + }; - _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); + const interpolation = track.getInterpolation(); - } + if ( interpolation !== track.DefaultInterpolation ) { -} + json.interpolation = interpolation; -PointLightShadow.prototype.isPointLightShadow = true; + } -class PointLight extends Light { + } - constructor( color, intensity, distance = 0, decay = 1 ) { + json.type = track.ValueTypeName; // mandatory - super( color, intensity ); + return json; - this.type = 'PointLight'; + } - this.distance = distance; - this.decay = decay; // for physically correct lights, should be 2. + InterpolantFactoryMethodDiscrete( result ) { - this.shadow = new PointLightShadow(); + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); } - get power() { + InterpolantFactoryMethodLinear( result ) { - // intensity = power per solid angle. - // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - return this.intensity * 4 * Math.PI; + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); } - set power( power ) { + InterpolantFactoryMethodSmooth( result ) { + + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + setInterpolation( interpolation ) { + + let factoryMethod; - // intensity = power per solid angle. - // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - this.intensity = power / ( 4 * Math.PI ); + switch ( interpolation ) { - } + case InterpolateDiscrete: - copy( source ) { + factoryMethod = this.InterpolantFactoryMethodDiscrete; - super.copy( source ); + break; - this.distance = source.distance; - this.decay = source.decay; + case InterpolateLinear: - this.shadow = source.shadow.clone(); + factoryMethod = this.InterpolantFactoryMethodLinear; - return this; + break; - } + case InterpolateSmooth: -} + factoryMethod = this.InterpolantFactoryMethodSmooth; -PointLight.prototype.isPointLight = true; + break; -class OrthographicCamera extends Camera { + } - constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { + if ( factoryMethod === undefined ) { - super(); + const message = 'unsupported interpolation for ' + + this.ValueTypeName + ' keyframe track named ' + this.name; - this.type = 'OrthographicCamera'; + if ( this.createInterpolant === undefined ) { - this.zoom = 1; - this.view = null; + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + this.setInterpolation( this.DefaultInterpolation ); - this.near = near; - this.far = far; + } else { - this.updateProjectionMatrix(); + throw new Error( message ); // fatal, in this case - } + } - copy( source, recursive ) { + } - super.copy( source, recursive ); + console.warn( 'THREE.KeyframeTrack:', message ); + return this; - 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 ); + this.createInterpolant = factoryMethod; return this; } - setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + getInterpolation() { - if ( this.view === null ) { + switch ( this.createInterpolant ) { - this.view = { - enabled: true, - fullWidth: 1, - fullHeight: 1, - offsetX: 0, - offsetY: 0, - width: 1, - height: 1 - }; + case this.InterpolantFactoryMethodDiscrete: - } + return InterpolateDiscrete; - this.view.enabled = true; - this.view.fullWidth = fullWidth; - this.view.fullHeight = fullHeight; - this.view.offsetX = x; - this.view.offsetY = y; - this.view.width = width; - this.view.height = height; + case this.InterpolantFactoryMethodLinear: - this.updateProjectionMatrix(); + return InterpolateLinear; - } + case this.InterpolantFactoryMethodSmooth: - clearViewOffset() { + return InterpolateSmooth; - if ( this.view !== null ) { + } - this.view.enabled = false; + } - } + getValueSize() { - this.updateProjectionMatrix(); + return this.values.length / this.times.length; } - updateProjectionMatrix() { + // move all keyframes either forwards or backwards in time + shift( timeOffset ) { - const dx = ( this.right - this.left ) / ( 2 * this.zoom ); - const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - const cx = ( this.right + this.left ) / 2; - const cy = ( this.top + this.bottom ) / 2; + if ( timeOffset !== 0.0 ) { - let left = cx - dx; - let right = cx + dx; - let top = cy + dy; - let bottom = cy - dy; + const times = this.times; - if ( this.view !== null && this.view.enabled ) { + for ( let i = 0, n = times.length; i !== n; ++ i ) { - const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; - const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + times[ i ] += timeOffset; - left += scaleW * this.view.offsetX; - right = left + scaleW * this.view.width; - top -= scaleH * this.view.offsetY; - bottom = top - scaleH * this.view.height; + } } - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - - this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + return this; } - toJSON( meta ) { + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale( timeScale ) { - const data = Object3D.prototype.toJSON.call( this, meta ); + if ( timeScale !== 1.0 ) { - 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; + const times = this.times; - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + for ( let i = 0, n = times.length; i !== n; ++ i ) { - return data; + times[ i ] *= timeScale; - } + } -} + } -OrthographicCamera.prototype.isOrthographicCamera = true; + return this; -class DirectionalLightShadow extends LightShadow { + } - constructor() { + // 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( startTime, endTime ) { - super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + const times = this.times, + nKeys = times.length; - } + let from = 0, + to = nKeys - 1; -} + while ( from !== nKeys && times[ from ] < startTime ) { -DirectionalLightShadow.prototype.isDirectionalLightShadow = true; + ++ from; -class DirectionalLight extends Light { + } - constructor( color, intensity ) { + while ( to !== - 1 && times[ to ] > endTime ) { - super( color, intensity ); + -- to; - this.type = 'DirectionalLight'; + } - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + ++ to; // inclusive -> exclusive bound - this.target = new Object3D(); + if ( from !== 0 || to !== nKeys ) { - this.shadow = new DirectionalLightShadow(); + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) { - } + to = Math.max( to, 1 ); + from = to - 1; - copy( source ) { + } - super.copy( source ); + const stride = this.getValueSize(); + this.times = arraySlice( times, from, to ); + this.values = arraySlice( this.values, from * stride, to * stride ); - this.target = source.target.clone(); - this.shadow = source.shadow.clone(); + } return this; } -} + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate() { -DirectionalLight.prototype.isDirectionalLight = true; + let valid = true; -class AmbientLight extends Light { + const valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - constructor( color, intensity ) { + console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); + valid = false; - super( color, intensity ); + } - this.type = 'AmbientLight'; + const times = this.times, + values = this.values, - } + nKeys = times.length; -} + if ( nKeys === 0 ) { -AmbientLight.prototype.isAmbientLight = true; + console.error( 'THREE.KeyframeTrack: Track is empty.', this ); + valid = false; -class RectAreaLight extends Light { + } - constructor( color, intensity, width = 10, height = 10 ) { + let prevTime = null; - super( color, intensity ); + for ( let i = 0; i !== nKeys; i ++ ) { - this.type = 'RectAreaLight'; + const currTime = times[ i ]; - this.width = width; - this.height = height; + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - } + console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; - copy( source ) { + } - super.copy( source ); + if ( prevTime !== null && prevTime > currTime ) { - this.width = source.width; - this.height = source.height; + console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; - return this; + } - } + prevTime = currTime; - toJSON( meta ) { + } - const data = super.toJSON( meta ); + if ( values !== undefined ) { - data.object.width = this.width; - data.object.height = this.height; + if ( isTypedArray( values ) ) { - return data; + for ( let i = 0, n = values.length; i !== n; ++ i ) { - } + const value = values[ i ]; -} + if ( isNaN( value ) ) { -RectAreaLight.prototype.isRectAreaLight = true; + console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); + valid = false; + break; -/** - * Primary reference: - * https://graphics.stanford.edu/papers/envmap/envmap.pdf - * - * Secondary reference: - * https://www.ppsloan.org/publications/StupidSH36.pdf - */ + } -// 3-band SH defined by 9 coefficients + } -class SphericalHarmonics3 { + } - constructor() { + } - this.coefficients = []; + return valid; - for ( let i = 0; i < 9; i ++ ) { + } - this.coefficients.push( new Vector3() ); + // 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() { - } + // times or values may be shared with other tracks, so overwriting is unsafe + const times = arraySlice( this.times ), + values = arraySlice( this.values ), + stride = this.getValueSize(), - } + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, - set( coefficients ) { + lastIndex = times.length - 1; - for ( let i = 0; i < 9; i ++ ) { + let writeIndex = 1; - this.coefficients[ i ].copy( coefficients[ i ] ); + for ( let i = 1; i < lastIndex; ++ i ) { - } + let keep = false; - return this; + const time = times[ i ]; + const timeNext = times[ i + 1 ]; - } + // remove adjacent keyframes scheduled at the same time - zero() { + if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { - for ( let i = 0; i < 9; i ++ ) { + if ( ! smoothInterpolation ) { - this.coefficients[ i ].set( 0, 0, 0 ); + // remove unnecessary keyframes same as their neighbors - } + const offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - return this; + for ( let j = 0; j !== stride; ++ j ) { - } + const value = values[ offset + j ]; - // get the radiance in the direction of the normal - // target is a Vector3 - getAt( normal, target ) { + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - // normal is assumed to be unit length + keep = true; + break; - const x = normal.x, y = normal.y, z = normal.z; + } - const coeff = this.coefficients; + } - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); + } else { - // band 1 - target.addScaledVector( coeff[ 1 ], 0.488603 * y ); - target.addScaledVector( coeff[ 2 ], 0.488603 * z ); - target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + keep = true; - // band 2 - target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); - target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); - target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); - target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); - target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + } - return target; + } - } + // in-place compaction - // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal - // target is a Vector3 - // https://graphics.stanford.edu/papers/envmap/envmap.pdf - getIrradianceAt( normal, target ) { + if ( keep ) { - // normal is assumed to be unit length + if ( i !== writeIndex ) { - const x = normal.x, y = normal.y, z = normal.z; + times[ writeIndex ] = times[ i ]; - const coeff = this.coefficients; + const readOffset = i * stride, + writeOffset = writeIndex * stride; - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 + for ( let j = 0; j !== stride; ++ j ) { - // band 1 - target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 - target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); - target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); + values[ writeOffset + j ] = values[ readOffset + j ]; - // band 2 - target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 - target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); - target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 - target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); - target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 + } - return target; + } - } + ++ writeIndex; - add( sh ) { + } - for ( let i = 0; i < 9; i ++ ) { + } - this.coefficients[ i ].add( sh.coefficients[ i ] ); + // flush last keyframe (compaction looks ahead) - } + if ( lastIndex > 0 ) { - return this; + times[ writeIndex ] = times[ lastIndex ]; - } + for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { - addScaledSH( sh, s ) { + values[ writeOffset + j ] = values[ readOffset + j ]; - for ( let i = 0; i < 9; i ++ ) { + } - this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); + ++ writeIndex; } - return this; - - } + if ( writeIndex !== times.length ) { - scale( s ) { + this.times = arraySlice( times, 0, writeIndex ); + this.values = arraySlice( values, 0, writeIndex * stride ); - for ( let i = 0; i < 9; i ++ ) { + } else { - this.coefficients[ i ].multiplyScalar( s ); + this.times = times; + this.values = values; } @@ -37765,2486 +38908,2453 @@ class SphericalHarmonics3 { } - lerp( sh, alpha ) { + clone() { - for ( let i = 0; i < 9; i ++ ) { + const times = arraySlice( this.times, 0 ); + const values = arraySlice( this.values, 0 ); - this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack( this.name, times, values ); - } + // Interpolant argument to constructor is not saved, so copy the factory method directly. + track.createInterpolant = this.createInterpolant; - return this; + return track; } - equals( sh ) { - - for ( let i = 0; i < 9; i ++ ) { +} - if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; - return false; +/** + * A Track of Boolean keyframe values. + */ +class BooleanKeyframeTrack extends KeyframeTrack {} - } +BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - } +/** + * A Track of keyframe values that represent color. + */ +class ColorKeyframeTrack extends KeyframeTrack {} - return true; +ColorKeyframeTrack.prototype.ValueTypeName = 'color'; - } +/** + * A Track of numeric keyframe values. + */ +class NumberKeyframeTrack extends KeyframeTrack {} - copy( sh ) { +NumberKeyframeTrack.prototype.ValueTypeName = 'number'; - return this.set( sh.coefficients ); +/** + * Spherical linear unit quaternion interpolant. + */ - } +class QuaternionLinearInterpolant extends Interpolant { - clone() { + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - return new this.constructor().copy( this ); + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); } - fromArray( array, offset = 0 ) { + interpolate_( i1, t0, t, t1 ) { - const coefficients = this.coefficients; + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - for ( let i = 0; i < 9; i ++ ) { + alpha = ( t - t0 ) / ( t1 - t0 ); - coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); + let offset = i1 * stride; - } + for ( let end = offset + stride; offset !== end; offset += 4 ) { - return this; + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); - } + } - toArray( array = [], offset = 0 ) { + return result; - const coefficients = this.coefficients; + } - for ( let i = 0; i < 9; i ++ ) { +} - coefficients[ i ].toArray( array, offset + ( i * 3 ) ); +/** + * A Track of quaternion keyframe values. + */ +class QuaternionKeyframeTrack extends KeyframeTrack { - } + InterpolantFactoryMethodLinear( result ) { - return array; + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); } - // evaluate the basis functions - // shBasis is an Array[ 9 ] - static getBasisAt( normal, shBasis ) { +} - // normal is assumed to be unit length +QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; +// ValueBufferType is inherited +QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - const x = normal.x, y = normal.y, z = normal.z; +/** + * A Track that interpolates Strings + */ +class StringKeyframeTrack extends KeyframeTrack {} - // band 0 - shBasis[ 0 ] = 0.282095; +StringKeyframeTrack.prototype.ValueTypeName = 'string'; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - // band 1 - shBasis[ 1 ] = 0.488603 * y; - shBasis[ 2 ] = 0.488603 * z; - shBasis[ 3 ] = 0.488603 * x; +/** + * A Track of vectored keyframe values. + */ +class VectorKeyframeTrack extends KeyframeTrack {} - // band 2 - shBasis[ 4 ] = 1.092548 * x * y; - shBasis[ 5 ] = 1.092548 * y * z; - shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); - shBasis[ 7 ] = 1.092548 * x * z; - shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); +VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; - } +class AnimationClip { -} + constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) { -SphericalHarmonics3.prototype.isSphericalHarmonics3 = true; + this.name = name; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; -class LightProbe extends Light { + this.uuid = generateUUID(); - constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - super( undefined, intensity ); + this.resetDuration(); - this.sh = sh; + } } - copy( source ) { - super.copy( source ); + static parse( json ) { - this.sh.copy( source.sh ); + const tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); - return this; + for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { - } + tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); - fromJSON( json ) { + } - this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); - this.sh.fromArray( json.sh ); + const clip = new this( json.name, json.duration, tracks, json.blendMode ); + clip.uuid = json.uuid; - return this; + return clip; } - toJSON( meta ) { - - const data = super.toJSON( meta ); + static toJSON( clip ) { - data.object.sh = this.sh.toArray(); + const tracks = [], + clipTracks = clip.tracks; - return data; + const json = { - } + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks, + 'uuid': clip.uuid, + 'blendMode': clip.blendMode -} + }; -LightProbe.prototype.isLightProbe = true; + for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { -class MaterialLoader extends Loader { + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - constructor( manager ) { + } - super( manager ); - this.textures = {}; + return json; } - load( url, onLoad, onProgress, onError ) { - - const scope = this; + static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { - const loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.setRequestHeader( scope.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; - try { + for ( let i = 0; i < numMorphTargets; i ++ ) { - onLoad( scope.parse( JSON.parse( text ) ) ); + let times = []; + let values = []; - } catch ( e ) { + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); - if ( onError ) { + values.push( 0, 1, 0 ); - onError( e ); + const order = getKeyframeOrder( times ); + times = sortedArray( times, 1, order ); + values = sortedArray( values, 1, order ); - } else { + // 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 ) { - console.error( e ); + times.push( numMorphTargets ); + values.push( values[ 0 ] ); - } + } - scope.manager.itemError( url ); + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); - } + } - }, onProgress, onError ); + return new this( name, - 1, tracks ); } - parse( json ) { - - const textures = this.textures; + static findByName( objectOrClipArray, name ) { - function getTexture( name ) { + let clipArray = objectOrClipArray; - if ( textures[ name ] === undefined ) { + if ( ! Array.isArray( objectOrClipArray ) ) { - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; - } + } - return textures[ name ]; + for ( let i = 0; i < clipArray.length; i ++ ) { - } + if ( clipArray[ i ].name === name ) { - const material = new Materials[ json.type ](); + return clipArray[ i ]; - if ( json.uuid !== undefined ) material.uuid = json.uuid; - if ( json.name !== undefined ) material.name = json.name; - if ( json.color !== undefined && material.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.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen ); - if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; - if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; - if ( json.fog !== undefined ) material.fog = json.fog; - if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.combine !== undefined ) material.combine = json.combine; - 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.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; - if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; - if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; - if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; - if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; - if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; - if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; - if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; + } - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; - if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; - if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; + return null; - if ( json.rotation !== undefined ) material.rotation = json.rotation; + } - if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; - if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; - if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; - if ( json.scale !== undefined ) material.scale = json.scale; + static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { - if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; - if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; - if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; + const animationToMorphTargets = {}; - if ( json.skinning !== undefined ) material.skinning = json.skinning; - if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets; - if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals; - if ( json.dithering !== undefined ) material.dithering = json.dithering; + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + const pattern = /^([\w-]*?)([\d]+)$/; - if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents; + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { - if ( json.visible !== undefined ) material.visible = json.visible; + const morphTarget = morphTargets[ i ]; + const parts = morphTarget.name.match( pattern ); - if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; + if ( parts && parts.length > 1 ) { - if ( json.userData !== undefined ) material.userData = json.userData; + const name = parts[ 1 ]; - if ( json.vertexColors !== undefined ) { + let animationMorphTargets = animationToMorphTargets[ name ]; - if ( typeof json.vertexColors === 'number' ) { + if ( ! animationMorphTargets ) { - material.vertexColors = ( json.vertexColors > 0 ) ? true : false; + animationToMorphTargets[ name ] = animationMorphTargets = []; - } else { + } - material.vertexColors = json.vertexColors; + animationMorphTargets.push( morphTarget ); } } - // Shader Material - - if ( json.uniforms !== undefined ) { - - for ( const name in json.uniforms ) { - - const uniform = json.uniforms[ name ]; - - material.uniforms[ name ] = {}; + const clips = []; - switch ( uniform.type ) { + for ( const name in animationToMorphTargets ) { - case 't': - material.uniforms[ name ].value = getTexture( uniform.value ); - break; + clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); - case 'c': - material.uniforms[ name ].value = new Color().setHex( uniform.value ); - break; + } - case 'v2': - material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); - break; + return clips; - case 'v3': - material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); - break; + } - case 'v4': - material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); - break; + // parse the animation.hierarchy format + static parseAnimation( animation, bones ) { - case 'm3': - material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); - break; + if ( ! animation ) { - case 'm4': - material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); - break; + console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); + return null; - default: - material.uniforms[ name ].value = uniform.value; + } - } + const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { - } + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { - } + const times = []; + const values = []; - if ( json.defines !== undefined ) material.defines = json.defines; - if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; - if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + flattenJSON( animationKeys, times, values, propertyName ); - if ( json.extensions !== undefined ) { + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - for ( const key in json.extensions ) { + destTracks.push( new trackType( trackName, times, values ) ); - material.extensions[ key ] = json.extensions[ key ]; + } } - } - - // Deprecated + }; - if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading + const tracks = []; - // for PointsMaterial + const clipName = animation.name || 'default'; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + // automatic length determination in AnimationClip. + let duration = animation.length || - 1; - // maps + const hierarchyTracks = animation.hierarchy || []; - if ( json.map !== undefined ) material.map = getTexture( json.map ); - if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); + for ( let h = 0; h < hierarchyTracks.length; h ++ ) { - if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); + const animationKeys = hierarchyTracks[ h ].keys; - if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); - if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); - if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; - if ( json.normalScale !== undefined ) { + // process morph targets + if ( animationKeys[ 0 ].morphTargets ) { - let normalScale = json.normalScale; + // figure out all morph targets used in this track + const morphTargetNames = {}; - if ( Array.isArray( normalScale ) === false ) { + let k; - // Blender exporter used to export a scalar. See #7459 + for ( k = 0; k < animationKeys.length; k ++ ) { - normalScale = [ normalScale, normalScale ]; + if ( animationKeys[ k ].morphTargets ) { - } + for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { - material.normalScale = new Vector2().fromArray( normalScale ); + morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; - } + } - if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); - if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; - if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; + } - if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); - if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); + } - if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); - if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( const morphTargetName in morphTargetNames ) { - if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + const times = []; + const values = []; - if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); - if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; + for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { - if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; - if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; + const animationKey = animationKeys[ k ]; - if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + } - if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); - if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); - if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); - if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + } - if ( json.transmission !== undefined ) material.transmission = json.transmission; - if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); + duration = morphTargetNames.length * fps; - return material; + } else { - } + // ...assume skeletal animation - setTextures( value ) { + const boneName = '.bones[' + bones[ h ].name + ']'; - this.textures = value; - return this; + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - } + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); -} + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); -const LoaderUtils = { + } - decodeText: function ( array ) { + } - if ( typeof TextDecoder !== 'undefined' ) { + if ( tracks.length === 0 ) { - return new TextDecoder().decode( array ); + return null; } - // Avoid the String.fromCharCode.apply(null, array) shortcut, which - // throws a "maximum call stack size exceeded" error for large arrays. + const clip = new this( clipName, duration, tracks, blendMode ); - let s = ''; + return clip; - for ( let i = 0, il = array.length; i < il; i ++ ) { + } - // Implicitly assumes little-endian. - s += String.fromCharCode( array[ i ] ); + resetDuration() { - } + const tracks = this.tracks; + let duration = 0; - try { + for ( let i = 0, n = tracks.length; i !== n; ++ i ) { - // merges multi-byte utf-8 characters. + const track = this.tracks[ i ]; - return decodeURIComponent( escape( s ) ); + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); - } catch ( e ) { // see #16358 + } - return s; + this.duration = duration; - } + return this; - }, + } - extractUrlBase: function ( url ) { + trim() { - const index = url.lastIndexOf( '/' ); + for ( let i = 0; i < this.tracks.length; i ++ ) { - if ( index === - 1 ) return './'; + this.tracks[ i ].trim( 0, this.duration ); + + } - return url.substr( 0, index + 1 ); + return this; } -}; + validate() { -function InstancedBufferGeometry() { + let valid = true; - BufferGeometry.call( this ); + for ( let i = 0; i < this.tracks.length; i ++ ) { - this.type = 'InstancedBufferGeometry'; - this.instanceCount = Infinity; + valid = valid && this.tracks[ i ].validate(); -} + } -InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), { + return valid; - constructor: InstancedBufferGeometry, + } - isInstancedBufferGeometry: true, + optimize() { - copy: function ( source ) { + for ( let i = 0; i < this.tracks.length; i ++ ) { - BufferGeometry.prototype.copy.call( this, source ); + this.tracks[ i ].optimize(); - this.instanceCount = source.instanceCount; + } return this; - }, - - clone: function () { - - return new this.constructor().copy( this ); + } - }, + clone() { - toJSON: function () { + const tracks = []; - const data = BufferGeometry.prototype.toJSON.call( this ); + for ( let i = 0; i < this.tracks.length; i ++ ) { - data.instanceCount = this.instanceCount; + tracks.push( this.tracks[ i ].clone() ); - data.isInstancedBufferGeometry = true; + } - return data; + return new this.constructor( this.name, this.duration, tracks, this.blendMode ); } -} ); + toJSON() { + + return this.constructor.toJSON( this ); -function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) { + } - if ( typeof ( normalized ) === 'number' ) { +} - meshPerAttribute = normalized; +function getTrackTypeForValueTypeName( typeName ) { - normalized = false; + switch ( typeName.toLowerCase() ) { - console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' ); + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': - } + return NumberKeyframeTrack; - BufferAttribute.call( this, array, itemSize, normalized ); + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': - this.meshPerAttribute = meshPerAttribute || 1; + return VectorKeyframeTrack; -} + case 'color': -InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), { + return ColorKeyframeTrack; - constructor: InstancedBufferAttribute, + case 'quaternion': - isInstancedBufferAttribute: true, + return QuaternionKeyframeTrack; - copy: function ( source ) { + case 'bool': + case 'boolean': - BufferAttribute.prototype.copy.call( this, source ); + return BooleanKeyframeTrack; - this.meshPerAttribute = source.meshPerAttribute; + case 'string': - return this; + return StringKeyframeTrack; - }, + } - toJSON: function () { + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); - const data = BufferAttribute.prototype.toJSON.call( this ); +} - data.meshPerAttribute = this.meshPerAttribute; +function parseKeyframeTrack( json ) { - data.isInstancedBufferAttribute = true; + if ( json.type === undefined ) { - return data; + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); } -} ); + const trackType = getTrackTypeForValueTypeName( json.type ); -class BufferGeometryLoader extends Loader { + if ( json.times === undefined ) { - constructor( manager ) { + const times = [], values = []; - super( manager ); + flattenJSON( json.keys, times, values, 'value' ); + + json.times = times; + json.values = values; } - load( url, onLoad, onProgress, onError ) { + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - const scope = this; + return trackType.parse( json ); - const loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.setRequestHeader( scope.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { + } else { - try { + // by default, we assume a constructor compatible with the base + return new trackType( json.name, json.times, json.values, json.interpolation ); - onLoad( scope.parse( JSON.parse( text ) ) ); + } - } catch ( e ) { +} - if ( onError ) { +const Cache = { - onError( e ); + enabled: false, - } else { + files: {}, - console.error( e ); + add: function ( key, file ) { - } + if ( this.enabled === false ) return; - scope.manager.itemError( url ); + // console.log( 'THREE.Cache', 'Adding key:', key ); - } + this.files[ key ] = file; - }, onProgress, onError ); + }, + + get: function ( key ) { - } + if ( this.enabled === false ) return; - parse( json ) { + // console.log( 'THREE.Cache', 'Checking key:', key ); - const interleavedBufferMap = {}; - const arrayBufferMap = {}; + return this.files[ key ]; - function getInterleavedBuffer( json, uuid ) { + }, - if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; + remove: function ( key ) { - const interleavedBuffers = json.interleavedBuffers; - const interleavedBuffer = interleavedBuffers[ uuid ]; + delete this.files[ key ]; - const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); + }, - const array = getTypedArray( interleavedBuffer.type, buffer ); - const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); - ib.uuid = interleavedBuffer.uuid; + clear: function () { - interleavedBufferMap[ uuid ] = ib; + this.files = {}; - return ib; + } - } +}; - function getArrayBuffer( json, uuid ) { +class LoadingManager { - if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; + constructor( onLoad, onProgress, onError ) { - const arrayBuffers = json.arrayBuffers; - const arrayBuffer = arrayBuffers[ uuid ]; + const scope = this; - const ab = new Uint32Array( arrayBuffer ).buffer; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; - arrayBufferMap[ uuid ] = ab; + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor - return ab; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - } + this.itemStart = function ( url ) { - const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + itemsTotal ++; - const index = json.data.index; + if ( isLoading === false ) { - if ( index !== undefined ) { + if ( scope.onStart !== undefined ) { - const typedArray = getTypedArray( index.type, index.array ); - geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + scope.onStart( url, itemsLoaded, itemsTotal ); - } + } - const attributes = json.data.attributes; + } - for ( const key in attributes ) { + isLoading = true; - const attribute = attributes[ key ]; - let bufferAttribute; + }; - if ( attribute.isInterleavedBufferAttribute ) { + this.itemEnd = function ( url ) { - const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); - bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + itemsLoaded ++; - } else { + if ( scope.onProgress !== undefined ) { - const typedArray = getTypedArray( attribute.type, attribute.array ); - const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; - bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); + scope.onProgress( url, itemsLoaded, itemsTotal ); } - if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; - geometry.setAttribute( key, bufferAttribute ); + if ( itemsLoaded === itemsTotal ) { - } + isLoading = false; - const morphAttributes = json.data.morphAttributes; + if ( scope.onLoad !== undefined ) { - if ( morphAttributes ) { + scope.onLoad(); - for ( const key in morphAttributes ) { + } - const attributeArray = morphAttributes[ key ]; + } - const array = []; + }; - for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + this.itemError = function ( url ) { - const attribute = attributeArray[ i ]; - let bufferAttribute; + if ( scope.onError !== undefined ) { - if ( attribute.isInterleavedBufferAttribute ) { + scope.onError( url ); - const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); - bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + } - } else { + }; - const typedArray = getTypedArray( attribute.type, attribute.array ); - bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + this.resolveURL = function ( url ) { - } + if ( urlModifier ) { - if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; - array.push( bufferAttribute ); + return urlModifier( url ); - } + } - geometry.morphAttributes[ key ] = array; + return url; - } + }; - } + this.setURLModifier = function ( transform ) { - const morphTargetsRelative = json.data.morphTargetsRelative; + urlModifier = transform; - if ( morphTargetsRelative ) { + return this; - geometry.morphTargetsRelative = true; + }; - } + this.addHandler = function ( regex, loader ) { - const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + handlers.push( regex, loader ); - if ( groups !== undefined ) { + return this; - for ( let i = 0, n = groups.length; i !== n; ++ i ) { + }; - const group = groups[ i ]; + this.removeHandler = function ( regex ) { - geometry.addGroup( group.start, group.count, group.materialIndex ); + const index = handlers.indexOf( regex ); + + if ( index !== - 1 ) { + + handlers.splice( index, 2 ); } - } + return this; - const boundingSphere = json.data.boundingSphere; + }; - if ( boundingSphere !== undefined ) { + this.getHandler = function ( file ) { - const center = new Vector3(); + for ( let i = 0, l = handlers.length; i < l; i += 2 ) { - if ( boundingSphere.center !== undefined ) { + const regex = handlers[ i ]; + const loader = handlers[ i + 1 ]; - center.fromArray( boundingSphere.center ); + if ( regex.global ) regex.lastIndex = 0; // see #17920 - } + if ( regex.test( file ) ) { - geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + return loader; - } + } - if ( json.name ) geometry.name = json.name; - if ( json.userData ) geometry.userData = json.userData; + } - return geometry; + return null; + + }; } } -class ObjectLoader extends Loader { +const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); + +class Loader { constructor( manager ) { - super( manager ); + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + this.crossOrigin = 'anonymous'; + this.withCredentials = false; + this.path = ''; + this.resourcePath = ''; + this.requestHeader = {}; } - load( url, onLoad, onProgress, onError ) { + load( /* url, onLoad, onProgress, onError */ ) {} + + loadAsync( url, onProgress ) { const scope = this; - const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; - this.resourcePath = this.resourcePath || path; + return new Promise( function ( resolve, reject ) { - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + scope.load( url, resolve, onProgress, reject ); - let json = null; + } ); - try { + } - json = JSON.parse( text ); + parse( /* data */ ) {} - } catch ( error ) { + setCrossOrigin( crossOrigin ) { - if ( onError !== undefined ) onError( error ); + this.crossOrigin = crossOrigin; + return this; - console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); + } - return; + setWithCredentials( value ) { - } + this.withCredentials = value; + return this; - const metadata = json.metadata; + } - if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + setPath( path ) { - console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); - return; + this.path = path; + return this; - } + } - scope.parse( json, onLoad ); + setResourcePath( resourcePath ) { - }, onProgress, onError ); + this.resourcePath = resourcePath; + return this; } - parse( json, onLoad ) { - - const animations = this.parseAnimations( json.animations ); - const shapes = this.parseShapes( json.shapes ); - const geometries = this.parseGeometries( json.geometries, shapes ); + setRequestHeader( requestHeader ) { - const images = this.parseImages( json.images, function () { + this.requestHeader = requestHeader; + return this; - if ( onLoad !== undefined ) onLoad( object ); + } - } ); +} - const textures = this.parseTextures( json.textures, images ); - const materials = this.parseMaterials( json.materials, textures ); +const loading = {}; - const object = this.parseObject( json.object, geometries, materials, animations ); - const skeletons = this.parseSkeletons( json.skeletons, object ); +class HttpError extends Error { - this.bindSkeletons( object, skeletons ); + constructor( message, response ) { - // + super( message ); + this.response = response; - if ( onLoad !== undefined ) { + } - let hasImages = false; +} - for ( const uuid in images ) { +class FileLoader extends Loader { - if ( images[ uuid ] instanceof HTMLImageElement ) { + constructor( manager ) { - hasImages = true; - break; + super( manager ); - } + } - } + load( url, onLoad, onProgress, onError ) { - if ( hasImages === false ) onLoad( object ); + if ( url === undefined ) url = ''; - } + if ( this.path !== undefined ) url = this.path + url; - return object; + url = this.manager.resolveURL( url ); - } + const cached = Cache.get( url ); - parseShapes( json ) { + if ( cached !== undefined ) { - const shapes = {}; + this.manager.itemStart( url ); - if ( json !== undefined ) { + setTimeout( () => { - for ( let i = 0, l = json.length; i < l; i ++ ) { + if ( onLoad ) onLoad( cached ); - const shape = new Shape().fromJSON( json[ i ] ); + this.manager.itemEnd( url ); - shapes[ shape.uuid ] = shape; + }, 0 ); - } + return cached; } - return shapes; + // Check if request is duplicate - } + if ( loading[ url ] !== undefined ) { - parseSkeletons( json, object ) { + loading[ url ].push( { - const skeletons = {}; - const bones = {}; + onLoad: onLoad, + onProgress: onProgress, + onError: onError - // generate bone lookup table + } ); - object.traverse( function ( child ) { + return; - if ( child.isBone ) bones[ child.uuid ] = child; + } + // Initialise array for duplicate requests + loading[ url ] = []; + + loading[ url ].push( { + onLoad: onLoad, + onProgress: onProgress, + onError: onError, } ); - // create skeletons + // create request + const req = new Request( url, { + headers: new Headers( this.requestHeader ), + credentials: this.withCredentials ? 'include' : 'same-origin', + // An abort controller could be added within a future PR + } ); - if ( json !== undefined ) { + // record states ( avoid data race ) + const mimeType = this.mimeType; + const responseType = this.responseType; - for ( let i = 0, l = json.length; i < l; i ++ ) { + // start the fetch + fetch( req ) + .then( response => { - const skeleton = new Skeleton().fromJSON( json[ i ], bones ); + if ( response.status === 200 || response.status === 0 ) { - skeletons[ skeleton.uuid ] = skeleton; + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. - } + if ( response.status === 0 ) { - } + console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); - return skeletons; + } - } + // Workaround: Checking if response.body === undefined for Alipay browser #23548 - parseGeometries( json, shapes ) { + if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) { - const geometries = {}; - let geometryShapes; + return response; - if ( json !== undefined ) { + } - const bufferGeometryLoader = new BufferGeometryLoader(); + const callbacks = loading[ url ]; + const reader = response.body.getReader(); + const contentLength = response.headers.get( 'Content-Length' ); + const total = contentLength ? parseInt( contentLength ) : 0; + const lengthComputable = total !== 0; + let loaded = 0; - for ( let i = 0, l = json.length; i < l; i ++ ) { + // periodically read data into the new stream tracking while download progress + const stream = new ReadableStream( { + start( controller ) { - let geometry; - const data = json[ i ]; + readData(); - switch ( data.type ) { + function readData() { - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + reader.read().then( ( { done, value } ) => { - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + if ( done ) { - break; + controller.close(); - case 'BoxGeometry': - case 'BoxBufferGeometry': + } else { - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + loaded += value.byteLength; - break; + const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } ); + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { - case 'CircleGeometry': - case 'CircleBufferGeometry': + const callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); - geometry = new Geometries[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + } - break; + controller.enqueue( value ); + readData(); - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + } ); - break; + } - case 'ConeGeometry': - case 'ConeBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + } ); - break; + return new Response( stream ); - case 'SphereGeometry': - case 'SphereBufferGeometry': + } else { - geometry = new Geometries[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response ); - break; + } - case 'DodecahedronGeometry': - case 'DodecahedronBufferGeometry': - case 'IcosahedronGeometry': - case 'IcosahedronBufferGeometry': - case 'OctahedronGeometry': - case 'OctahedronBufferGeometry': - case 'TetrahedronGeometry': - case 'TetrahedronBufferGeometry': + } ) + .then( response => { - geometry = new Geometries[ data.type ]( - data.radius, - data.detail - ); + switch ( responseType ) { - break; + case 'arraybuffer': - case 'RingGeometry': - case 'RingBufferGeometry': + return response.arrayBuffer(); - geometry = new Geometries[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + case 'blob': - break; + return response.blob(); - case 'TorusGeometry': - case 'TorusBufferGeometry': + case 'document': - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + return response.text() + .then( text => { - break; + const parser = new DOMParser(); + return parser.parseFromString( text, mimeType ); - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + } ); - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + case 'json': - break; + return response.json(); - case 'TubeGeometry': - case 'TubeBufferGeometry': + default: - // This only works for built-in curves (e.g. CatmullRomCurve3). - // User defined curves or instances of CurvePath will not be deserialized. - geometry = new Geometries[ data.type ]( - new Curves[ data.path.type ]().fromJSON( data.path ), - data.tubularSegments, - data.radius, - data.radialSegments, - data.closed - ); + if ( mimeType === undefined ) { - break; + return response.text(); - case 'LatheGeometry': - case 'LatheBufferGeometry': + } else { - geometry = new Geometries[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + // sniff encoding + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec( mimeType ); + const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined; + const decoder = new TextDecoder( label ); + return response.arrayBuffer().then( ab => decoder.decode( ab ) ); - break; + } - case 'PolyhedronGeometry': - case 'PolyhedronBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.vertices, - data.indices, - data.radius, - data.details - ); + } ) + .then( data => { - break; + // Add to cache only on HTTP success, so that we do not cache + // error response bodies as proper responses to requests. + Cache.add( url, data ); - case 'ShapeGeometry': - case 'ShapeBufferGeometry': + const callbacks = loading[ url ]; + delete loading[ url ]; - geometryShapes = []; + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { - for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + const callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( data ); - const shape = shapes[ data.shapes[ j ] ]; + } - geometryShapes.push( shape ); + } ) + .catch( err => { - } + // Abort errors and other errors are handled the same - geometry = new Geometries[ data.type ]( - geometryShapes, - data.curveSegments - ); + const callbacks = loading[ url ]; - break; + if ( callbacks === undefined ) { + // When onLoad was called and url was deleted in `loading` + this.manager.itemError( url ); + throw err; - case 'ExtrudeGeometry': - case 'ExtrudeBufferGeometry': + } - geometryShapes = []; + delete loading[ url ]; - for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { - const shape = shapes[ data.shapes[ j ] ]; + const callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( err ); - geometryShapes.push( shape ); + } - } + this.manager.itemError( url ); - const extrudePath = data.options.extrudePath; + } ) + .finally( () => { - if ( extrudePath !== undefined ) { + this.manager.itemEnd( url ); - data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + } ); - } + this.manager.itemStart( url ); - geometry = new Geometries[ data.type ]( - geometryShapes, - data.options - ); + } - break; + setResponseType( value ) { - case 'BufferGeometry': - case 'InstancedBufferGeometry': + this.responseType = value; + return this; - geometry = bufferGeometryLoader.parse( data ); + } - break; + setMimeType( value ) { - case 'Geometry': + this.mimeType = value; + return this; - console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' ); + } - break; +} - default: +class AnimationLoader extends Loader { - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + constructor( manager ) { - continue; + super( manager ); - } + } - geometry.uuid = data.uuid; + load( url, onLoad, onProgress, onError ) { - if ( data.name !== undefined ) geometry.name = data.name; - if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; + const scope = this; - geometries[ data.uuid ] = geometry; + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - } + try { - } + onLoad( scope.parse( JSON.parse( text ) ) ); - return geometries; + } catch ( e ) { - } + if ( onError ) { - parseMaterials( json, textures ) { + onError( e ); - const cache = {}; // MultiMaterial - const materials = {}; + } else { - if ( json !== undefined ) { + console.error( e ); - const loader = new MaterialLoader(); - loader.setTextures( textures ); + } - for ( let i = 0, l = json.length; i < l; i ++ ) { + scope.manager.itemError( url ); - const data = json[ i ]; + } - if ( data.type === 'MultiMaterial' ) { + }, onProgress, onError ); - // Deprecated + } - const array = []; + parse( json ) { - for ( let j = 0; j < data.materials.length; j ++ ) { + const animations = []; - const material = data.materials[ j ]; + for ( let i = 0; i < json.length; i ++ ) { - if ( cache[ material.uuid ] === undefined ) { + const clip = AnimationClip.parse( json[ i ] ); - cache[ material.uuid ] = loader.parse( material ); + animations.push( clip ); - } + } - array.push( cache[ material.uuid ] ); + return animations; - } + } - materials[ data.uuid ] = array; +} - } else { +/** + * Abstract Base class to block based textures loader (dds, pvr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ - if ( cache[ data.uuid ] === undefined ) { +class CompressedTextureLoader extends Loader { - cache[ data.uuid ] = loader.parse( data ); + constructor( manager ) { - } + super( manager ); - materials[ data.uuid ] = cache[ data.uuid ]; + } - } + load( url, onLoad, onProgress, onError ) { - } + const scope = this; - } + const images = []; - return materials; + const texture = new CompressedTexture(); - } + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); - parseAnimations( json ) { + let loaded = 0; - const animations = {}; + function loadTexture( i ) { - if ( json !== undefined ) { + loader.load( url[ i ], function ( buffer ) { - for ( let i = 0; i < json.length; i ++ ) { + const texDatas = scope.parse( buffer, true ); - const data = json[ i ]; + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; - const clip = AnimationClip.parse( data ); + loaded += 1; - animations[ clip.uuid ] = clip; + if ( loaded === 6 ) { - } + if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; - } + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; - return animations; + if ( onLoad ) onLoad( texture ); - } + } - parseImages( json, onLoad ) { + }, onProgress, onError ); - const scope = this; - const images = {}; + } - let loader; + if ( Array.isArray( url ) ) { - function loadImage( url ) { + for ( let i = 0, il = url.length; i < il; ++ i ) { - scope.manager.itemStart( url ); + loadTexture( i ); - return loader.load( url, function () { + } - scope.manager.itemEnd( url ); + } else { - }, undefined, function () { + // compressed cubemap texture stored in a single DDS file - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + loader.load( url, function ( buffer ) { - } ); + const texDatas = scope.parse( buffer, true ); - } + if ( texDatas.isCubemap ) { - function deserializeImage( image ) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; - if ( typeof image === 'string' ) { + for ( let f = 0; f < faces; f ++ ) { - const url = image; + images[ f ] = { mipmaps: [] }; - const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + for ( let i = 0; i < texDatas.mipmapCount; i ++ ) { - return loadImage( path ); + 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; - } else { + } - if ( image.data ) { + } - return { - data: getTypedArray( image.type, image.data ), - width: image.width, - height: image.height - }; + texture.image = images; } else { - return null; + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; } - } - - } - - if ( json !== undefined && json.length > 0 ) { - - const manager = new LoadingManager( onLoad ); - - loader = new ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + if ( texDatas.mipmapCount === 1 ) { - for ( let i = 0, il = json.length; i < il; i ++ ) { + texture.minFilter = LinearFilter; - const image = json[ i ]; - const url = image.url; + } - if ( Array.isArray( url ) ) { + texture.format = texDatas.format; + texture.needsUpdate = true; - // load array of images e.g CubeTexture + if ( onLoad ) onLoad( texture ); - images[ image.uuid ] = []; + }, onProgress, onError ); - for ( let j = 0, jl = url.length; j < jl; j ++ ) { + } - const currentUrl = url[ j ]; + return texture; - const deserializedImage = deserializeImage( currentUrl ); + } - if ( deserializedImage !== null ) { +} - if ( deserializedImage instanceof HTMLImageElement ) { +class ImageLoader extends Loader { - images[ image.uuid ].push( deserializedImage ); + constructor( manager ) { - } else { + super( manager ); - // special case: handle array of data textures for cube textures + } - images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + load( url, onLoad, onProgress, onError ) { - } + if ( this.path !== undefined ) url = this.path + url; - } + url = this.manager.resolveURL( url ); - } + const scope = this; - } else { + const cached = Cache.get( url ); - // load single image + if ( cached !== undefined ) { - const deserializedImage = deserializeImage( image.url ); + scope.manager.itemStart( url ); - if ( deserializedImage !== null ) { + setTimeout( function () { - images[ image.uuid ] = deserializedImage; + if ( onLoad ) onLoad( cached ); - } + scope.manager.itemEnd( url ); - } + }, 0 ); - } + return cached; } - return images; - - } + const image = createElementNS( 'img' ); - parseTextures( json, images ) { + function onImageLoad() { - function parseConstant( value, type ) { + removeEventListeners(); - if ( typeof value === 'number' ) return value; + Cache.add( url, this ); - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + if ( onLoad ) onLoad( this ); - return type[ value ]; + scope.manager.itemEnd( url ); } - const textures = {}; - - if ( json !== undefined ) { + function onImageError( event ) { - for ( let i = 0, l = json.length; i < l; i ++ ) { + removeEventListeners(); - const data = json[ i ]; + if ( onError ) onError( event ); - if ( data.image === undefined ) { + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + } - } + function removeEventListeners() { - if ( images[ data.image ] === undefined ) { + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + } - } + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); - let texture; - const image = images[ data.image ]; + if ( url.slice( 0, 5 ) !== 'data:' ) { - if ( Array.isArray( image ) ) { + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; - texture = new CubeTexture( image ); + } - if ( image.length === 6 ) texture.needsUpdate = true; + scope.manager.itemStart( url ); - } else { + image.src = url; - if ( image && image.data ) { + return image; - texture = new DataTexture( image.data, image.width, image.height ); + } - } else { +} - texture = new Texture( image ); +class CubeTextureLoader extends Loader { - } + constructor( manager ) { - if ( image ) texture.needsUpdate = true; // textures can have undefined image data + super( manager ); - } + } - texture.uuid = data.uuid; + load( urls, onLoad, onProgress, onError ) { - if ( data.name !== undefined ) texture.name = data.name; + const texture = new CubeTexture(); - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); - if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); - if ( data.center !== undefined ) texture.center.fromArray( data.center ); - if ( data.rotation !== undefined ) texture.rotation = data.rotation; + let loaded = 0; - if ( data.wrap !== undefined ) { + function loadTexture( i ) { - texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); - texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + loader.load( urls[ i ], function ( image ) { - } + texture.images[ i ] = image; - if ( data.format !== undefined ) texture.format = data.format; - if ( data.type !== undefined ) texture.type = data.type; - if ( data.encoding !== undefined ) texture.encoding = data.encoding; + loaded ++; - if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); - if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); - if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + if ( loaded === 6 ) { - if ( data.flipY !== undefined ) texture.flipY = data.flipY; + texture.needsUpdate = true; - if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; - if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; + if ( onLoad ) onLoad( texture ); - textures[ data.uuid ] = texture; + } - } + }, undefined, onError ); } - return textures; - - } + for ( let i = 0; i < urls.length; ++ i ) { - parseObject( data, geometries, materials, animations ) { + loadTexture( i ); - let object; + } - function getGeometry( name ) { + return texture; - if ( geometries[ name ] === undefined ) { + } - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); +} - } +/** + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ - return geometries[ name ]; +class DataTextureLoader extends Loader { - } + constructor( manager ) { - function getMaterial( name ) { + super( manager ); - if ( name === undefined ) return undefined; + } - if ( Array.isArray( name ) ) { + load( url, onLoad, onProgress, onError ) { - const array = []; + const scope = this; - for ( let i = 0, l = name.length; i < l; i ++ ) { + const texture = new DataTexture(); - const uuid = name[ i ]; + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setPath( this.path ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( buffer ) { - if ( materials[ uuid ] === undefined ) { + const texData = scope.parse( buffer ); - console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); + if ( ! texData ) return; - } + if ( texData.image !== undefined ) { - array.push( materials[ uuid ] ); + texture.image = texData.image; - } + } else if ( texData.data !== undefined ) { - return array; + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; } - if ( materials[ name ] === undefined ) { - - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; - } + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; - return materials[ name ]; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; - } + if ( texData.encoding !== undefined ) { - let geometry, material; + texture.encoding = texData.encoding; - switch ( data.type ) { + } - case 'Scene': + if ( texData.flipY !== undefined ) { - object = new Scene(); + texture.flipY = texData.flipY; - if ( data.background !== undefined ) { + } - if ( Number.isInteger( data.background ) ) { + if ( texData.format !== undefined ) { - object.background = new Color( data.background ); + texture.format = texData.format; - } + } - } + if ( texData.type !== undefined ) { - if ( data.fog !== undefined ) { + texture.type = texData.type; - if ( data.fog.type === 'Fog' ) { + } - object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + if ( texData.mipmaps !== undefined ) { - } else if ( data.fog.type === 'FogExp2' ) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; // presumably... - object.fog = new FogExp2( data.fog.color, data.fog.density ); + } - } + if ( texData.mipmapCount === 1 ) { - } + texture.minFilter = LinearFilter; - break; + } - case 'PerspectiveCamera': + if ( texData.generateMipmaps !== undefined ) { - object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + texture.generateMipmaps = texData.generateMipmaps; - 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 ); + } - break; + texture.needsUpdate = true; - case 'OrthographicCamera': + if ( onLoad ) onLoad( texture, texData ); - object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + }, onProgress, onError ); - if ( data.zoom !== undefined ) object.zoom = data.zoom; - if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - break; + return texture; - case 'AmbientLight': + } - object = new AmbientLight( data.color, data.intensity ); +} - break; +class TextureLoader extends Loader { - case 'DirectionalLight': + constructor( manager ) { - object = new DirectionalLight( data.color, data.intensity ); + super( manager ); - break; + } - case 'PointLight': + load( url, onLoad, onProgress, onError ) { - object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + const texture = new Texture(); - break; + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - case 'RectAreaLight': + loader.load( url, function ( image ) { - object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + texture.image = image; + texture.needsUpdate = true; - break; + if ( onLoad !== undefined ) { - case 'SpotLight': + onLoad( texture ); - object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + } - break; + }, onProgress, onError ); - case 'HemisphereLight': + return texture; - object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + } - break; +} - case 'LightProbe': +class Light extends Object3D { - object = new LightProbe().fromJSON( data ); + constructor( color, intensity = 1 ) { - break; + super(); - case 'SkinnedMesh': + this.isLight = true; - geometry = getGeometry( data.geometry ); - material = getMaterial( data.material ); + this.type = 'Light'; - object = new SkinnedMesh( geometry, material ); + this.color = new Color( color ); + this.intensity = intensity; - if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; - if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); - if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; + } - break; + dispose() { - case 'Mesh': + // Empty here in base class; some subclasses override. - geometry = getGeometry( data.geometry ); - material = getMaterial( data.material ); + } - object = new Mesh( geometry, material ); + copy( source, recursive ) { - break; + super.copy( source, recursive ); - case 'InstancedMesh': + this.color.copy( source.color ); + this.intensity = source.intensity; - geometry = getGeometry( data.geometry ); - material = getMaterial( data.material ); - const count = data.count; - const instanceMatrix = data.instanceMatrix; + return this; - object = new InstancedMesh( geometry, material, count ); - object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + } - break; + toJSON( meta ) { - case 'LOD': + const data = super.toJSON( meta ); - object = new LOD(); + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; - break; + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); - case 'Line': + 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; - object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); - break; + return data; - case 'LineLoop': + } - object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); +} - break; +class HemisphereLight extends Light { - case 'LineSegments': + constructor( skyColor, groundColor, intensity ) { - object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + super( skyColor, intensity ); - break; + this.isHemisphereLight = true; - case 'PointCloud': - case 'Points': + this.type = 'HemisphereLight'; - object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - break; + this.groundColor = new Color( groundColor ); - case 'Sprite': + } - object = new Sprite( getMaterial( data.material ) ); + copy( source, recursive ) { - break; + super.copy( source, recursive ); - case 'Group': + this.groundColor.copy( source.groundColor ); - object = new Group(); + return this; - break; + } - case 'Bone': +} - object = new Bone(); +const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); +const _lookTarget$1 = /*@__PURE__*/ new Vector3(); - break; +class LightShadow { - default: + constructor( camera ) { - object = new Object3D(); + this.camera = camera; - } + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; - object.uuid = data.uuid; + this.mapSize = new Vector2( 512, 512 ); - if ( data.name !== undefined ) object.name = data.name; + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); - if ( data.matrix !== undefined ) { + this.autoUpdate = true; + this.needsUpdate = false; - object.matrix.fromArray( data.matrix ); + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); - if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; - if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale ); + this._viewportCount = 1; - } else { + this._viewports = [ - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + new Vector4( 0, 0, 1, 1 ) - } + ]; - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + } - if ( data.shadow ) { + getViewportCount() { - if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; - if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; - if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; - if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); - if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); + return this._viewportCount; - } + } - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; - if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; - if ( data.userData !== undefined ) object.userData = data.userData; - if ( data.layers !== undefined ) object.layers.mask = data.layers; + getFrustum() { - if ( data.children !== undefined ) { + return this._frustum; - const children = data.children; + } - for ( let i = 0; i < children.length; i ++ ) { + updateMatrices( light ) { - object.add( this.parseObject( children[ i ], geometries, materials, animations ) ); + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; - } + _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld$1 ); - } + _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget$1 ); + shadowCamera.updateMatrixWorld(); - if ( data.animations !== undefined ) { + _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); - const objectAnimations = data.animations; + 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 + ); - for ( let i = 0; i < objectAnimations.length; i ++ ) { + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - const uuid = objectAnimations[ i ]; + } - object.animations.push( animations[ uuid ] ); + getViewport( viewportIndex ) { - } + return this._viewports[ viewportIndex ]; - } + } - if ( data.type === 'LOD' ) { + getFrameExtents() { - if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; + return this._frameExtents; - const levels = data.levels; + } - for ( let l = 0; l < levels.length; l ++ ) { + dispose() { - const level = levels[ l ]; - const child = object.getObjectByProperty( 'uuid', level.object ); + if ( this.map ) { - if ( child !== undefined ) { + this.map.dispose(); - object.addLevel( child, level.distance ); + } - } + if ( this.mapPass ) { - } + this.mapPass.dispose(); } - return object; - } - bindSkeletons( object, skeletons ) { - - if ( Object.keys( skeletons ).length === 0 ) return; - - object.traverse( function ( child ) { + copy( source ) { - if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { + this.camera = source.camera.clone(); - const skeleton = skeletons[ child.skeleton ]; + this.bias = source.bias; + this.radius = source.radius; - if ( skeleton === undefined ) { + this.mapSize.copy( source.mapSize ); - console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton ); + return this; - } else { + } - child.bind( skeleton, child.bindMatrix ); + clone() { - } + return new this.constructor().copy( this ); - } + } - } ); + toJSON() { - } + const object = {}; - /* DEPRECATED */ + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); - setTexturePath( value ) { + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; - console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' ); - return this.setResourcePath( value ); + return object; } } -const TEXTURE_MAPPING = { - UVMapping: UVMapping, - CubeReflectionMapping: CubeReflectionMapping, - CubeRefractionMapping: CubeRefractionMapping, - EquirectangularReflectionMapping: EquirectangularReflectionMapping, - EquirectangularRefractionMapping: EquirectangularRefractionMapping, - CubeUVReflectionMapping: CubeUVReflectionMapping, - CubeUVRefractionMapping: CubeUVRefractionMapping -}; - -const TEXTURE_WRAPPING = { - RepeatWrapping: RepeatWrapping, - ClampToEdgeWrapping: ClampToEdgeWrapping, - MirroredRepeatWrapping: MirroredRepeatWrapping -}; - -const TEXTURE_FILTER = { - NearestFilter: NearestFilter, - NearestMipmapNearestFilter: NearestMipmapNearestFilter, - NearestMipmapLinearFilter: NearestMipmapLinearFilter, - LinearFilter: LinearFilter, - LinearMipmapNearestFilter: LinearMipmapNearestFilter, - LinearMipmapLinearFilter: LinearMipmapLinearFilter -}; - -function ImageBitmapLoader( manager ) { +class SpotLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - if ( typeof createImageBitmap === 'undefined' ) { + this.isSpotLightShadow = true; - console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); + this.focus = 1; } - if ( typeof fetch === 'undefined' ) { + updateMatrices( light ) { - console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); + const camera = this.camera; - } + const fov = RAD2DEG * 2 * light.angle * this.focus; + const aspect = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; - Loader.call( this, manager ); + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { - this.options = { premultiplyAlpha: 'none' }; + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); -} + } -ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + super.updateMatrices( light ); - constructor: ImageBitmapLoader, + } - isImageBitmapLoader: true, + copy( source ) { - setOptions: function setOptions( options ) { + super.copy( source ); - this.options = options; + this.focus = source.focus; return this; - }, - - load: function ( url, onLoad, onProgress, onError ) { + } - if ( url === undefined ) url = ''; +} - if ( this.path !== undefined ) url = this.path + url; +class SpotLight extends Light { - url = this.manager.resolveURL( url ); + constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) { - const scope = this; + super( color, intensity ); - const cached = Cache.get( url ); + this.isSpotLight = true; - if ( cached !== undefined ) { + this.type = 'SpotLight'; - scope.manager.itemStart( url ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - setTimeout( function () { + this.target = new Object3D(); - if ( onLoad ) onLoad( cached ); + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; // for physically correct lights, should be 2. - scope.manager.itemEnd( url ); + this.map = null; - }, 0 ); + this.shadow = new SpotLightShadow(); - return cached; + } - } + get power() { - const fetchOptions = {}; - fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; - fetchOptions.headers = this.requestHeader; + // compute the light's luminous power (in lumens) from its intensity (in candela) + // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd) + return this.intensity * Math.PI; - fetch( url, fetchOptions ).then( function ( res ) { + } - return res.blob(); + set power( power ) { - } ).then( function ( blob ) { + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / Math.PI; - return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) ); + } - } ).then( function ( imageBitmap ) { + dispose() { - Cache.add( url, imageBitmap ); + this.shadow.dispose(); - if ( onLoad ) onLoad( imageBitmap ); + } - scope.manager.itemEnd( url ); + copy( source, recursive ) { - } ).catch( function ( e ) { + super.copy( source, recursive ); - if ( onError ) onError( e ); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + this.target = source.target.clone(); - } ); + this.shadow = source.shadow.clone(); - scope.manager.itemStart( url ); + return this; } -} ); +} -class ShapePath { +const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld = /*@__PURE__*/ new Vector3(); +const _lookTarget = /*@__PURE__*/ new Vector3(); + +class PointLightShadow extends LightShadow { constructor() { - this.type = 'ShapePath'; + super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); - this.color = new Color(); + this.isPointLightShadow = true; - this.subPaths = []; - this.currentPath = null; + this._frameExtents = new Vector2( 4, 2 ); - } + this._viewportCount = 6; - moveTo( x, y ) { + this._viewports = [ + // 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.currentPath = new Path(); - this.subPaths.push( this.currentPath ); - this.currentPath.moveTo( x, y ); + // positive X + new Vector4( 2, 1, 1, 1 ), + // negative X + new Vector4( 0, 1, 1, 1 ), + // positive Z + new Vector4( 3, 1, 1, 1 ), + // negative Z + new Vector4( 1, 1, 1, 1 ), + // positive Y + new Vector4( 3, 0, 1, 1 ), + // negative Y + new Vector4( 1, 0, 1, 1 ) + ]; - return this; + this._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 ) + ]; - } + this._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 ) + ]; - lineTo( x, y ) { + } - this.currentPath.lineTo( x, y ); + updateMatrices( light, viewportIndex = 0 ) { - return this; + const camera = this.camera; + const shadowMatrix = this.matrix; - } + const far = light.distance || camera.far; - quadraticCurveTo( aCPx, aCPy, aX, aY ) { + if ( far !== camera.far ) { - this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + camera.far = far; + camera.updateProjectionMatrix(); - return this; + } - } + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + camera.position.copy( _lightPositionWorld ); - bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + _lookTarget.copy( camera.position ); + _lookTarget.add( this._cubeDirections[ viewportIndex ] ); + camera.up.copy( this._cubeUps[ viewportIndex ] ); + camera.lookAt( _lookTarget ); + camera.updateMatrixWorld(); - this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); - return this; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix ); } - splineThru( pts ) { - - this.currentPath.splineThru( pts ); +} - return this; +class PointLight extends Light { - } + constructor( color, intensity, distance = 0, decay = 1 ) { - toShapes( isCCW, noHoles ) { + super( color, intensity ); - function toShapesNoHoles( inSubpaths ) { + this.isPointLight = true; - const shapes = []; + this.type = 'PointLight'; - for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { + this.distance = distance; + this.decay = decay; // for physically correct lights, should be 2. - const tmpPath = inSubpaths[ i ]; + this.shadow = new PointLightShadow(); - const tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; + } - shapes.push( tmpShape ); + get power() { - } + // compute the light's luminous power (in lumens) from its intensity (in candela) + // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd) + return this.intensity * 4 * Math.PI; - return shapes; + } - } + set power( power ) { - function isPointInsidePolygon( inPt, inPolygon ) { + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / ( 4 * Math.PI ); - const 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 - let inside = false; - for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + dispose() { - let edgeLowPt = inPolygon[ p ]; - let edgeHighPt = inPolygon[ q ]; + this.shadow.dispose(); - let edgeDx = edgeHighPt.x - edgeLowPt.x; - let edgeDy = edgeHighPt.y - edgeLowPt.y; + } - if ( Math.abs( edgeDy ) > Number.EPSILON ) { + copy( source, recursive ) { - // not parallel - if ( edgeDy < 0 ) { + super.copy( source, recursive ); - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + this.distance = source.distance; + this.decay = source.decay; - } + this.shadow = source.shadow.clone(); - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + return this; - if ( inPt.y === edgeLowPt.y ) { + } - if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! +} - } else { +class DirectionalLightShadow extends LightShadow { - const 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 + constructor() { - } + super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); - } else { + this.isDirectionalLightShadow = true; - // 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; + } - } +} - } +class DirectionalLight extends Light { - return inside; + constructor( color, intensity ) { - } + super( color, intensity ); - const isClockWise = ShapeUtils.isClockWise; + this.isDirectionalLight = true; - const subPaths = this.subPaths; - if ( subPaths.length === 0 ) return []; + this.type = 'DirectionalLight'; - if ( noHoles === true ) return toShapesNoHoles( subPaths ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); + this.target = new Object3D(); - let solid, tmpPath, tmpShape; - const shapes = []; + this.shadow = new DirectionalLightShadow(); - if ( subPaths.length === 1 ) { + } - tmpPath = subPaths[ 0 ]; - tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + dispose() { - } + this.shadow.dispose(); - let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + } - // console.log("Holes first", holesFirst); + copy( source ) { - const betterShapeHoles = []; - const newShapes = []; - let newShapeHoles = []; - let mainIdx = 0; - let tmpPoints; + super.copy( source ); - newShapes[ mainIdx ] = undefined; - newShapeHoles[ mainIdx ] = []; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); - for ( let i = 0, l = subPaths.length; i < l; i ++ ) { + return this; - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + } - if ( solid ) { +} - if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; +class AmbientLight extends Light { - newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; - newShapes[ mainIdx ].s.curves = tmpPath.curves; + constructor( color, intensity ) { - if ( holesFirst ) mainIdx ++; - newShapeHoles[ mainIdx ] = []; + super( color, intensity ); - //console.log('cw', i); + this.isAmbientLight = true; - } else { + this.type = 'AmbientLight'; - newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + } - //console.log('ccw', i); +} - } +class RectAreaLight extends Light { - } + constructor( color, intensity, width = 10, height = 10 ) { - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + super( color, intensity ); + this.isRectAreaLight = true; - if ( newShapes.length > 1 ) { + this.type = 'RectAreaLight'; - let ambiguous = false; - const toChange = []; + this.width = width; + this.height = height; - for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + } - betterShapeHoles[ sIdx ] = []; + get power() { - } + // compute the light's luminous power (in lumens) from its intensity (in nits) + return this.intensity * this.width * this.height * Math.PI; - for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + } - const sho = newShapeHoles[ sIdx ]; + set power( power ) { - for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { + // set the light's intensity (in nits) from the desired luminous power (in lumens) + this.intensity = power / ( this.width * this.height * Math.PI ); - const ho = sho[ hIdx ]; - let hole_unassigned = true; + } - for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + copy( source ) { - if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + super.copy( source ); - if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { + this.width = source.width; + this.height = source.height; - hole_unassigned = false; - betterShapeHoles[ s2Idx ].push( ho ); + return this; - } else { + } - ambiguous = true; + toJSON( meta ) { - } + const data = super.toJSON( meta ); - } + data.object.width = this.width; + data.object.height = this.height; - } + return data; - if ( hole_unassigned ) { + } - betterShapeHoles[ sIdx ].push( ho ); +} - } +/** + * Primary reference: + * https://graphics.stanford.edu/papers/envmap/envmap.pdf + * + * Secondary reference: + * https://www.ppsloan.org/publications/StupidSH36.pdf + */ - } +// 3-band SH defined by 9 coefficients - } - // console.log("ambiguous: ", ambiguous); +class SphericalHarmonics3 { - if ( toChange.length > 0 ) { + constructor() { - // console.log("to change: ", toChange); - if ( ! ambiguous ) newShapeHoles = betterShapeHoles; + this.isSphericalHarmonics3 = true; - } + this.coefficients = []; - } + for ( let i = 0; i < 9; i ++ ) { - let tmpHoles; + this.coefficients.push( new Vector3() ); - for ( let i = 0, il = newShapes.length; i < il; i ++ ) { + } - tmpShape = newShapes[ i ].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[ i ]; + } - for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + set( coefficients ) { - tmpShape.holes.push( tmpHoles[ j ].h ); + for ( let i = 0; i < 9; i ++ ) { - } + this.coefficients[ i ].copy( coefficients[ i ] ); } - //console.log("shape", shapes); - - return shapes; + return this; } -} + zero() { -class Font { + for ( let i = 0; i < 9; i ++ ) { - constructor( data ) { + this.coefficients[ i ].set( 0, 0, 0 ); - this.type = 'Font'; + } - this.data = data; + return this; } - generateShapes( text, size = 100 ) { + // get the radiance in the direction of the normal + // target is a Vector3 + getAt( normal, target ) { - const shapes = []; - const paths = createPaths( text, size, this.data ); + // normal is assumed to be unit length - for ( let p = 0, pl = paths.length; p < pl; p ++ ) { + const x = normal.x, y = normal.y, z = normal.z; - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + const coeff = this.coefficients; - } + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); - return shapes; + // band 1 + target.addScaledVector( coeff[ 1 ], 0.488603 * y ); + target.addScaledVector( coeff[ 2 ], 0.488603 * z ); + target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); + target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); + target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); + target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); + target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + + return target; } -} + // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal + // target is a Vector3 + // https://graphics.stanford.edu/papers/envmap/envmap.pdf + getIrradianceAt( normal, target ) { + + // normal is assumed to be unit length -function createPaths( text, size, data ) { + const x = normal.x, y = normal.y, z = normal.z; - const chars = Array.from( text ); - const scale = size / data.resolution; - const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; + const coeff = this.coefficients; - const paths = []; + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 - let offsetX = 0, offsetY = 0; + // band 1 + target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 + target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); + target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); - for ( let i = 0; i < chars.length; i ++ ) { + // band 2 + target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 + target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); + target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 + target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); + target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 - const char = chars[ i ]; + return target; - if ( char === '\n' ) { + } - offsetX = 0; - offsetY -= line_height; + add( sh ) { - } else { + for ( let i = 0; i < 9; i ++ ) { - const ret = createPath( char, scale, offsetX, offsetY, data ); - offsetX += ret.offsetX; - paths.push( ret.path ); + this.coefficients[ i ].add( sh.coefficients[ i ] ); } + return this; + } - return paths; + addScaledSH( sh, s ) { + + for ( let i = 0; i < 9; i ++ ) { -} + this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); -function createPath( char, scale, offsetX, offsetY, data ) { + } + + return this; - const glyph = data.glyphs[ char ] || data.glyphs[ '?' ]; + } - if ( ! glyph ) { + scale( s ) { - console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' ); + for ( let i = 0; i < 9; i ++ ) { - return; + this.coefficients[ i ].multiplyScalar( s ); + + } + + return this; } - const path = new ShapePath(); + lerp( sh, alpha ) { - let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; + for ( let i = 0; i < 9; i ++ ) { - if ( glyph.o ) { + this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); - const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + } - for ( let i = 0, l = outline.length; i < l; ) { + return this; - const action = outline[ i ++ ]; + } - switch ( action ) { + equals( sh ) { - case 'm': // moveTo + for ( let i = 0; i < 9; i ++ ) { - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { - path.moveTo( x, y ); + return false; - break; + } - case 'l': // lineTo + } - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + return true; - path.lineTo( x, y ); + } - break; + copy( sh ) { - case 'q': // quadraticCurveTo + return this.set( sh.coefficients ); - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; + } - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + clone() { - break; + return new this.constructor().copy( this ); - case 'b': // bezierCurveTo + } - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; - cpx2 = outline[ i ++ ] * scale + offsetX; - cpy2 = outline[ i ++ ] * scale + offsetY; + fromArray( array, offset = 0 ) { - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + const coefficients = this.coefficients; - break; + for ( let i = 0; i < 9; i ++ ) { - } + coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); } + return this; + } - return { offsetX: glyph.ha * scale, path: path }; + toArray( array = [], offset = 0 ) { -} + const coefficients = this.coefficients; -Font.prototype.isFont = true; + for ( let i = 0; i < 9; i ++ ) { -class FontLoader extends Loader { + coefficients[ i ].toArray( array, offset + ( i * 3 ) ); - constructor( manager ) { + } - super( manager ); + return array; } - load( url, onLoad, onProgress, onError ) { + // evaluate the basis functions + // shBasis is an Array[ 9 ] + static getBasisAt( normal, shBasis ) { - const scope = this; + // normal is assumed to be unit length - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { + const x = normal.x, y = normal.y, z = normal.z; - let json; + // band 0 + shBasis[ 0 ] = 0.282095; - try { + // band 1 + shBasis[ 1 ] = 0.488603 * y; + shBasis[ 2 ] = 0.488603 * z; + shBasis[ 3 ] = 0.488603 * x; - json = JSON.parse( text ); + // band 2 + shBasis[ 4 ] = 1.092548 * x * y; + shBasis[ 5 ] = 1.092548 * y * z; + shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); + shBasis[ 7 ] = 1.092548 * x * z; + shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); - } catch ( e ) { + } - console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); - json = JSON.parse( text.substring( 65, text.length - 2 ) ); +} - } +class LightProbe extends Light { - const font = scope.parse( json ); + constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { - if ( onLoad ) onLoad( font ); + super( undefined, intensity ); - }, onProgress, onError ); + this.isLightProbe = true; - } + this.sh = sh; - parse( json ) { + } - return new Font( json ); + copy( source ) { - } + super.copy( source ); -} + this.sh.copy( source.sh ); -let _context; + return this; -const AudioContext = { + } - getContext: function () { + fromJSON( json ) { - if ( _context === undefined ) { + this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); + this.sh.fromArray( json.sh ); - _context = new ( window.AudioContext || window.webkitAudioContext )(); + return this; - } + } - return _context; + toJSON( meta ) { - }, + const data = super.toJSON( meta ); - setContext: function ( value ) { + data.object.sh = this.sh.toArray(); - _context = value; + return data; } -}; +} -class AudioLoader extends Loader { +class MaterialLoader extends Loader { constructor( manager ) { super( manager ); + this.textures = {}; } @@ -40252,25 +41362,15 @@ class AudioLoader extends Loader { const scope = this; - const loader = new FileLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( buffer ) { + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { try { - // Create a copy of the buffer. The `decodeAudioData` method - // detaches the buffer when complete, preventing reuse. - const bufferCopy = buffer.slice( 0 ); - - const context = AudioContext.getContext(); - context.decodeAudioData( bufferCopy, function ( audioBuffer ) { - - onLoad( audioBuffer ); - - } ); + onLoad( scope.parse( JSON.parse( text ) ) ); } catch ( e ) { @@ -40292,2352 +41392,2300 @@ class AudioLoader extends Loader { } -} + parse( json ) { -class HemisphereLightProbe extends LightProbe { + const textures = this.textures; - constructor( skyColor, groundColor, intensity = 1 ) { + function getTexture( name ) { - super( undefined, intensity ); + if ( textures[ name ] === undefined ) { - const color1 = new Color().set( skyColor ); - const color2 = new Color().set( groundColor ); + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - const sky = new Vector3( color1.r, color1.g, color1.b ); - const ground = new Vector3( color2.r, color2.g, color2.b ); + } - // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); - const c0 = Math.sqrt( Math.PI ); - const c1 = c0 * Math.sqrt( 0.75 ); + return textures[ name ]; - this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); - this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); + } - } + const material = MaterialLoader.createMaterialFromType( json.type ); -} + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined && material.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.sheen !== undefined ) material.sheen = json.sheen; + if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor ); + if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness; + if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity; + if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; + if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.iridescence !== undefined ) material.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if ( json.transmission !== undefined ) material.transmission = json.transmission; + if ( json.thickness !== undefined ) material.thickness = json.thickness; + if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance; + if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor ); + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.combine !== undefined ) material.combine = json.combine; + if ( json.side !== undefined ) material.side = json.side; + if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide; + 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; -HemisphereLightProbe.prototype.isHemisphereLightProbe = true; + if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; + if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; + if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; + if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; + if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; + if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; + if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; + if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; -class AmbientLightProbe extends LightProbe { + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; - constructor( color, intensity = 1 ) { + if ( json.rotation !== undefined ) material.rotation = json.rotation; - super( undefined, intensity ); + if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; + if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; + if ( json.scale !== undefined ) material.scale = json.scale; - const color1 = new Color().set( color ); + if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; - // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); - this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); + if ( json.dithering !== undefined ) material.dithering = json.dithering; - } + if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage; + if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha; -} + if ( json.visible !== undefined ) material.visible = json.visible; -AmbientLightProbe.prototype.isAmbientLightProbe = true; + if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; -const _eyeRight = new Matrix4(); -const _eyeLeft = new Matrix4(); + if ( json.userData !== undefined ) material.userData = json.userData; -class StereoCamera { + if ( json.vertexColors !== undefined ) { - constructor() { + if ( typeof json.vertexColors === 'number' ) { - this.type = 'StereoCamera'; + material.vertexColors = ( json.vertexColors > 0 ) ? true : false; - this.aspect = 1; + } else { - this.eyeSep = 0.064; + material.vertexColors = json.vertexColors; - this.cameraL = new PerspectiveCamera(); - this.cameraL.layers.enable( 1 ); - this.cameraL.matrixAutoUpdate = false; + } - this.cameraR = new PerspectiveCamera(); - this.cameraR.layers.enable( 2 ); - this.cameraR.matrixAutoUpdate = false; + } - this._cache = { - focus: null, - fov: null, - aspect: null, - near: null, - far: null, - zoom: null, - eyeSep: null - }; + // Shader Material - } + if ( json.uniforms !== undefined ) { - update( camera ) { + for ( const name in json.uniforms ) { - const cache = this._cache; + const uniform = json.uniforms[ name ]; - const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || - cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || - cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + material.uniforms[ name ] = {}; - if ( needsUpdate ) { + switch ( uniform.type ) { - cache.focus = camera.focus; - cache.fov = camera.fov; - cache.aspect = camera.aspect * this.aspect; - cache.near = camera.near; - cache.far = camera.far; - cache.zoom = camera.zoom; - cache.eyeSep = this.eyeSep; + case 't': + material.uniforms[ name ].value = getTexture( uniform.value ); + break; - // Off-axis stereoscopic effect based on - // http://paulbourke.net/stereographics/stereorender/ + case 'c': + material.uniforms[ name ].value = new Color().setHex( uniform.value ); + break; - const projectionMatrix = camera.projectionMatrix.clone(); - const eyeSepHalf = cache.eyeSep / 2; - const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; - const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; - let xmin, xmax; + case 'v2': + material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); + break; - // translate xOffset + case 'v3': + material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); + break; - _eyeLeft.elements[ 12 ] = - eyeSepHalf; - _eyeRight.elements[ 12 ] = eyeSepHalf; + case 'v4': + material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); + break; - // for left eye + case 'm3': + material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); + break; - xmin = - ymax * cache.aspect + eyeSepOnProjection; - xmax = ymax * cache.aspect + eyeSepOnProjection; + case 'm4': + material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); + break; - projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + default: + material.uniforms[ name ].value = uniform.value; - this.cameraL.projectionMatrix.copy( projectionMatrix ); + } - // for right eye + } - xmin = - ymax * cache.aspect - eyeSepOnProjection; - xmax = ymax * cache.aspect - eyeSepOnProjection; + } - projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + if ( json.defines !== undefined ) material.defines = json.defines; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion; - this.cameraR.projectionMatrix.copy( projectionMatrix ); + if ( json.extensions !== undefined ) { - } + for ( const key in json.extensions ) { - this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); - this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); + material.extensions[ key ] = json.extensions[ key ]; - } + } -} + } -class Clock { + // for PointsMaterial - constructor( autoStart ) { + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + // maps - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + if ( json.map !== undefined ) material.map = getTexture( json.map ); + if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); - this.running = false; + if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); - } + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - start() { + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; + if ( json.normalScale !== undefined ) { - this.startTime = now(); + let normalScale = json.normalScale; - this.oldTime = this.startTime; - this.elapsedTime = 0; - this.running = true; + if ( Array.isArray( normalScale ) === false ) { - } + // Blender exporter used to export a scalar. See #7459 - stop() { + normalScale = [ normalScale, normalScale ]; - this.getElapsedTime(); - this.running = false; - this.autoStart = false; + } - } + material.normalScale = new Vector2().fromArray( normalScale ); - getElapsedTime() { + } - this.getDelta(); - return this.elapsedTime; + if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); + if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; - } + if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); - getDelta() { + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - let diff = 0; + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap ); + if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); - if ( this.autoStart && ! this.running ) { + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; - this.start(); - return 0; + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; - } + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; - if ( this.running ) { + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - const newTime = now(); + if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; + if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); + if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); + if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); + if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); - this.elapsedTime += diff; + if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap ); + if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap ); - } + if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); + if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap ); - return diff; + if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap ); + if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap ); + + return material; } -} + setTextures( value ) { -function now() { + this.textures = value; + return this; - return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 + } -} + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; -const _position$2 = /*@__PURE__*/ new Vector3(); -const _quaternion$3 = /*@__PURE__*/ new Quaternion(); -const _scale$1 = /*@__PURE__*/ new Vector3(); -const _orientation = /*@__PURE__*/ new Vector3(); + return new materialLib[ type ](); -class AudioListener extends Object3D { + } - constructor() { +} - super(); +class LoaderUtils { - this.type = 'AudioListener'; + static decodeText( array ) { - this.context = AudioContext.getContext(); + if ( typeof TextDecoder !== 'undefined' ) { - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + return new TextDecoder().decode( array ); - this.filter = null; + } - this.timeDelta = 0; + // Avoid the String.fromCharCode.apply(null, array) shortcut, which + // throws a "maximum call stack size exceeded" error for large arrays. - // private + let s = ''; - this._clock = new Clock(); + for ( let i = 0, il = array.length; i < il; i ++ ) { - } + // Implicitly assumes little-endian. + s += String.fromCharCode( array[ i ] ); - getInput() { + } - return this.gain; + try { - } + // merges multi-byte utf-8 characters. - removeFilter() { + return decodeURIComponent( escape( s ) ); - if ( this.filter !== null ) { + } catch ( e ) { // see #16358 - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); - this.gain.connect( this.context.destination ); - this.filter = null; + return s; } - return this; - } - getFilter() { + static extractUrlBase( url ) { - return this.filter; + const index = url.lastIndexOf( '/' ); - } + if ( index === - 1 ) return './'; - setFilter( value ) { + return url.slice( 0, index + 1 ); - if ( this.filter !== null ) { + } - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); + static resolveURL( url, path ) { - } else { + // Invalid URL + if ( typeof url !== 'string' || url === '' ) return ''; - this.gain.disconnect( this.context.destination ); + // Host Relative URL + if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { + + path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); } - this.filter = value; - this.gain.connect( this.filter ); - this.filter.connect( this.context.destination ); + // Absolute URL http://,https://,// + if ( /^(https?:)?\/\//i.test( url ) ) return url; - return this; + // Data URI + if ( /^data:.*,.*$/i.test( url ) ) return url; + + // Blob URL + if ( /^blob:.*$/i.test( url ) ) return url; + + // Relative URL + return path + url; } - getMasterVolume() { +} - return this.gain.gain.value; +class InstancedBufferGeometry extends BufferGeometry { - } + constructor() { - setMasterVolume( value ) { + super(); - this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + this.isInstancedBufferGeometry = true; - return this; + this.type = 'InstancedBufferGeometry'; + this.instanceCount = Infinity; } - updateMatrixWorld( force ) { + copy( source ) { - super.updateMatrixWorld( force ); + super.copy( source ); - const listener = this.context.listener; - const up = this.up; + this.instanceCount = source.instanceCount; - this.timeDelta = this._clock.getDelta(); + return this; - this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 ); + } - _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 ); + clone() { - if ( listener.positionX ) { + return new this.constructor().copy( this ); - // code path for Chrome (see #14393) + } - const endTime = this.context.currentTime + this.timeDelta; + toJSON() { - listener.positionX.linearRampToValueAtTime( _position$2.x, endTime ); - listener.positionY.linearRampToValueAtTime( _position$2.y, endTime ); - listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime ); - listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime ); - listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime ); - listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime ); - listener.upX.linearRampToValueAtTime( up.x, endTime ); - listener.upY.linearRampToValueAtTime( up.y, endTime ); - listener.upZ.linearRampToValueAtTime( up.z, endTime ); + const data = super.toJSON( this ); - } else { + data.instanceCount = this.instanceCount; - listener.setPosition( _position$2.x, _position$2.y, _position$2.z ); - listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z ); + data.isInstancedBufferGeometry = true; - } + return data; } } -class Audio extends Object3D { - - constructor( listener ) { - - super(); - - this.type = 'Audio'; +class BufferGeometryLoader extends Loader { - this.listener = listener; - this.context = listener.context; + constructor( manager ) { - this.gain = this.context.createGain(); - this.gain.connect( listener.getInput() ); + super( manager ); - this.autoplay = false; + } - this.buffer = null; - this.detune = 0; - this.loop = false; - this.loopStart = 0; - this.loopEnd = 0; - this.offset = 0; - this.duration = undefined; - this.playbackRate = 1; - this.isPlaying = false; - this.hasPlaybackControl = true; - this.source = null; - this.sourceType = 'empty'; + load( url, onLoad, onProgress, onError ) { - this._startedAt = 0; - this._progress = 0; - this._connected = false; + const scope = this; - this.filters = []; + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { - } + try { - getOutput() { + onLoad( scope.parse( JSON.parse( text ) ) ); - return this.gain; + } catch ( e ) { - } + if ( onError ) { - setNodeSource( audioNode ) { + onError( e ); - this.hasPlaybackControl = false; - this.sourceType = 'audioNode'; - this.source = audioNode; - this.connect(); + } else { - return this; + console.error( e ); - } + } - setMediaElementSource( mediaElement ) { + scope.manager.itemError( url ); - this.hasPlaybackControl = false; - this.sourceType = 'mediaNode'; - this.source = this.context.createMediaElementSource( mediaElement ); - this.connect(); + } - return this; + }, onProgress, onError ); } - setMediaStreamSource( mediaStream ) { + parse( json ) { - this.hasPlaybackControl = false; - this.sourceType = 'mediaStreamNode'; - this.source = this.context.createMediaStreamSource( mediaStream ); - this.connect(); + const interleavedBufferMap = {}; + const arrayBufferMap = {}; - return this; + function getInterleavedBuffer( json, uuid ) { - } + if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; - setBuffer( audioBuffer ) { + const interleavedBuffers = json.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[ uuid ]; - this.buffer = audioBuffer; - this.sourceType = 'buffer'; + const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); - if ( this.autoplay ) this.play(); + const array = getTypedArray( interleavedBuffer.type, buffer ); + const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); + ib.uuid = interleavedBuffer.uuid; - return this; + interleavedBufferMap[ uuid ] = ib; - } + return ib; - play( delay = 0 ) { + } - if ( this.isPlaying === true ) { + function getArrayBuffer( json, uuid ) { - console.warn( 'THREE.Audio: Audio is already playing.' ); - return; + if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; - } + const arrayBuffers = json.arrayBuffers; + const arrayBuffer = arrayBuffers[ uuid ]; - if ( this.hasPlaybackControl === false ) { + const ab = new Uint32Array( arrayBuffer ).buffer; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + arrayBufferMap[ uuid ] = ab; - } + return ab; - this._startedAt = this.context.currentTime + delay; + } - const source = this.context.createBufferSource(); - source.buffer = this.buffer; - source.loop = this.loop; - source.loopStart = this.loopStart; - source.loopEnd = this.loopEnd; - source.onended = this.onEnded.bind( this ); - source.start( this._startedAt, this._progress + this.offset, this.duration ); + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); - this.isPlaying = true; + const index = json.data.index; - this.source = source; + if ( index !== undefined ) { - this.setDetune( this.detune ); - this.setPlaybackRate( this.playbackRate ); + const typedArray = getTypedArray( index.type, index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); - return this.connect(); + } - } + const attributes = json.data.attributes; - pause() { + for ( const key in attributes ) { - if ( this.hasPlaybackControl === false ) { + const attribute = attributes[ key ]; + let bufferAttribute; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + if ( attribute.isInterleavedBufferAttribute ) { - } + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); - if ( this.isPlaying === true ) { + } else { - // update current progress + const typedArray = getTypedArray( attribute.type, attribute.array ); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); - this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; + } - if ( this.loop === true ) { + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage ); - // ensure _progress does not exceed duration with looped audios + if ( attribute.updateRange !== undefined ) { - this._progress = this._progress % ( this.duration || this.buffer.duration ); + bufferAttribute.updateRange.offset = attribute.updateRange.offset; + bufferAttribute.updateRange.count = attribute.updateRange.count; } - this.source.stop(); - this.source.onended = null; - - this.isPlaying = false; + geometry.setAttribute( key, bufferAttribute ); } - return this; + const morphAttributes = json.data.morphAttributes; - } + if ( morphAttributes ) { - stop() { + for ( const key in morphAttributes ) { - if ( this.hasPlaybackControl === false ) { + const attributeArray = morphAttributes[ key ]; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + const array = []; - } + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { - this._progress = 0; + const attribute = attributeArray[ i ]; + let bufferAttribute; - this.source.stop(); - this.source.onended = null; - this.isPlaying = false; + if ( attribute.isInterleavedBufferAttribute ) { - return this; + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); - } + } else { - connect() { + const typedArray = getTypedArray( attribute.type, attribute.array ); + bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); - if ( this.filters.length > 0 ) { + } - this.source.connect( this.filters[ 0 ] ); + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + array.push( bufferAttribute ); - for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + } - this.filters[ i - 1 ].connect( this.filters[ i ] ); + geometry.morphAttributes[ key ] = array; } - this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + } - } else { + const morphTargetsRelative = json.data.morphTargetsRelative; - this.source.connect( this.getOutput() ); + if ( morphTargetsRelative ) { - } + geometry.morphTargetsRelative = true; - this._connected = true; + } - return this; + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; - } + if ( groups !== undefined ) { - disconnect() { + for ( let i = 0, n = groups.length; i !== n; ++ i ) { - if ( this.filters.length > 0 ) { + const group = groups[ i ]; - this.source.disconnect( this.filters[ 0 ] ); + geometry.addGroup( group.start, group.count, group.materialIndex ); - for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + } - this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + } - } + const boundingSphere = json.data.boundingSphere; - this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + if ( boundingSphere !== undefined ) { - } else { + const center = new Vector3(); - this.source.disconnect( this.getOutput() ); + if ( boundingSphere.center !== undefined ) { - } + center.fromArray( boundingSphere.center ); - this._connected = false; + } - return this; + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - } + } - getFilters() { + if ( json.name ) geometry.name = json.name; + if ( json.userData ) geometry.userData = json.userData; - return this.filters; + return geometry; } - setFilters( value ) { +} - if ( ! value ) value = []; +class ObjectLoader extends Loader { - if ( this._connected === true ) { + constructor( manager ) { - this.disconnect(); - this.filters = value.slice(); - this.connect(); + super( manager ); - } else { + } - this.filters = value.slice(); + load( url, onLoad, onProgress, onError ) { - } + const scope = this; - return this; + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; - } + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - setDetune( value ) { + let json = null; - this.detune = value; + try { - if ( this.source.detune === undefined ) return; // only set detune when available + json = JSON.parse( text ); - if ( this.isPlaying === true ) { + } catch ( error ) { - this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); + if ( onError !== undefined ) onError( error ); - } + console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); - return this; + return; - } + } - getDetune() { + const metadata = json.metadata; - return this.detune; + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { - } + console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); + return; - getFilter() { + } - return this.getFilters()[ 0 ]; + scope.parse( json, onLoad ); - } + }, onProgress, onError ); - setFilter( filter ) { + } - return this.setFilters( filter ? [ filter ] : [] ); + async loadAsync( url, onProgress ) { - } + const scope = this; - setPlaybackRate( value ) { + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; - if ( this.hasPlaybackControl === false ) { + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + const text = await loader.loadAsync( url, onProgress ); - } + const json = JSON.parse( text ); - this.playbackRate = value; + const metadata = json.metadata; - if ( this.isPlaying === true ) { + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { - this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url ); } - return this; + return await scope.parseAsync( json ); } - getPlaybackRate() { - - return this.playbackRate; - - } + parse( json, onLoad ) { - onEnded() { + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); - this.isPlaying = false; + const images = this.parseImages( json.images, function () { - } + if ( onLoad !== undefined ) onLoad( object ); - getLoop() { + } ); - if ( this.hasPlaybackControl === false ) { + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return false; + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); - } + this.bindSkeletons( object, skeletons ); - return this.loop; + // - } + if ( onLoad !== undefined ) { - setLoop( value ) { + let hasImages = false; - if ( this.hasPlaybackControl === false ) { + for ( const uuid in images ) { - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + if ( images[ uuid ].data instanceof HTMLImageElement ) { - } + hasImages = true; + break; - this.loop = value; + } - if ( this.isPlaying === true ) { + } - this.source.loop = this.loop; + if ( hasImages === false ) onLoad( object ); } - return this; + return object; } - setLoopStart( value ) { + async parseAsync( json ) { - this.loopStart = value; + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); - return this; + const images = await this.parseImagesAsync( json.images ); - } + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); - setLoopEnd( value ) { + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); - this.loopEnd = value; + this.bindSkeletons( object, skeletons ); - return this; + return object; } - getVolume() { - - return this.gain.gain.value; - - } + parseShapes( json ) { - setVolume( value ) { + const shapes = {}; - this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + if ( json !== undefined ) { - return this; + for ( let i = 0, l = json.length; i < l; i ++ ) { - } + const shape = new Shape().fromJSON( json[ i ] ); -} + shapes[ shape.uuid ] = shape; -const _position$3 = /*@__PURE__*/ new Vector3(); -const _quaternion$4 = /*@__PURE__*/ new Quaternion(); -const _scale$2 = /*@__PURE__*/ new Vector3(); -const _orientation$1 = /*@__PURE__*/ new Vector3(); + } -class PositionalAudio extends Audio { + } - constructor( listener ) { + return shapes; - super( listener ); + } - this.panner = this.context.createPanner(); - this.panner.panningModel = 'HRTF'; - this.panner.connect( this.gain ); + parseSkeletons( json, object ) { - } + const skeletons = {}; + const bones = {}; - getOutput() { + // generate bone lookup table - return this.panner; + object.traverse( function ( child ) { - } + if ( child.isBone ) bones[ child.uuid ] = child; - getRefDistance() { + } ); - return this.panner.refDistance; + // create skeletons - } + if ( json !== undefined ) { - setRefDistance( value ) { + for ( let i = 0, l = json.length; i < l; i ++ ) { - this.panner.refDistance = value; + const skeleton = new Skeleton().fromJSON( json[ i ], bones ); - return this; + skeletons[ skeleton.uuid ] = skeleton; - } + } - getRolloffFactor() { + } - return this.panner.rolloffFactor; + return skeletons; } - setRolloffFactor( value ) { + parseGeometries( json, shapes ) { - this.panner.rolloffFactor = value; + const geometries = {}; - return this; + if ( json !== undefined ) { - } + const bufferGeometryLoader = new BufferGeometryLoader(); - getDistanceModel() { + for ( let i = 0, l = json.length; i < l; i ++ ) { - return this.panner.distanceModel; + let geometry; + const data = json[ i ]; - } + switch ( data.type ) { - setDistanceModel( value ) { + case 'BufferGeometry': + case 'InstancedBufferGeometry': - this.panner.distanceModel = value; + geometry = bufferGeometryLoader.parse( data ); + break; - return this; + default: - } + if ( data.type in Geometries ) { - getMaxDistance() { + geometry = Geometries[ data.type ].fromJSON( data, shapes ); - return this.panner.maxDistance; + } else { - } + console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` ); - setMaxDistance( value ) { + } - this.panner.maxDistance = value; + } - return this; + geometry.uuid = data.uuid; - } + if ( data.name !== undefined ) geometry.name = data.name; + if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; - setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { + geometries[ data.uuid ] = geometry; - this.panner.coneInnerAngle = coneInnerAngle; - this.panner.coneOuterAngle = coneOuterAngle; - this.panner.coneOuterGain = coneOuterGain; + } - return this; + } - } + return geometries; - updateMatrixWorld( force ) { + } - super.updateMatrixWorld( force ); + parseMaterials( json, textures ) { - if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; + const cache = {}; // MultiMaterial + const materials = {}; - this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 ); + if ( json !== undefined ) { - _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 ); + const loader = new MaterialLoader(); + loader.setTextures( textures ); - const panner = this.panner; + for ( let i = 0, l = json.length; i < l; i ++ ) { - if ( panner.positionX ) { + const data = json[ i ]; - // code path for Chrome and Firefox (see #14393) + if ( cache[ data.uuid ] === undefined ) { - const endTime = this.context.currentTime + this.listener.timeDelta; + cache[ data.uuid ] = loader.parse( data ); - panner.positionX.linearRampToValueAtTime( _position$3.x, endTime ); - panner.positionY.linearRampToValueAtTime( _position$3.y, endTime ); - panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime ); - panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime ); - panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime ); - panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + } - } else { + materials[ data.uuid ] = cache[ data.uuid ]; - panner.setPosition( _position$3.x, _position$3.y, _position$3.z ); - panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z ); + } } - } + return materials; -} + } -class AudioAnalyser { + parseAnimations( json ) { - constructor( audio, fftSize = 2048 ) { + const animations = {}; - this.analyser = audio.context.createAnalyser(); - this.analyser.fftSize = fftSize; + if ( json !== undefined ) { - this.data = new Uint8Array( this.analyser.frequencyBinCount ); + for ( let i = 0; i < json.length; i ++ ) { - audio.getOutput().connect( this.analyser ); + const data = json[ i ]; - } + const clip = AnimationClip.parse( data ); + animations[ clip.uuid ] = clip; - getFrequencyData() { + } - this.analyser.getByteFrequencyData( this.data ); + } - return this.data; + return animations; } - getAverageFrequency() { + parseImages( json, onLoad ) { - let value = 0; - const data = this.getFrequencyData(); + const scope = this; + const images = {}; - for ( let i = 0; i < data.length; i ++ ) { + let loader; - value += data[ i ]; + function loadImage( url ) { - } + scope.manager.itemStart( url ); - return value / data.length; + return loader.load( url, function () { - } + scope.manager.itemEnd( url ); -} + }, undefined, function () { -class PropertyMixer { + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - constructor( binding, typeName, valueSize ) { + } ); - this.binding = binding; - this.valueSize = valueSize; + } - let mixFunction, - mixFunctionAdditive, - setIdentity; + function deserializeImage( image ) { + + if ( typeof image === 'string' ) { - // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] - // - // 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 - // - // 'add' is used for additive cumulative results - // - // 'work' is optional and is only present for quaternion types. It is used - // to store intermediate quaternion multiplication results + const url = image; - switch ( typeName ) { + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; - case 'quaternion': - mixFunction = this._slerp; - mixFunctionAdditive = this._slerpAdditive; - setIdentity = this._setAdditiveIdentityQuaternion; + return loadImage( path ); - this.buffer = new Float64Array( valueSize * 6 ); - this._workIndex = 5; - break; + } else { - case 'string': - case 'bool': - mixFunction = this._select; + if ( image.data ) { - // Use the regular mix function and for additive on these types, - // additive is not relevant for non-numeric types - mixFunctionAdditive = this._select; + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; - setIdentity = this._setAdditiveIdentityOther; + } else { - this.buffer = new Array( valueSize * 5 ); - break; + return null; - default: - mixFunction = this._lerp; - mixFunctionAdditive = this._lerpAdditive; - setIdentity = this._setAdditiveIdentityNumeric; + } - this.buffer = new Float64Array( valueSize * 5 ); + } } - this._mixBufferRegion = mixFunction; - this._mixBufferRegionAdditive = mixFunctionAdditive; - this._setIdentity = setIdentity; - this._origIndex = 3; - this._addIndex = 4; + if ( json !== undefined && json.length > 0 ) { - this.cumulativeWeight = 0; - this.cumulativeWeightAdditive = 0; + const manager = new LoadingManager( onLoad ); - this.useCount = 0; - this.referenceCount = 0; + loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - } + for ( let i = 0, il = json.length; i < il; i ++ ) { - // accumulate data in the 'incoming' region into 'accu' - accumulate( accuIndex, weight ) { + const image = json[ i ]; + const url = image.url; - // note: happily accumulating nothing when weight = 0, the caller knows - // the weight and shouldn't have made the call in the first place + if ( Array.isArray( url ) ) { - const buffer = this.buffer, - stride = this.valueSize, - offset = accuIndex * stride + stride; + // load array of images e.g CubeTexture - let currentWeight = this.cumulativeWeight; + const imageArray = []; - if ( currentWeight === 0 ) { + for ( let j = 0, jl = url.length; j < jl; j ++ ) { - // accuN := incoming * weight + const currentUrl = url[ j ]; - for ( let i = 0; i !== stride; ++ i ) { + const deserializedImage = deserializeImage( currentUrl ); - buffer[ offset + i ] = buffer[ i ]; + if ( deserializedImage !== null ) { - } + if ( deserializedImage instanceof HTMLImageElement ) { - currentWeight = weight; + imageArray.push( deserializedImage ); - } else { + } else { - // accuN := accuN + incoming * weight + // special case: handle array of data textures for cube textures - currentWeight += weight; - const mix = weight / currentWeight; - this._mixBufferRegion( buffer, offset, 0, mix, stride ); + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); - } + } - this.cumulativeWeight = currentWeight; + } - } + } - // accumulate data in the 'incoming' region into 'add' - accumulateAdditive( weight ) { + images[ image.uuid ] = new Source( imageArray ); - const buffer = this.buffer, - stride = this.valueSize, - offset = stride * this._addIndex; + } else { - if ( this.cumulativeWeightAdditive === 0 ) { + // load single image - // add = identity + const deserializedImage = deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); - this._setIdentity(); - } + } - // add := add + incoming * weight + } - this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); - this.cumulativeWeightAdditive += weight; + } + + return images; } - // apply the state of 'accu' to the binding when accus differ - apply( accuIndex ) { + async parseImagesAsync( json ) { - const stride = this.valueSize, - buffer = this.buffer, - offset = accuIndex * stride + stride, + const scope = this; + const images = {}; - weight = this.cumulativeWeight, - weightAdditive = this.cumulativeWeightAdditive, + let loader; - binding = this.binding; + async function deserializeImage( image ) { - this.cumulativeWeight = 0; - this.cumulativeWeightAdditive = 0; + if ( typeof image === 'string' ) { - if ( weight < 1 ) { + const url = image; - // accuN := accuN + original * ( 1 - cumulativeWeight ) + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; - const originalValueOffset = stride * this._origIndex; + return await loader.loadAsync( path ); - this._mixBufferRegion( - buffer, offset, originalValueOffset, 1 - weight, stride ); + } else { - } + if ( image.data ) { - if ( weightAdditive > 0 ) { + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; - // accuN := accuN + additive accuN + } else { - this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); + return null; - } + } - for ( let i = stride, e = stride + stride; i !== e; ++ i ) { + } - if ( buffer[ i ] !== buffer[ i + stride ] ) { + } - // value has changed -> update scene graph + if ( json !== undefined && json.length > 0 ) { - binding.setValue( buffer, offset ); - break; + loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); - } + for ( let i = 0, il = json.length; i < il; i ++ ) { - } + const image = json[ i ]; + const url = image.url; - } + if ( Array.isArray( url ) ) { - // remember the state of the bound property and copy it to both accus - saveOriginalState() { + // load array of images e.g CubeTexture - const binding = this.binding; + const imageArray = []; - const buffer = this.buffer, - stride = this.valueSize, + for ( let j = 0, jl = url.length; j < jl; j ++ ) { - originalValueOffset = stride * this._origIndex; + const currentUrl = url[ j ]; - binding.getValue( buffer, originalValueOffset ); + const deserializedImage = await deserializeImage( currentUrl ); - // accu[0..1] := orig -- initially detect changes against the original - for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { + if ( deserializedImage !== null ) { - buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + if ( deserializedImage instanceof HTMLImageElement ) { - } + imageArray.push( deserializedImage ); - // Add to identity for additive - this._setIdentity(); + } else { - this.cumulativeWeight = 0; - this.cumulativeWeightAdditive = 0; + // special case: handle array of data textures for cube textures - } + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); - // apply the state previously taken via 'saveOriginalState' to the binding - restoreOriginalState() { + } - const originalValueOffset = this.valueSize * 3; - this.binding.setValue( this.buffer, originalValueOffset ); + } - } + } - _setAdditiveIdentityNumeric() { + images[ image.uuid ] = new Source( imageArray ); - const startIndex = this._addIndex * this.valueSize; - const endIndex = startIndex + this.valueSize; + } else { - for ( let i = startIndex; i < endIndex; i ++ ) { + // load single image - this.buffer[ i ] = 0; + const deserializedImage = await deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); - } + } - } + } - _setAdditiveIdentityQuaternion() { + } - this._setAdditiveIdentityNumeric(); - this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; + return images; } - _setAdditiveIdentityOther() { + parseTextures( json, images ) { - const startIndex = this._origIndex * this.valueSize; - const targetIndex = this._addIndex * this.valueSize; + function parseConstant( value, type ) { - for ( let i = 0; i < this.valueSize; i ++ ) { + if ( typeof value === 'number' ) return value; - this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + + return type[ value ]; } - } + const textures = {}; + if ( json !== undefined ) { - // mix functions + for ( let i = 0, l = json.length; i < l; i ++ ) { - _select( buffer, dstOffset, srcOffset, t, stride ) { + const data = json[ i ]; - if ( t >= 0.5 ) { + if ( data.image === undefined ) { - for ( let i = 0; i !== stride; ++ i ) { + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); - buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + } - } + if ( images[ data.image ] === undefined ) { - } + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); - } + } - _slerp( buffer, dstOffset, srcOffset, t ) { + const source = images[ data.image ]; + const image = source.data; - Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); + let texture; - } + if ( Array.isArray( image ) ) { - _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + texture = new CubeTexture(); - const workOffset = this._workIndex * stride; + if ( image.length === 6 ) texture.needsUpdate = true; - // Store result in intermediate buffer offset - Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); + } else { - // Slerp to the intermediate result - Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); + if ( image && image.data ) { - } + texture = new DataTexture(); - _lerp( buffer, dstOffset, srcOffset, t, stride ) { + } else { - const s = 1 - t; + texture = new Texture(); - for ( let i = 0; i !== stride; ++ i ) { + } - const j = dstOffset + i; + if ( image ) texture.needsUpdate = true; // textures can have undefined image data - buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + } - } + texture.source = source; - } + texture.uuid = data.uuid; - _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + if ( data.name !== undefined ) texture.name = data.name; - for ( let i = 0; i !== stride; ++ i ) { + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); - const j = dstOffset + i; + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.center !== undefined ) texture.center.fromArray( data.center ); + if ( data.rotation !== undefined ) texture.rotation = data.rotation; - buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; + if ( data.wrap !== undefined ) { - } + texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); + texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); - } + } -} + if ( data.format !== undefined ) texture.format = data.format; + if ( data.type !== undefined ) texture.type = data.type; + if ( data.encoding !== undefined ) texture.encoding = data.encoding; -// Characters [].:/ are reserved for track binding syntax. -const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; -const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; -// Attempts to allow node names from any language. ES5's `\w` regexp matches -// only latin characters, and the unicode \p{L} is not yet supported. So -// instead, we exclude reserved characters and match everything else. -const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; -const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; + if ( data.flipY !== undefined ) texture.flipY = data.flipY; -// Parent directories, delimited by '/' or ':'. Currently unused, but must -// be matched to parse the rest of the track name. -const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); + if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; + if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; -// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. -const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); + if ( data.userData !== undefined ) texture.userData = data.userData; -// Object on target node, and accessor. May not contain reserved -// characters. Accessor may contain any character except closing bracket. -const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); + textures[ data.uuid ] = texture; -// Property and accessor. May not contain reserved characters. Accessor may -// contain any non-bracket characters. -const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); + } -const _trackRe = new RegExp( '' - + '^' - + _directoryRe - + _nodeRe - + _objectRe - + _propertyRe - + '$' -); + } -const _supportedObjectNames = [ 'material', 'materials', 'bones' ]; + return textures; -function Composite( targetGroup, path, optionalParsedPath ) { + } - const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); + parseObject( data, geometries, materials, textures, animations ) { - this._targetGroup = targetGroup; - this._bindings = targetGroup.subscribe_( path, parsedPath ); + let object; -} + function getGeometry( name ) { -Object.assign( Composite.prototype, { + if ( geometries[ name ] === undefined ) { - getValue: function ( array, offset ) { + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); - this.bind(); // bind all binding + } - const firstValidIndex = this._targetGroup.nCachedObjects_, - binding = this._bindings[ firstValidIndex ]; + return geometries[ name ]; - // and only call .getValue on the first - if ( binding !== undefined ) binding.getValue( array, offset ); + } - }, + function getMaterial( name ) { - setValue: function ( array, offset ) { + if ( name === undefined ) return undefined; - const bindings = this._bindings; + if ( Array.isArray( name ) ) { - for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + const array = []; - bindings[ i ].setValue( array, offset ); + for ( let i = 0, l = name.length; i < l; i ++ ) { - } + const uuid = name[ i ]; - }, + if ( materials[ uuid ] === undefined ) { - bind: function () { + console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); - const bindings = this._bindings; + } - for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + array.push( materials[ uuid ] ); - bindings[ i ].bind(); + } - } + return array; - }, + } - unbind: function () { + if ( materials[ name ] === undefined ) { - const bindings = this._bindings; + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + } - bindings[ i ].unbind(); + return materials[ name ]; } - } + function getTexture( uuid ) { + + if ( textures[ uuid ] === undefined ) { -} ); + console.warn( 'THREE.ObjectLoader: Undefined texture', uuid ); + } -function PropertyBinding( rootNode, path, parsedPath ) { + return textures[ uuid ]; - this.path = path; - this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); + } - this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; + let geometry, material; - this.rootNode = rootNode; + switch ( data.type ) { -} + case 'Scene': -Object.assign( PropertyBinding, { + object = new Scene(); - Composite: Composite, + if ( data.background !== undefined ) { - create: function ( root, path, parsedPath ) { + if ( Number.isInteger( data.background ) ) { - if ( ! ( root && root.isAnimationObjectGroup ) ) { + object.background = new Color( data.background ); - return new PropertyBinding( root, path, parsedPath ); + } else { - } else { + object.background = getTexture( data.background ); - return new PropertyBinding.Composite( root, path, parsedPath ); + } - } + } - }, + if ( data.environment !== undefined ) { - /** - * Replaces spaces with underscores and removes unsupported characters from - * node names, to ensure compatibility with parseTrackName(). - * - * @param {string} name Node name to be sanitized. - * @return {string} - */ - sanitizeNodeName: function ( name ) { + object.environment = getTexture( data.environment ); - return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); + } - }, + if ( data.fog !== undefined ) { - parseTrackName: function ( trackName ) { + if ( data.fog.type === 'Fog' ) { - const matches = _trackRe.exec( trackName ); + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); - if ( ! matches ) { + } else if ( data.fog.type === 'FogExp2' ) { - throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); + object.fog = new FogExp2( data.fog.color, data.fog.density ); - } + } - const results = { - // directoryName: matches[ 1 ], // (tschw) currently unused - nodeName: matches[ 2 ], - objectName: matches[ 3 ], - objectIndex: matches[ 4 ], - propertyName: matches[ 5 ], // required - propertyIndex: matches[ 6 ] - }; + } - const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + break; - if ( lastDot !== undefined && lastDot !== - 1 ) { + case 'PerspectiveCamera': - const objectName = results.nodeName.substring( lastDot + 1 ); + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - // Object names must be checked against an allowlist. Otherwise, there - // is no way to parse 'foo.bar.baz': 'baz' must be a property, but - // 'bar' could be the objectName, or part of a nodeName (which can - // include '.' characters). - if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { + 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 ); - results.nodeName = results.nodeName.substring( 0, lastDot ); - results.objectName = objectName; + break; - } + case 'OrthographicCamera': - } + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - if ( results.propertyName === null || results.propertyName.length === 0 ) { + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + break; - } + case 'AmbientLight': - return results; + object = new AmbientLight( data.color, data.intensity ); - }, + break; - findNode: function ( root, nodeName ) { + case 'DirectionalLight': - if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { + object = new DirectionalLight( data.color, data.intensity ); - return root; + break; - } + case 'PointLight': - // search into skeleton bones. - if ( root.skeleton ) { + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - const bone = root.skeleton.getBoneByName( nodeName ); + break; - if ( bone !== undefined ) { + case 'RectAreaLight': - return bone; + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); - } + break; - } + case 'SpotLight': - // search into node subtree. - if ( root.children ) { + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - const searchNodeSubtree = function ( children ) { + break; - for ( let i = 0; i < children.length; i ++ ) { + case 'HemisphereLight': - const childNode = children[ i ]; + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + break; - return childNode; + case 'LightProbe': - } + object = new LightProbe().fromJSON( data ); - const result = searchNodeSubtree( childNode.children ); + break; - if ( result ) return result; + case 'SkinnedMesh': - } + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); - return null; + object = new SkinnedMesh( geometry, material ); - }; + if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; + if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); + if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; - const subTreeNode = searchNodeSubtree( root.children ); + break; - if ( subTreeNode ) { + case 'Mesh': - return subTreeNode; + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); - } + object = new Mesh( geometry, material ); - } + break; - return null; + case 'InstancedMesh': - } + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; -} ); + object = new InstancedMesh( geometry, material, count ); + object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize ); -Object.assign( PropertyBinding.prototype, { // prototype, continued + break; - // these are used to "bind" a nonexistent property - _getValue_unavailable: function () {}, - _setValue_unavailable: function () {}, - - BindingType: { - Direct: 0, - EntireArray: 1, - ArrayElement: 2, - HasFromToArray: 3 - }, + case 'LOD': - Versioning: { - None: 0, - NeedsUpdate: 1, - MatrixWorldNeedsUpdate: 2 - }, + object = new LOD(); - GetterByBindingType: [ + break; - function getValue_direct( buffer, offset ) { + case 'Line': - buffer[ offset ] = this.node[ this.propertyName ]; + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); - }, + break; - function getValue_array( buffer, offset ) { + case 'LineLoop': - const source = this.resolvedProperty; + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); - for ( let i = 0, n = source.length; i !== n; ++ i ) { + break; - buffer[ offset ++ ] = source[ i ]; + case 'LineSegments': - } + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); - }, + break; - function getValue_arrayElement( buffer, offset ) { + case 'PointCloud': + case 'Points': - buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - }, + break; - function getValue_toArray( buffer, offset ) { + case 'Sprite': - this.resolvedProperty.toArray( buffer, offset ); + object = new Sprite( getMaterial( data.material ) ); - } + break; - ], + case 'Group': - SetterByBindingTypeAndVersioning: [ + object = new Group(); - [ - // Direct + break; - function setValue_direct( buffer, offset ) { + case 'Bone': - this.targetObject[ this.propertyName ] = buffer[ offset ]; + object = new Bone(); - }, + break; - function setValue_direct_setNeedsUpdate( buffer, offset ) { + default: - this.targetObject[ this.propertyName ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + object = new Object3D(); - }, + } - function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + object.uuid = data.uuid; - this.targetObject[ this.propertyName ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + if ( data.name !== undefined ) object.name = data.name; - } + if ( data.matrix !== undefined ) { - ], [ + object.matrix.fromArray( data.matrix ); - // EntireArray + if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; + if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale ); - function setValue_array( buffer, offset ) { + } else { - const dest = this.resolvedProperty; + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - for ( let i = 0, n = dest.length; i !== n; ++ i ) { + } - dest[ i ] = buffer[ offset ++ ]; + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - } + if ( data.shadow ) { - }, + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); - function setValue_array_setNeedsUpdate( buffer, offset ) { + } - const dest = this.resolvedProperty; + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.userData !== undefined ) object.userData = data.userData; + if ( data.layers !== undefined ) object.layers.mask = data.layers; - for ( let i = 0, n = dest.length; i !== n; ++ i ) { + if ( data.children !== undefined ) { - dest[ i ] = buffer[ offset ++ ]; + const children = data.children; - } + for ( let i = 0; i < children.length; i ++ ) { - this.targetObject.needsUpdate = true; + object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) ); - }, + } - function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + } - const dest = this.resolvedProperty; + if ( data.animations !== undefined ) { - for ( let i = 0, n = dest.length; i !== n; ++ i ) { + const objectAnimations = data.animations; - dest[ i ] = buffer[ offset ++ ]; + for ( let i = 0; i < objectAnimations.length; i ++ ) { - } + const uuid = objectAnimations[ i ]; - this.targetObject.matrixWorldNeedsUpdate = true; + object.animations.push( animations[ uuid ] ); } - ], [ - - // ArrayElement + } - function setValue_arrayElement( buffer, offset ) { + if ( data.type === 'LOD' ) { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; - }, + const levels = data.levels; - function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + for ( let l = 0; l < levels.length; l ++ ) { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + const level = levels[ l ]; + const child = object.getObjectByProperty( 'uuid', level.object ); - }, + if ( child !== undefined ) { - function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + object.addLevel( child, level.distance ); - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + } } - ], [ + } - // HasToFromArray + return object; - function setValue_fromArray( buffer, offset ) { + } - this.resolvedProperty.fromArray( buffer, offset ); + bindSkeletons( object, skeletons ) { - }, + if ( Object.keys( skeletons ).length === 0 ) return; - function setValue_fromArray_setNeedsUpdate( buffer, offset ) { + object.traverse( function ( child ) { - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.needsUpdate = true; + if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { - }, + const skeleton = skeletons[ child.skeleton ]; - function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + if ( skeleton === undefined ) { - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.matrixWorldNeedsUpdate = true; + console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton ); - } + } else { - ] + child.bind( skeleton, child.bindMatrix ); - ], + } - 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. + } - }, +} - setValue: function getValue_unbound( sourceArray, offset ) { +const TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping +}; - this.bind(); - this.setValue( sourceArray, offset ); +const TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping +}; - }, +const TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + LinearFilter: LinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter +}; - // create getter / setter pair for a property in the scene graph - bind: function () { +class ImageBitmapLoader extends Loader { - let targetObject = this.node; - const parsedPath = this.parsedPath; + constructor( manager ) { - const objectName = parsedPath.objectName; - const propertyName = parsedPath.propertyName; - let propertyIndex = parsedPath.propertyIndex; + super( manager ); - if ( ! targetObject ) { + this.isImageBitmapLoader = true; - targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; + if ( typeof createImageBitmap === 'undefined' ) { - this.node = targetObject; + console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); } - // 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 ) { + if ( typeof fetch === 'undefined' ) { - console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); - return; + console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); } - if ( objectName ) { - - let objectIndex = parsedPath.objectIndex; + this.options = { premultiplyAlpha: 'none' }; - // special cases were we need to reach deeper into the hierarchy to get the face materials.... - switch ( objectName ) { + } - case 'materials': + setOptions( options ) { - if ( ! targetObject.material ) { + this.options = options; - console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); - return; + return this; - } + } - if ( ! targetObject.material.materials ) { + load( url, onLoad, onProgress, onError ) { - console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); - return; + if ( url === undefined ) url = ''; - } + if ( this.path !== undefined ) url = this.path + url; - targetObject = targetObject.material.materials; + url = this.manager.resolveURL( url ); - break; + const scope = this; - case 'bones': + const cached = Cache.get( url ); - if ( ! targetObject.skeleton ) { + if ( cached !== undefined ) { - console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); - return; + scope.manager.itemStart( url ); - } + setTimeout( function () { - // potential future optimization: skip this if propertyIndex is already an integer - // and convert the integer string to a true integer. + if ( onLoad ) onLoad( cached ); - targetObject = targetObject.skeleton.bones; + scope.manager.itemEnd( url ); - // support resolving morphTarget names into indices. - for ( let i = 0; i < targetObject.length; i ++ ) { + }, 0 ); - if ( targetObject[ i ].name === objectIndex ) { + return cached; - objectIndex = i; - break; + } - } + const fetchOptions = {}; + fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; + fetchOptions.headers = this.requestHeader; - } + fetch( url, fetchOptions ).then( function ( res ) { - break; + return res.blob(); - default: + } ).then( function ( blob ) { - if ( targetObject[ objectName ] === undefined ) { + return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) ); - console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); - return; + } ).then( function ( imageBitmap ) { - } + Cache.add( url, imageBitmap ); - targetObject = targetObject[ objectName ]; + if ( onLoad ) onLoad( imageBitmap ); - } + scope.manager.itemEnd( url ); + } ).catch( function ( e ) { - if ( objectIndex !== undefined ) { + if ( onError ) onError( e ); - if ( targetObject[ objectIndex ] === undefined ) { + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); - return; + } ); - } + scope.manager.itemStart( url ); - targetObject = targetObject[ objectIndex ]; + } - } +} - } +let _context; - // resolve property - const nodeProperty = targetObject[ propertyName ]; +const AudioContext = { - if ( nodeProperty === undefined ) { + getContext: function () { - const nodeName = parsedPath.nodeName; + if ( _context === undefined ) { - console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + - '.' + propertyName + ' but it wasn\'t found.', targetObject ); - return; + _context = new ( window.AudioContext || window.webkitAudioContext )(); } - // determine versioning scheme - let versioning = this.Versioning.None; - - this.targetObject = targetObject; - - if ( targetObject.needsUpdate !== undefined ) { // material + return _context; - versioning = this.Versioning.NeedsUpdate; + }, - } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + setContext: function ( value ) { - versioning = this.Versioning.MatrixWorldNeedsUpdate; + _context = value; - } + } - // determine how the property gets bound - let bindingType = this.BindingType.Direct; +}; - if ( propertyIndex !== undefined ) { +class AudioLoader extends Loader { - // access a sub element of the property array (only primitives are supported right now) + constructor( manager ) { - if ( propertyName === 'morphTargetInfluences' ) { + super( manager ); - // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + } - // support resolving morphTarget names into indices. - if ( ! targetObject.geometry ) { + load( url, onLoad, onProgress, onError ) { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); - return; + const scope = this; - } + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( buffer ) { - if ( targetObject.geometry.isBufferGeometry ) { + try { - if ( ! targetObject.geometry.morphAttributes ) { + // Create a copy of the buffer. The `decodeAudioData` method + // detaches the buffer when complete, preventing reuse. + const bufferCopy = buffer.slice( 0 ); - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); - return; + const context = AudioContext.getContext(); + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { - } + onLoad( audioBuffer ); - if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { + } ); - propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; + } catch ( e ) { - } + if ( onError ) { + onError( e ); } else { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this ); - return; + console.error( e ); } + scope.manager.itemError( url ); + } - bindingType = this.BindingType.ArrayElement; + }, onProgress, onError ); - this.resolvedProperty = nodeProperty; - this.propertyIndex = propertyIndex; + } - } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { +} - // must use copy for Object3D.Euler/Quaternion +class HemisphereLightProbe extends LightProbe { - bindingType = this.BindingType.HasFromToArray; + constructor( skyColor, groundColor, intensity = 1 ) { - this.resolvedProperty = nodeProperty; + super( undefined, intensity ); - } else if ( Array.isArray( nodeProperty ) ) { + this.isHemisphereLightProbe = true; - bindingType = this.BindingType.EntireArray; + const color1 = new Color().set( skyColor ); + const color2 = new Color().set( groundColor ); - this.resolvedProperty = nodeProperty; + const sky = new Vector3( color1.r, color1.g, color1.b ); + const ground = new Vector3( color2.r, color2.g, color2.b ); - } else { + // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); + const c0 = Math.sqrt( Math.PI ); + const c1 = c0 * Math.sqrt( 0.75 ); - this.propertyName = propertyName; + this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); + this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); - } + } - // select getter / setter - this.getValue = this.GetterByBindingType[ bindingType ]; - this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; +} - }, +class AmbientLightProbe extends LightProbe { - unbind: function () { + constructor( color, intensity = 1 ) { - this.node = null; + super( undefined, intensity ); - // 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; + this.isAmbientLightProbe = true; + + const color1 = new Color().set( color ); + + // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); + this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); } -} ); +} -// DECLARE ALIAS AFTER assign prototype -Object.assign( PropertyBinding.prototype, { +const _eyeRight = /*@__PURE__*/ new Matrix4(); +const _eyeLeft = /*@__PURE__*/ new Matrix4(); +const _projectionMatrix = /*@__PURE__*/ new Matrix4(); - // initial state of these methods that calls 'bind' - _getValue_unbound: PropertyBinding.prototype.getValue, - _setValue_unbound: PropertyBinding.prototype.setValue, +class StereoCamera { -} ); + constructor() { -/** - * - * 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. - */ + this.type = 'StereoCamera'; -class AnimationObjectGroup { + this.aspect = 1; - constructor() { + this.eyeSep = 0.064; - this.uuid = MathUtils.generateUUID(); + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; - // cached objects followed by the active ones - this._objects = Array.prototype.slice.call( arguments ); + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; - this.nCachedObjects_ = 0; // threshold - // note: read by PropertyBinding.Composite + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; - const indices = {}; - this._indicesByUUID = indices; // for bookkeeping + } - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + update( camera ) { - indices[ arguments[ i ].uuid ] = i; + const cache = this._cache; - } + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || + cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || + cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; - this._paths = []; // inside: string - this._parsedPaths = []; // inside: { we don't care, here } - this._bindings = []; // inside: Array< PropertyBinding > - this._bindingsIndicesByPath = {}; // inside: indices in these arrays + if ( needsUpdate ) { - const scope = this; + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; - this.stats = { + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ - objects: { - get total() { + _projectionMatrix.copy( camera.projectionMatrix ); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; + let xmin, xmax; - return scope._objects.length; + // translate xOffset - }, - get inUse() { + _eyeLeft.elements[ 12 ] = - eyeSepHalf; + _eyeRight.elements[ 12 ] = eyeSepHalf; - return this.total - scope.nCachedObjects_; + // for left eye - } - }, - get bindingsPerObject() { + xmin = - ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; - return scope._bindings.length; + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - } + this.cameraL.projectionMatrix.copy( _projectionMatrix ); - }; + // for right eye + + xmin = - ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraR.projectionMatrix.copy( _projectionMatrix ); + + } + + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); } - add() { +} - const objects = this._objects, - indicesByUUID = this._indicesByUUID, - paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - nBindings = bindings.length; +class Clock { - let knownObject = undefined, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_; + constructor( autoStart = true ) { - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + this.autoStart = autoStart; - const object = arguments[ i ], - uuid = object.uuid; - let index = indicesByUUID[ uuid ]; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; - if ( index === undefined ) { + this.running = false; + + } + + start() { + + this.startTime = now(); - // unknown object -> add it to the ACTIVE region + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; - index = nObjects ++; - indicesByUUID[ uuid ] = index; - objects.push( object ); + } - // accounting is done, now do the same for all bindings + stop() { - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; - bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); + } - } + getElapsedTime() { - } else if ( index < nCachedObjects ) { + this.getDelta(); + return this.elapsedTime; - knownObject = objects[ index ]; + } - // move existing object to the ACTIVE region + getDelta() { - const firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ]; + let diff = 0; - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + if ( this.autoStart && ! this.running ) { - indicesByUUID[ uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = object; + this.start(); + return 0; - // accounting is done, now do the same for all bindings + } - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + if ( this.running ) { - const bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ]; + const newTime = now(); - let binding = bindingsForPath[ index ]; + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; - bindingsForPath[ index ] = lastCached; + this.elapsedTime += diff; - if ( binding === undefined ) { + } - // since we do not bother to create new bindings - // for objects that are cached, the binding may - // or may not exist + return diff; - binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); + } - } +} - bindingsForPath[ firstActiveIndex ] = binding; +function now() { - } + return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 - } else if ( objects[ index ] !== knownObject ) { +} - console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + - 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); +const _position$1 = /*@__PURE__*/ new Vector3(); +const _quaternion$1 = /*@__PURE__*/ new Quaternion(); +const _scale$1 = /*@__PURE__*/ new Vector3(); +const _orientation$1 = /*@__PURE__*/ new Vector3(); - } // else the object is already where we want it to be +class AudioListener extends Object3D { - } // for arguments + constructor() { - this.nCachedObjects_ = nCachedObjects; + super(); - } + this.type = 'AudioListener'; - remove() { + this.context = AudioContext.getContext(); - const objects = this._objects, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - let nCachedObjects = this.nCachedObjects_; + this.filter = null; - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + this.timeDelta = 0; - const object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + // private - if ( index !== undefined && index >= nCachedObjects ) { + this._clock = new Clock(); - // move existing object into the CACHED region + } - const lastCachedIndex = nCachedObjects ++, - firstActiveObject = objects[ lastCachedIndex ]; + getInput() { - indicesByUUID[ firstActiveObject.uuid ] = index; - objects[ index ] = firstActiveObject; + return this.gain; - indicesByUUID[ uuid ] = lastCachedIndex; - objects[ lastCachedIndex ] = object; + } - // accounting is done, now do the same for all bindings + removeFilter() { - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + if ( this.filter !== null ) { - const bindingsForPath = bindings[ j ], - firstActive = bindingsForPath[ lastCachedIndex ], - binding = bindingsForPath[ index ]; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; - bindingsForPath[ index ] = firstActive; - bindingsForPath[ lastCachedIndex ] = binding; + } - } + return this; - } + } - } // for arguments + getFilter() { - this.nCachedObjects_ = nCachedObjects; + return this.filter; } - // remove & forget - uncache() { + setFilter( value ) { - const objects = this._objects, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + if ( this.filter !== null ) { - let nCachedObjects = this.nCachedObjects_, - nObjects = objects.length; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + } else { - const object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + this.gain.disconnect( this.context.destination ); - if ( index !== undefined ) { + } - delete indicesByUUID[ uuid ]; + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); - if ( index < nCachedObjects ) { + return this; - // object is cached, shrink the CACHED region + } - const firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ], - lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + getMasterVolume() { - // last cached object takes this object's place - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + return this.gain.gain.value; - // 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 + setMasterVolume( value ) { - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); - const bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - last = bindingsForPath[ lastIndex ]; + return this; - bindingsForPath[ index ] = lastCached; - bindingsForPath[ firstActiveIndex ] = last; - bindingsForPath.pop(); + } - } + updateMatrixWorld( force ) { - } else { + super.updateMatrixWorld( force ); - // object is active, just swap with the last and pop + const listener = this.context.listener; + const up = this.up; - const lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + this.timeDelta = this._clock.getDelta(); - if ( lastIndex > 0 ) { + this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 ); - indicesByUUID[ lastObject.uuid ] = index; + _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 ); - } + if ( listener.positionX ) { - objects[ index ] = lastObject; - objects.pop(); + // code path for Chrome (see #14393) - // accounting is done, now do the same for all bindings + const endTime = this.context.currentTime + this.timeDelta; - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + listener.positionX.linearRampToValueAtTime( _position$1.x, endTime ); + listener.positionY.linearRampToValueAtTime( _position$1.y, endTime ); + listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime ); + listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime ); + listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime ); + listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + listener.upX.linearRampToValueAtTime( up.x, endTime ); + listener.upY.linearRampToValueAtTime( up.y, endTime ); + listener.upZ.linearRampToValueAtTime( up.z, endTime ); - const bindingsForPath = bindings[ j ]; + } else { - bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; - bindingsForPath.pop(); + listener.setPosition( _position$1.x, _position$1.y, _position$1.z ); + listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z ); - } + } - } // cached or active + } - } // if object is known +} - } // for arguments +class Audio extends Object3D { - this.nCachedObjects_ = nCachedObjects; + constructor( listener ) { - } + super(); - // Internal interface used by befriended PropertyBinding.Composite: + this.type = 'Audio'; - subscribe_( path, parsedPath ) { + this.listener = listener; + this.context = listener.context; - // returns an array of bindings for the given path that is changed - // according to the contained objects in the group + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); - const indicesByPath = this._bindingsIndicesByPath; - let index = indicesByPath[ path ]; - const bindings = this._bindings; + this.autoplay = false; - if ( index !== undefined ) return bindings[ index ]; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = 'empty'; - const paths = this._paths, - parsedPaths = this._parsedPaths, - objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - bindingsForPath = new Array( nObjects ); + this._startedAt = 0; + this._progress = 0; + this._connected = false; - index = bindings.length; + this.filters = []; - indicesByPath[ path ] = index; + } - paths.push( path ); - parsedPaths.push( parsedPath ); - bindings.push( bindingsForPath ); + getOutput() { - for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { + return this.gain; - const object = objects[ i ]; - bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); + } - } + setNodeSource( audioNode ) { - return bindingsForPath; + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); + + return this; } - unsubscribe_( path ) { + setMediaElementSource( mediaElement ) { - // tells the group to forget about a property path and no longer - // update the array previously obtained with 'subscribe_' + this.hasPlaybackControl = false; + this.sourceType = 'mediaNode'; + this.source = this.context.createMediaElementSource( mediaElement ); + this.connect(); - const indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ]; + return this; - if ( index !== undefined ) { + } - const paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - lastBindingsIndex = bindings.length - 1, - lastBindings = bindings[ lastBindingsIndex ], - lastBindingsPath = path[ lastBindingsIndex ]; + setMediaStreamSource( mediaStream ) { - indicesByPath[ lastBindingsPath ] = index; + this.hasPlaybackControl = false; + this.sourceType = 'mediaStreamNode'; + this.source = this.context.createMediaStreamSource( mediaStream ); + this.connect(); - bindings[ index ] = lastBindings; - bindings.pop(); + return this; - parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; - parsedPaths.pop(); + } - paths[ index ] = paths[ lastBindingsIndex ]; - paths.pop(); + setBuffer( audioBuffer ) { - } + this.buffer = audioBuffer; + this.sourceType = 'buffer'; + + if ( this.autoplay ) this.play(); + + return this; } -} + play( delay = 0 ) { -AnimationObjectGroup.prototype.isAnimationObjectGroup = true; + if ( this.isPlaying === true ) { -class AnimationAction { + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; - constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { + } - this._mixer = mixer; - this._clip = clip; - this._localRoot = localRoot; - this.blendMode = blendMode; + if ( this.hasPlaybackControl === false ) { - const tracks = clip.tracks, - nTracks = tracks.length, - interpolants = new Array( nTracks ); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - const interpolantSettings = { - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding - }; + } - for ( let i = 0; i !== nTracks; ++ i ) { + this._startedAt = this.context.currentTime + delay; - const interpolant = tracks[ i ].createInterpolant( null ); - interpolants[ i ] = interpolant; - interpolant.settings = interpolantSettings; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind( this ); + source.start( this._startedAt, this._progress + this.offset, this.duration ); - } + this.isPlaying = true; - this._interpolantSettings = interpolantSettings; + this.source = source; - this._interpolants = interpolants; // bound by the mixer + this.setDetune( this.detune ); + this.setPlaybackRate( this.playbackRate ); - // inside: PropertyMixer (managed by the mixer) - this._propertyBindings = new Array( nTracks ); + return this.connect(); - this._cacheIndex = null; // for the memory manager - this._byClipCacheIndex = null; // for the memory manager + } - this._timeScaleInterpolant = null; - this._weightInterpolant = null; + pause() { - this.loop = LoopRepeat; - this._loopCount = - 1; + if ( this.hasPlaybackControl === false ) { - // global mixer time when the action is to be started - // it's set back to 'null' upon start of the action - this._startTime = null; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - // 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; + if ( this.isPlaying === true ) { - this.weight = 1; - this._effectiveWeight = 1; + // update current progress - this.repetitions = Infinity; // no. of repetitions when looping + this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; - this.paused = false; // true -> zero effective time scale - this.enabled = true; // false -> zero effective weight + if ( this.loop === true ) { - this.clampWhenFinished = false;// keep feeding the last frame? + // ensure _progress does not exceed duration with looped audios - this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate - this.zeroSlopeAtEnd = true;// clips for start, loop and end + this._progress = this._progress % ( this.duration || this.buffer.duration ); - } + } - // State & Scheduling + this.source.stop(); + this.source.onended = null; - play() { + this.isPlaying = false; - this._mixer._activateAction( this ); + } return this; @@ -42645,127 +43693,110 @@ class AnimationAction { stop() { - this._mixer._deactivateAction( this ); - - return this.reset(); + if ( this.hasPlaybackControl === false ) { - } + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - reset() { + } - this.paused = false; - this.enabled = true; + this._progress = 0; - this.time = 0; // restart clip - this._loopCount = - 1;// forget previous loops - this._startTime = null;// forget scheduling + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; - return this.stopFading().stopWarping(); + return this; } - isRunning() { - - return this.enabled && ! this.paused && this.timeScale !== 0 && - this._startTime === null && this._mixer._isActiveAction( this ); + connect() { - } + if ( this.filters.length > 0 ) { - // return true when play has been called - isScheduled() { + this.source.connect( this.filters[ 0 ] ); - return this._mixer._isActiveAction( this ); + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { - } + this.filters[ i - 1 ].connect( this.filters[ i ] ); - startAt( time ) { + } - this._startTime = time; + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); - return this; + } else { - } + this.source.connect( this.getOutput() ); - setLoop( mode, repetitions ) { + } - this.loop = mode; - this.repetitions = repetitions; + this._connected = true; return this; } - // Weight + disconnect() { - // 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( weight ) { + if ( this.filters.length > 0 ) { - this.weight = weight; + this.source.disconnect( this.filters[ 0 ] ); - // note: same logic as when updated at runtime - this._effectiveWeight = this.enabled ? weight : 0; + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { - return this.stopFading(); + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); - } + } - // return the weight considering fading and .enabled - getEffectiveWeight() { + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); - return this._effectiveWeight; + } else { - } + this.source.disconnect( this.getOutput() ); - fadeIn( duration ) { + } - return this._scheduleFading( duration, 0, 1 ); + this._connected = false; + + return this; } - fadeOut( duration ) { + getFilters() { - return this._scheduleFading( duration, 1, 0 ); + return this.filters; } - crossFadeFrom( fadeOutAction, duration, warp ) { + setFilters( value ) { - fadeOutAction.fadeOut( duration ); - this.fadeIn( duration ); + if ( ! value ) value = []; - if ( warp ) { + if ( this._connected === true ) { - const fadeInDuration = this._clip.duration, - fadeOutDuration = fadeOutAction._clip.duration, + this.disconnect(); + this.filters = value.slice(); + this.connect(); - startEndRatio = fadeOutDuration / fadeInDuration, - endStartRatio = fadeInDuration / fadeOutDuration; + } else { - fadeOutAction.warp( 1.0, startEndRatio, duration ); - this.warp( endStartRatio, 1.0, duration ); + this.filters = value.slice(); } - return this; - - } - - crossFadeTo( fadeInAction, duration, warp ) { - - return fadeInAction.crossFadeFrom( this, duration, warp ); + return this; } - stopFading() { + setDetune( value ) { - const weightInterpolant = this._weightInterpolant; + this.detune = value; - if ( weightInterpolant !== null ) { + if ( this.source.detune === undefined ) return; // only set detune when available - this._weightInterpolant = null; - this._mixer._takeBackControlInterpolant( weightInterpolant ); + if ( this.isPlaying === true ) { + + this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); } @@ -42773,86 +43804,84 @@ class AnimationAction { } - // Time Scale Control + getDetune() { - // set the time scale 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( timeScale ) { + return this.detune; - this.timeScale = timeScale; - this._effectiveTimeScale = this.paused ? 0 : timeScale; + } - return this.stopWarping(); + getFilter() { + + return this.getFilters()[ 0 ]; } - // return the time scale considering warping and .paused - getEffectiveTimeScale() { + setFilter( filter ) { - return this._effectiveTimeScale; + return this.setFilters( filter ? [ filter ] : [] ); } - setDuration( duration ) { + setPlaybackRate( value ) { - this.timeScale = this._clip.duration / duration; + if ( this.hasPlaybackControl === false ) { - return this.stopWarping(); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - } + } - syncWith( action ) { + this.playbackRate = value; - this.time = action.time; - this.timeScale = action.timeScale; + if ( this.isPlaying === true ) { - return this.stopWarping(); + this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + + } + + return this; } - halt( duration ) { + getPlaybackRate() { - return this.warp( this._effectiveTimeScale, 0, duration ); + return this.playbackRate; } - warp( startTimeScale, endTimeScale, duration ) { + onEnded() { - const mixer = this._mixer, - now = mixer.time, - timeScale = this.timeScale; + this.isPlaying = false; - let interpolant = this._timeScaleInterpolant; + } - if ( interpolant === null ) { + getLoop() { - interpolant = mixer._lendControlInterpolant(); - this._timeScaleInterpolant = interpolant; + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; } - const times = interpolant.parameterPositions, - values = interpolant.sampleValues; + return this.loop; - times[ 0 ] = now; - times[ 1 ] = now + duration; + } - values[ 0 ] = startTimeScale / timeScale; - values[ 1 ] = endTimeScale / timeScale; + setLoop( value ) { - return this; + if ( this.hasPlaybackControl === false ) { - } + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - stopWarping() { + } - const timeScaleInterpolant = this._timeScaleInterpolant; + this.loop = value; - if ( timeScaleInterpolant !== null ) { + if ( this.isPlaying === true ) { - this._timeScaleInterpolant = null; - this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + this.source.loop = this.loop; } @@ -42860,6060 +43889,5749 @@ class AnimationAction { } - // Object Accessors + setLoopStart( value ) { - getMixer() { + this.loopStart = value; - return this._mixer; + return this; } - getClip() { + setLoopEnd( value ) { - return this._clip; + this.loopEnd = value; + + return this; } - getRoot() { + getVolume() { - return this._localRoot || this._mixer._root; + return this.gain.gain.value; } - // Interna + setVolume( value ) { - _update( time, deltaTime, timeDirection, accuIndex ) { + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); - // called by the mixer + return this; - if ( ! this.enabled ) { + } - // call ._updateWeight() to update ._effectiveWeight +} - this._updateWeight( time ); - return; +const _position = /*@__PURE__*/ new Vector3(); +const _quaternion = /*@__PURE__*/ new Quaternion(); +const _scale = /*@__PURE__*/ new Vector3(); +const _orientation = /*@__PURE__*/ new Vector3(); - } +class PositionalAudio extends Audio { - const startTime = this._startTime; + constructor( listener ) { - if ( startTime !== null ) { + super( listener ); - // check for scheduled start of action + this.panner = this.context.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.connect( this.gain ); - const timeRunning = ( time - startTime ) * timeDirection; - if ( timeRunning < 0 || timeDirection === 0 ) { + } - return; // yet to come / don't decide when delta = 0 + disconnect() { - } + super.disconnect(); - // start + this.panner.disconnect( this.gain ); - this._startTime = null; // unschedule - deltaTime = timeDirection * timeRunning; + } - } + getOutput() { - // apply time scale and advance time + return this.panner; - deltaTime *= this._updateTimeScale( time ); - const clipTime = this._updateTime( deltaTime ); + } - // note: _updateTime may disable the action resulting in - // an effective weight of 0 + getRefDistance() { - const weight = this._updateWeight( time ); + return this.panner.refDistance; - if ( weight > 0 ) { + } - const interpolants = this._interpolants; - const propertyMixers = this._propertyBindings; + setRefDistance( value ) { - switch ( this.blendMode ) { + this.panner.refDistance = value; - case AdditiveAnimationBlendMode: + return this; - for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + } - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulateAdditive( weight ); + getRolloffFactor() { - } + return this.panner.rolloffFactor; - break; + } - case NormalAnimationBlendMode: - default: + setRolloffFactor( value ) { - for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + this.panner.rolloffFactor = value; - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulate( accuIndex, weight ); + return this; - } + } - } + getDistanceModel() { - } + return this.panner.distanceModel; } - _updateWeight( time ) { - - let weight = 0; - - if ( this.enabled ) { + setDistanceModel( value ) { - weight = this.weight; - const interpolant = this._weightInterpolant; + this.panner.distanceModel = value; - if ( interpolant !== null ) { + return this; - const interpolantValue = interpolant.evaluate( time )[ 0 ]; + } - weight *= interpolantValue; + getMaxDistance() { - if ( time > interpolant.parameterPositions[ 1 ] ) { + return this.panner.maxDistance; - this.stopFading(); + } - if ( interpolantValue === 0 ) { + setMaxDistance( value ) { - // faded out, disable - this.enabled = false; + this.panner.maxDistance = value; - } + return this; - } + } - } + setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { - } + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; - this._effectiveWeight = weight; - return weight; + return this; } - _updateTimeScale( time ) { + updateMatrixWorld( force ) { - let timeScale = 0; + super.updateMatrixWorld( force ); - if ( ! this.paused ) { + if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; - timeScale = this.timeScale; + this.matrixWorld.decompose( _position, _quaternion, _scale ); - const interpolant = this._timeScaleInterpolant; + _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); - if ( interpolant !== null ) { + const panner = this.panner; - const interpolantValue = interpolant.evaluate( time )[ 0 ]; + if ( panner.positionX ) { - timeScale *= interpolantValue; + // code path for Chrome and Firefox (see #14393) - if ( time > interpolant.parameterPositions[ 1 ] ) { + const endTime = this.context.currentTime + this.listener.timeDelta; - this.stopWarping(); + panner.positionX.linearRampToValueAtTime( _position.x, endTime ); + panner.positionY.linearRampToValueAtTime( _position.y, endTime ); + panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); + panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); + panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); + panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); - if ( timeScale === 0 ) { + } else { - // motion has halted, pause - this.paused = true; + panner.setPosition( _position.x, _position.y, _position.z ); + panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); - } else { + } - // warp done - apply final time scale - this.timeScale = timeScale; + } - } +} - } +class AudioAnalyser { - } + constructor( audio, fftSize = 2048 ) { - } + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; - this._effectiveTimeScale = timeScale; - return timeScale; + this.data = new Uint8Array( this.analyser.frequencyBinCount ); + + audio.getOutput().connect( this.analyser ); } - _updateTime( deltaTime ) { - const duration = this._clip.duration; - const loop = this.loop; + getFrequencyData() { - let time = this.time + deltaTime; - let loopCount = this._loopCount; + this.analyser.getByteFrequencyData( this.data ); - const pingPong = ( loop === LoopPingPong ); + return this.data; - if ( deltaTime === 0 ) { + } - if ( loopCount === - 1 ) return time; + getAverageFrequency() { - return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; + let value = 0; + const data = this.getFrequencyData(); + + for ( let i = 0; i < data.length; i ++ ) { + + value += data[ i ]; } - if ( loop === LoopOnce ) { + return value / data.length; - if ( loopCount === - 1 ) { + } - // just started +} - this._loopCount = 0; - this._setEndings( true, true, false ); +class PropertyMixer { - } + constructor( binding, typeName, valueSize ) { - handle_stop: { + this.binding = binding; + this.valueSize = valueSize; - if ( time >= duration ) { + let mixFunction, + mixFunctionAdditive, + setIdentity; - time = duration; + // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] + // + // 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 + // + // 'add' is used for additive cumulative results + // + // 'work' is optional and is only present for quaternion types. It is used + // to store intermediate quaternion multiplication results - } else if ( time < 0 ) { + switch ( typeName ) { - time = 0; + case 'quaternion': + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; - } else { + this.buffer = new Float64Array( valueSize * 6 ); + this._workIndex = 5; + break; - this.time = time; + case 'string': + case 'bool': + mixFunction = this._select; - break handle_stop; + // Use the regular mix function and for additive on these types, + // additive is not relevant for non-numeric types + mixFunctionAdditive = this._select; - } + setIdentity = this._setAdditiveIdentityOther; - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + this.buffer = new Array( valueSize * 5 ); + break; - this.time = time; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime < 0 ? - 1 : 1 - } ); + this.buffer = new Float64Array( valueSize * 5 ); - } + } - } else { // repetitive Repeat or PingPong + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; - if ( loopCount === - 1 ) { + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - // just started + this.useCount = 0; + this.referenceCount = 0; - if ( deltaTime >= 0 ) { + } - loopCount = 0; + // accumulate data in the 'incoming' region into 'accu' + accumulate( accuIndex, weight ) { - this._setEndings( true, this.repetitions === 0, pingPong ); + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place - } else { + const buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride; - // when looping in reverse direction, the initial - // transition through zero counts as a repetition, - // so leave loopCount at -1 + let currentWeight = this.cumulativeWeight; - this._setEndings( this.repetitions === 0, true, pingPong ); + if ( currentWeight === 0 ) { - } + // accuN := incoming * weight - } + for ( let i = 0; i !== stride; ++ i ) { - if ( time >= duration || time < 0 ) { + buffer[ offset + i ] = buffer[ i ]; - // wrap around + } - const loopDelta = Math.floor( time / duration ); // signed - time -= duration * loopDelta; + currentWeight = weight; - loopCount += Math.abs( loopDelta ); + } else { - const pending = this.repetitions - loopCount; + // accuN := accuN + incoming * weight - if ( pending <= 0 ) { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); - // have to stop (switch state, clamp time, fire event) + } - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + this.cumulativeWeight = currentWeight; - time = deltaTime > 0 ? duration : 0; + } - this.time = time; + // accumulate data in the 'incoming' region into 'add' + accumulateAdditive( weight ) { - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime > 0 ? 1 : - 1 - } ); + const buffer = this.buffer, + stride = this.valueSize, + offset = stride * this._addIndex; - } else { + if ( this.cumulativeWeightAdditive === 0 ) { - // keep running + // add = identity - if ( pending === 1 ) { + this._setIdentity(); - // entering the last round + } - const atStart = deltaTime < 0; - this._setEndings( atStart, ! atStart, pingPong ); + // add := add + incoming * weight - } else { + this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); + this.cumulativeWeightAdditive += weight; - this._setEndings( false, false, pingPong ); + } - } + // apply the state of 'accu' to the binding when accus differ + apply( accuIndex ) { - this._loopCount = loopCount; + const stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, - this.time = time; + weight = this.cumulativeWeight, + weightAdditive = this.cumulativeWeightAdditive, - this._mixer.dispatchEvent( { - type: 'loop', action: this, loopDelta: loopDelta - } ); + binding = this.binding; - } + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - } else { + if ( weight < 1 ) { - this.time = time; + // accuN := accuN + original * ( 1 - cumulativeWeight ) - } + const originalValueOffset = stride * this._origIndex; - if ( pingPong && ( loopCount & 1 ) === 1 ) { + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); - // invert time for the "pong round" + } - return duration - time; + if ( weightAdditive > 0 ) { - } + // accuN := accuN + additive accuN + + this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); } - return time; + for ( let i = stride, e = stride + stride; i !== e; ++ i ) { - } + if ( buffer[ i ] !== buffer[ i + stride ] ) { - _setEndings( atStart, atEnd, pingPong ) { + // value has changed -> update scene graph - const settings = this._interpolantSettings; + binding.setValue( buffer, offset ); + break; - if ( pingPong ) { + } - settings.endingStart = ZeroSlopeEnding; - settings.endingEnd = ZeroSlopeEnding; + } - } else { + } - // assuming for LoopOnce atStart == atEnd == true + // remember the state of the bound property and copy it to both accus + saveOriginalState() { - if ( atStart ) { + const binding = this.binding; - settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + const buffer = this.buffer, + stride = this.valueSize, - } else { + originalValueOffset = stride * this._origIndex; - settings.endingStart = WrapAroundEnding; + binding.getValue( buffer, originalValueOffset ); - } + // accu[0..1] := orig -- initially detect changes against the original + for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { - if ( atEnd ) { + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; - settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + } - } else { + // Add to identity for additive + this._setIdentity(); - settings.endingEnd = WrapAroundEnding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - } + } + + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState() { - } + const originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); } - _scheduleFading( duration, weightNow, weightThen ) { + _setAdditiveIdentityNumeric() { - const mixer = this._mixer, now = mixer.time; - let interpolant = this._weightInterpolant; + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; - if ( interpolant === null ) { + for ( let i = startIndex; i < endIndex; i ++ ) { - interpolant = mixer._lendControlInterpolant(); - this._weightInterpolant = interpolant; + this.buffer[ i ] = 0; } - const times = interpolant.parameterPositions, - values = interpolant.sampleValues; + } - times[ 0 ] = now; - values[ 0 ] = weightNow; - times[ 1 ] = now + duration; - values[ 1 ] = weightThen; + _setAdditiveIdentityQuaternion() { - return this; + this._setAdditiveIdentityNumeric(); + this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; } -} + _setAdditiveIdentityOther() { -class AnimationMixer extends EventDispatcher { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; - constructor( root ) { + for ( let i = 0; i < this.valueSize; i ++ ) { - super(); + this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; - this._root = root; - this._initMemoryManager(); - this._accuIndex = 0; - this.time = 0; - this.timeScale = 1.0; + } } - _bindAction( action, prototypeAction ) { - const root = action._localRoot || this._root, - tracks = action._clip.tracks, - nTracks = tracks.length, - bindings = action._propertyBindings, - interpolants = action._interpolants, - rootUuid = root.uuid, - bindingsByRoot = this._bindingsByRootAndName; + // mix functions - let bindingsByName = bindingsByRoot[ rootUuid ]; + _select( buffer, dstOffset, srcOffset, t, stride ) { - if ( bindingsByName === undefined ) { + if ( t >= 0.5 ) { - bindingsByName = {}; - bindingsByRoot[ rootUuid ] = bindingsByName; + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + + } } - for ( let i = 0; i !== nTracks; ++ i ) { + } - const track = tracks[ i ], - trackName = track.name; + _slerp( buffer, dstOffset, srcOffset, t ) { - let binding = bindingsByName[ trackName ]; + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); - if ( binding !== undefined ) { + } - bindings[ i ] = binding; + _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { - } else { + const workOffset = this._workIndex * stride; - binding = bindings[ i ]; + // Store result in intermediate buffer offset + Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); - if ( binding !== undefined ) { + // Slerp to the intermediate result + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); - // existing binding, make sure the cache knows + } - if ( binding._cacheIndex === null ) { + _lerp( buffer, dstOffset, srcOffset, t, stride ) { - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + const s = 1 - t; - } + for ( let i = 0; i !== stride; ++ i ) { - continue; + const j = dstOffset + i; - } + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; - const path = prototypeAction && prototypeAction. - _propertyBindings[ i ].binding.parsedPath; + } - binding = new PropertyMixer( - PropertyBinding.create( root, trackName, path ), - track.ValueTypeName, track.getValueSize() ); + } - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { - bindings[ i ] = binding; + for ( let i = 0; i !== stride; ++ i ) { - } + const j = dstOffset + i; - interpolants[ i ].resultBuffer = binding.buffer; + buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; } } - _activateAction( action ) { +} - if ( ! this._isActiveAction( action ) ) { +// Characters [].:/ are reserved for track binding syntax. +const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; +const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); - if ( action._cacheIndex === null ) { +// Attempts to allow node names from any language. ES5's `\w` regexp matches +// only latin characters, and the unicode \p{L} is not yet supported. So +// instead, we exclude reserved characters and match everything else. +const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; +const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; - // this action has been forgotten by the cache, but the user - // appears to be still using it -> rebind +// Parent directories, delimited by '/' or ':'. Currently unused, but must +// be matched to parse the rest of the track name. +const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); - const rootUuid = ( action._localRoot || this._root ).uuid, - clipUuid = action._clip.uuid, - actionsForClip = this._actionsByClip[ clipUuid ]; +// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. +const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); - this._bindAction( action, - actionsForClip && actionsForClip.knownActions[ 0 ] ); +// Object on target node, and accessor. May not contain reserved +// characters. Accessor may contain any character except closing bracket. +const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); - this._addInactiveAction( action, clipUuid, rootUuid ); +// Property and accessor. May not contain reserved characters. Accessor may +// contain any non-bracket characters. +const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); - } +const _trackRe = new RegExp( '' + + '^' + + _directoryRe + + _nodeRe + + _objectRe + + _propertyRe + + '$' +); - const bindings = action._propertyBindings; +const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ]; - // increment reference counts / sort out state - for ( let i = 0, n = bindings.length; i !== n; ++ i ) { +class Composite { - const binding = bindings[ i ]; + constructor( targetGroup, path, optionalParsedPath ) { - if ( binding.useCount ++ === 0 ) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); - this._lendBinding( binding ); - binding.saveOriginalState(); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); - } + } - } + getValue( array, offset ) { - this._lendAction( action ); + this.bind(); // bind all binding - } + const firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; + + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); } - _deactivateAction( action ) { + setValue( array, offset ) { - if ( this._isActiveAction( action ) ) { + const bindings = this._bindings; - const bindings = action._propertyBindings; + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { - // decrement reference counts / sort out state - for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + bindings[ i ].setValue( array, offset ); - const binding = bindings[ i ]; + } - if ( -- binding.useCount === 0 ) { + } - binding.restoreOriginalState(); - this._takeBackBinding( binding ); + bind() { - } + const bindings = this._bindings; - } + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { - this._takeBackAction( action ); + bindings[ i ].bind(); } } - // Memory manager - - _initMemoryManager() { + unbind() { - this._actions = []; // 'nActiveActions' followed by inactive ones - this._nActiveActions = 0; + const bindings = this._bindings; - this._actionsByClip = {}; - // inside: - // { - // knownActions: Array< AnimationAction > - used as prototypes - // actionByRoot: AnimationAction - lookup - // } + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + bindings[ i ].unbind(); - this._bindings = []; // 'nActiveBindings' followed by inactive ones - this._nActiveBindings = 0; + } - this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + } +} - this._controlInterpolants = []; // same game as above - this._nActiveControlInterpolants = 0; +// 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. +class PropertyBinding { - const scope = this; + constructor( rootNode, path, parsedPath ) { - this.stats = { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); - actions: { - get total() { + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; - return scope._actions.length; + this.rootNode = rootNode; - }, - get inUse() { + // initial state of these methods that calls 'bind' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; - return scope._nActiveActions; + } - } - }, - bindings: { - get total() { - return scope._bindings.length; + static create( root, path, parsedPath ) { - }, - get inUse() { + if ( ! ( root && root.isAnimationObjectGroup ) ) { - return scope._nActiveBindings; + return new PropertyBinding( root, path, parsedPath ); - } - }, - controlInterpolants: { - get total() { + } else { - return scope._controlInterpolants.length; + return new PropertyBinding.Composite( root, path, parsedPath ); - }, - get inUse() { + } - return scope._nActiveControlInterpolants; + } - } - } + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name Node name to be sanitized. + * @return {string} + */ + static sanitizeNodeName( name ) { - }; + return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); } - // Memory management for AnimationAction objects - - _isActiveAction( action ) { + static parseTrackName( trackName ) { - const index = action._cacheIndex; - return index !== null && index < this._nActiveActions; + const matches = _trackRe.exec( trackName ); - } + if ( matches === null ) { - _addInactiveAction( action, clipUuid, rootUuid ) { + throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); - const actions = this._actions, - actionsByClip = this._actionsByClip; + } - let actionsForClip = actionsByClip[ clipUuid ]; + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; - if ( actionsForClip === undefined ) { + const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); - actionsForClip = { + if ( lastDot !== undefined && lastDot !== - 1 ) { - knownActions: [ action ], - actionByRoot: {} + const objectName = results.nodeName.substring( lastDot + 1 ); - }; + // Object names must be checked against an allowlist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { - action._byClipCacheIndex = 0; + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; - actionsByClip[ clipUuid ] = actionsForClip; + } - } else { + } - const knownActions = actionsForClip.knownActions; + if ( results.propertyName === null || results.propertyName.length === 0 ) { - action._byClipCacheIndex = knownActions.length; - knownActions.push( action ); + throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); } - action._cacheIndex = actions.length; - actions.push( action ); - - actionsForClip.actionByRoot[ rootUuid ] = action; + return results; } - _removeInactiveAction( action ) { + static findNode( root, nodeName ) { - const actions = this._actions, - lastInactiveAction = actions[ actions.length - 1 ], - cacheIndex = action._cacheIndex; + if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + return root; - action._cacheIndex = null; + } + // search into skeleton bones. + if ( root.skeleton ) { - const clipUuid = action._clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ], - knownActionsForClip = actionsForClip.knownActions, + const bone = root.skeleton.getBoneByName( nodeName ); - lastKnownAction = - knownActionsForClip[ knownActionsForClip.length - 1 ], + if ( bone !== undefined ) { - byClipCacheIndex = action._byClipCacheIndex; + return bone; - lastKnownAction._byClipCacheIndex = byClipCacheIndex; - knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; - knownActionsForClip.pop(); + } - action._byClipCacheIndex = null; + } + // search into node subtree. + if ( root.children ) { - const actionByRoot = actionsForClip.actionByRoot, - rootUuid = ( action._localRoot || this._root ).uuid; + const searchNodeSubtree = function ( children ) { - delete actionByRoot[ rootUuid ]; + for ( let i = 0; i < children.length; i ++ ) { - if ( knownActionsForClip.length === 0 ) { + const childNode = children[ i ]; - delete actionsByClip[ clipUuid ]; + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { - } + return childNode; - this._removeInactiveBindingsForAction( action ); + } - } + const result = searchNodeSubtree( childNode.children ); - _removeInactiveBindingsForAction( action ) { + if ( result ) return result; - const bindings = action._propertyBindings; + } - for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + return null; - const binding = bindings[ i ]; + }; - if ( -- binding.referenceCount === 0 ) { + const subTreeNode = searchNodeSubtree( root.children ); - this._removeInactiveBinding( binding ); + if ( subTreeNode ) { + + return subTreeNode; } } - } - - _lendAction( action ) { - - // [ active actions | inactive actions ] - // [ active actions >| inactive actions ] - // s a - // <-swap-> - // a s + return null; - const actions = this._actions, - prevIndex = action._cacheIndex, + } - lastActiveIndex = this._nActiveActions ++, + // these are used to "bind" a nonexistent property + _getValue_unavailable() {} + _setValue_unavailable() {} - firstInactiveAction = actions[ lastActiveIndex ]; + // Getters - action._cacheIndex = lastActiveIndex; - actions[ lastActiveIndex ] = action; + _getValue_direct( buffer, offset ) { - firstInactiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = firstInactiveAction; + buffer[ offset ] = this.targetObject[ this.propertyName ]; } - _takeBackAction( action ) { + _getValue_array( buffer, offset ) { - // [ active actions | inactive actions ] - // [ active actions |< inactive actions ] - // a s - // <-swap-> - // s a + const source = this.resolvedProperty; - const actions = this._actions, - prevIndex = action._cacheIndex, + for ( let i = 0, n = source.length; i !== n; ++ i ) { - firstInactiveIndex = -- this._nActiveActions, + buffer[ offset ++ ] = source[ i ]; - lastActiveAction = actions[ firstInactiveIndex ]; + } - action._cacheIndex = firstInactiveIndex; - actions[ firstInactiveIndex ] = action; + } - lastActiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = lastActiveAction; + _getValue_arrayElement( buffer, offset ) { + + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; } - // Memory management for PropertyMixer objects + _getValue_toArray( buffer, offset ) { - _addInactiveBinding( binding, rootUuid, trackName ) { + this.resolvedProperty.toArray( buffer, offset ); - const bindingsByRoot = this._bindingsByRootAndName, - bindings = this._bindings; + } - let bindingByName = bindingsByRoot[ rootUuid ]; + // Direct - if ( bindingByName === undefined ) { + _setValue_direct( buffer, offset ) { - bindingByName = {}; - bindingsByRoot[ rootUuid ] = bindingByName; + this.targetObject[ this.propertyName ] = buffer[ offset ]; - } + } - bindingByName[ trackName ] = binding; + _setValue_direct_setNeedsUpdate( buffer, offset ) { - binding._cacheIndex = bindings.length; - bindings.push( binding ); + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; } - _removeInactiveBinding( binding ) { + _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - const bindings = this._bindings, - propBinding = binding.binding, - rootUuid = propBinding.rootNode.uuid, - trackName = propBinding.path, - bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - lastInactiveBinding = bindings[ bindings.length - 1 ], - cacheIndex = binding._cacheIndex; + } - lastInactiveBinding._cacheIndex = cacheIndex; - bindings[ cacheIndex ] = lastInactiveBinding; - bindings.pop(); + // EntireArray - delete bindingByName[ trackName ]; + _setValue_array( buffer, offset ) { - if ( Object.keys( bindingByName ).length === 0 ) { + const dest = this.resolvedProperty; - delete bindingsByRoot[ rootUuid ]; + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; } } - _lendBinding( binding ) { + _setValue_array_setNeedsUpdate( buffer, offset ) { - const bindings = this._bindings, - prevIndex = binding._cacheIndex, + const dest = this.resolvedProperty; - lastActiveIndex = this._nActiveBindings ++, + for ( let i = 0, n = dest.length; i !== n; ++ i ) { - firstInactiveBinding = bindings[ lastActiveIndex ]; + dest[ i ] = buffer[ offset ++ ]; - binding._cacheIndex = lastActiveIndex; - bindings[ lastActiveIndex ] = binding; + } - firstInactiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = firstInactiveBinding; + this.targetObject.needsUpdate = true; } - _takeBackBinding( binding ) { + _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { - const bindings = this._bindings, - prevIndex = binding._cacheIndex, + const dest = this.resolvedProperty; - firstInactiveIndex = -- this._nActiveBindings, + for ( let i = 0, n = dest.length; i !== n; ++ i ) { - lastActiveBinding = bindings[ firstInactiveIndex ]; + dest[ i ] = buffer[ offset ++ ]; - binding._cacheIndex = firstInactiveIndex; - bindings[ firstInactiveIndex ] = binding; + } - lastActiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = lastActiveBinding; + this.targetObject.matrixWorldNeedsUpdate = true; } + // ArrayElement - // Memory management of Interpolants for weight and time scale - - _lendControlInterpolant() { - - const interpolants = this._controlInterpolants, - lastActiveIndex = this._nActiveControlInterpolants ++; - - let interpolant = interpolants[ lastActiveIndex ]; - - if ( interpolant === undefined ) { + _setValue_arrayElement( buffer, offset ) { - interpolant = new LinearInterpolant( - new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - interpolant.__cacheIndex = lastActiveIndex; - interpolants[ lastActiveIndex ] = interpolant; + } - } + _setValue_arrayElement_setNeedsUpdate( buffer, offset ) { - return interpolant; + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; } - _takeBackControlInterpolant( interpolant ) { + _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { - const interpolants = this._controlInterpolants, - prevIndex = interpolant.__cacheIndex, + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - firstInactiveIndex = -- this._nActiveControlInterpolants, + } - lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + // HasToFromArray - interpolant.__cacheIndex = firstInactiveIndex; - interpolants[ firstInactiveIndex ] = interpolant; + _setValue_fromArray( buffer, offset ) { - lastActiveInterpolant.__cacheIndex = prevIndex; - interpolants[ prevIndex ] = lastActiveInterpolant; + this.resolvedProperty.fromArray( buffer, offset ); } - // 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( clip, optionalRoot, blendMode ) { - - const root = optionalRoot || this._root, - rootUuid = root.uuid; + _setValue_fromArray_setNeedsUpdate( buffer, offset ) { - let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; - const clipUuid = clipObject !== null ? clipObject.uuid : clip; + } - const actionsForClip = this._actionsByClip[ clipUuid ]; - let prototypeAction = null; + _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { - if ( blendMode === undefined ) { + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; - if ( clipObject !== null ) { + } - blendMode = clipObject.blendMode; + _getValue_unbound( targetArray, offset ) { - } else { + this.bind(); + this.getValue( targetArray, offset ); - blendMode = NormalAnimationBlendMode; + } - } + _setValue_unbound( sourceArray, offset ) { - } + this.bind(); + this.setValue( sourceArray, offset ); - if ( actionsForClip !== undefined ) { + } - const existingAction = actionsForClip.actionByRoot[ rootUuid ]; + // create getter / setter pair for a property in the scene graph + bind() { - if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { + let targetObject = this.node; + const parsedPath = this.parsedPath; - return existingAction; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; - } + if ( ! targetObject ) { - // we know the clip, so we don't have to parse all - // the bindings again but can just copy - prototypeAction = actionsForClip.knownActions[ 0 ]; + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; - // also, take the clip from the prototype action - if ( clipObject === null ) - clipObject = prototypeAction._clip; + this.node = targetObject; } - // clip must be known when specified via string - if ( clipObject === null ) return null; - - // allocate all resources required to run it - const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); - - this._bindAction( newAction, prototypeAction ); + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; - // and make the action known to the memory manager - this._addInactiveAction( newAction, clipUuid, rootUuid ); + // ensure there is a value node + if ( ! targetObject ) { - return newAction; + console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); + return; - } + } - // get an existing action - existingAction( clip, optionalRoot ) { + if ( objectName ) { - const root = optionalRoot || this._root, - rootUuid = root.uuid, + let objectIndex = parsedPath.objectIndex; - clipObject = typeof clip === 'string' ? - AnimationClip.findByName( root, clip ) : clip, + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { - clipUuid = clipObject ? clipObject.uuid : clip, + case 'materials': - actionsForClip = this._actionsByClip[ clipUuid ]; + if ( ! targetObject.material ) { - if ( actionsForClip !== undefined ) { + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; - return actionsForClip.actionByRoot[ rootUuid ] || null; + } - } + if ( ! targetObject.material.materials ) { - return null; + console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); + return; - } + } - // deactivates all previously scheduled actions - stopAllAction() { + targetObject = targetObject.material.materials; - const actions = this._actions, - nActions = this._nActiveActions; + break; - for ( let i = nActions - 1; i >= 0; -- i ) { + case 'bones': - actions[ i ].stop(); + if ( ! targetObject.skeleton ) { - } + console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); + return; - return this; + } - } + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. - // advance the time and update apply the animation - update( deltaTime ) { + targetObject = targetObject.skeleton.bones; - deltaTime *= this.timeScale; + // support resolving morphTarget names into indices. + for ( let i = 0; i < targetObject.length; i ++ ) { - const actions = this._actions, - nActions = this._nActiveActions, + if ( targetObject[ i ].name === objectIndex ) { - time = this.time += deltaTime, - timeDirection = Math.sign( deltaTime ), + objectIndex = i; + break; - accuIndex = this._accuIndex ^= 1; + } - // run active actions + } - for ( let i = 0; i !== nActions; ++ i ) { + break; - const action = actions[ i ]; + case 'map': - action._update( time, deltaTime, timeDirection, accuIndex ); + if ( ! targetObject.material ) { - } + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; - // update scene graph + } - const bindings = this._bindings, - nBindings = this._nActiveBindings; + if ( ! targetObject.material.map ) { - for ( let i = 0; i !== nBindings; ++ i ) { + console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this ); + return; - bindings[ i ].apply( accuIndex ); + } - } + targetObject = targetObject.material.map; + break; - return this; + default: - } + if ( targetObject[ objectName ] === undefined ) { - // Allows you to seek to a specific time in an animation. - setTime( timeInSeconds ) { + console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); + return; - this.time = 0; // Zero out time attribute for AnimationMixer object; - for ( let i = 0; i < this._actions.length; i ++ ) { + } - this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + targetObject = targetObject[ objectName ]; - } + } - return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. - } + if ( objectIndex !== undefined ) { - // return this mixer's root target object - getRoot() { + if ( targetObject[ objectIndex ] === undefined ) { - return this._root; + console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); + return; - } + } - // free all resources specific to a particular clip - uncacheClip( clip ) { + targetObject = targetObject[ objectIndex ]; - const actions = this._actions, - clipUuid = clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + } - if ( actionsForClip !== undefined ) { + } - // note: just calling _removeInactiveAction would mess up the - // iteration state and also require updating the state we can - // just throw away + // resolve property + const nodeProperty = targetObject[ propertyName ]; - const actionsToRemove = actionsForClip.knownActions; + if ( nodeProperty === undefined ) { - for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + const nodeName = parsedPath.nodeName; - const action = actionsToRemove[ i ]; + console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + + '.' + propertyName + ' but it wasn\'t found.', targetObject ); + return; - this._deactivateAction( action ); + } - const cacheIndex = action._cacheIndex, - lastInactiveAction = actions[ actions.length - 1 ]; + // determine versioning scheme + let versioning = this.Versioning.None; - action._cacheIndex = null; - action._byClipCacheIndex = null; + this.targetObject = targetObject; - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + if ( targetObject.needsUpdate !== undefined ) { // material - this._removeInactiveBindingsForAction( action ); + versioning = this.Versioning.NeedsUpdate; - } + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform - delete actionsByClip[ clipUuid ]; + versioning = this.Versioning.MatrixWorldNeedsUpdate; } - } - - // free all resources specific to a particular root target object - uncacheRoot( root ) { - - const rootUuid = root.uuid, - actionsByClip = this._actionsByClip; + // determine how the property gets bound + let bindingType = this.BindingType.Direct; - for ( const clipUuid in actionsByClip ) { + if ( propertyIndex !== undefined ) { - const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, - action = actionByRoot[ rootUuid ]; + // access a sub element of the property array (only primitives are supported right now) - if ( action !== undefined ) { + if ( propertyName === 'morphTargetInfluences' ) { - this._deactivateAction( action ); - this._removeInactiveAction( action ); + // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. - } + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { - } + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); + return; - const bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ]; + } - if ( bindingByName !== undefined ) { + if ( ! targetObject.geometry.morphAttributes ) { - for ( const trackName in bindingByName ) { + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; - const binding = bindingByName[ trackName ]; - binding.restoreOriginalState(); - this._removeInactiveBinding( binding ); + } - } + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { - } + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; - } + } - // remove a targeted clip from the cache - uncacheAction( clip, optionalRoot ) { + } - const action = this.existingAction( clip, optionalRoot ); + bindingType = this.BindingType.ArrayElement; - if ( action !== null ) { + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; - this._deactivateAction( action ); - this._removeInactiveAction( action ); + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { - } + // must use copy for Object3D.Euler/Quaternion - } + bindingType = this.BindingType.HasFromToArray; -} + this.resolvedProperty = nodeProperty; -AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 ); + } else if ( Array.isArray( nodeProperty ) ) { -class Uniform { + bindingType = this.BindingType.EntireArray; - constructor( value ) { + this.resolvedProperty = nodeProperty; - if ( typeof value === 'string' ) { + } else { - console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); - value = arguments[ 1 ]; + this.propertyName = propertyName; } - this.value = value; + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; } - clone() { + unbind() { - return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); + 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; } } -function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) { - - InterleavedBuffer.call( this, array, stride ); +PropertyBinding.Composite = Composite; - this.meshPerAttribute = meshPerAttribute || 1; - -} +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; -InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), { +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; - constructor: InstancedInterleavedBuffer, +PropertyBinding.prototype.GetterByBindingType = [ - isInstancedInterleavedBuffer: true, + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray, - copy: function ( source ) { +]; - InterleavedBuffer.prototype.copy.call( this, source ); +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ - this.meshPerAttribute = source.meshPerAttribute; + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate, - return this; + ], [ - }, + // EntireArray - clone: function ( data ) { + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate, - const ib = InterleavedBuffer.prototype.clone.call( this, data ); + ], [ - ib.meshPerAttribute = this.meshPerAttribute; + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate, - return ib; + ], [ - }, + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate, - toJSON: function ( data ) { + ] - const json = InterleavedBuffer.prototype.toJSON.call( this, data ); +]; - json.isInstancedInterleavedBuffer = true; - json.meshPerAttribute = this.meshPerAttribute; +/** + * + * 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. + */ - return json; +class AnimationObjectGroup { - } + constructor() { -} ); + this.isAnimationObjectGroup = true; -function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) { + this.uuid = generateUUID(); - this.buffer = buffer; - this.type = type; - this.itemSize = itemSize; - this.elementSize = elementSize; - this.count = count; + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); - this.version = 0; + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite -} + const indices = {}; + this._indicesByUUID = indices; // for bookkeeping -Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', { + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { - set: function ( value ) { + indices[ arguments[ i ].uuid ] = i; - if ( value === true ) this.version ++; + } - } + this._paths = []; // inside: string + this._parsedPaths = []; // inside: { we don't care, here } + this._bindings = []; // inside: Array< PropertyBinding > + this._bindingsIndicesByPath = {}; // inside: indices in these arrays -} ); + const scope = this; -Object.assign( GLBufferAttribute.prototype, { + this.stats = { - isGLBufferAttribute: true, + objects: { + get total() { - setBuffer: function ( buffer ) { + return scope._objects.length; - this.buffer = buffer; + }, + get inUse() { - return this; + return this.total - scope.nCachedObjects_; - }, + } + }, + get bindingsPerObject() { - setType: function ( type, elementSize ) { + return scope._bindings.length; - this.type = type; - this.elementSize = elementSize; + } - return this; + }; - }, + } - setItemSize: function ( itemSize ) { + add() { - this.itemSize = itemSize; + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; - return this; + let knownObject = undefined, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_; - }, + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { - setCount: function ( count ) { + const object = arguments[ i ], + uuid = object.uuid; + let index = indicesByUUID[ uuid ]; - this.count = count; + if ( index === undefined ) { - return this; + // 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 -function Raycaster( origin, direction, near = 0, far = Infinity ) { + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - this.ray = new Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); - this.near = near; - this.far = far; - this.camera = null; - this.layers = new Layers(); + } - this.params = { - Mesh: {}, - Line: { threshold: 1 }, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; + } else if ( index < nCachedObjects ) { - Object.defineProperties( this.params, { - PointCloud: { - get: function () { + knownObject = objects[ index ]; - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; + // move existing object to the ACTIVE region - } - } - } ); + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; -} + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; -function ascSort( a, b ) { + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; - return a.distance - b.distance; + // accounting is done, now do the same for all bindings -} + for ( let j = 0, m = nBindings; j !== m; ++ j ) { -function intersectObject( object, raycaster, intersects, recursive ) { + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ]; - if ( object.layers.test( raycaster.layers ) ) { + let binding = bindingsForPath[ index ]; - object.raycast( raycaster, intersects ); + bindingsForPath[ index ] = lastCached; - } + if ( binding === undefined ) { - if ( recursive === true ) { + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist - const children = object.children; + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); - for ( let i = 0, l = children.length; i < l; i ++ ) { + } - intersectObject( children[ i ], raycaster, intersects, true ); + bindingsForPath[ firstActiveIndex ] = binding; - } + } - } + } else if ( objects[ index ] !== knownObject ) { -} + console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); -Object.assign( Raycaster.prototype, { + } // else the object is already where we want it to be - set: function ( origin, direction ) { + } // for arguments - // direction is assumed to be normalized (for accurate distance calculations) + this.nCachedObjects_ = nCachedObjects; - this.ray.set( origin, direction ); + } - }, + remove() { - setFromCamera: function ( coords, camera ) { + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - if ( camera && camera.isPerspectiveCamera ) { + let nCachedObjects = this.nCachedObjects_; - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - this.camera = camera; + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { - } else if ( camera && camera.isOrthographicCamera ) { + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - 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 ); - this.camera = camera; + if ( index !== undefined && index >= nCachedObjects ) { - } else { + // move existing object into the CACHED region - console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); + const lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; - } + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; - }, + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; - intersectObject: function ( object, recursive = false, intersects = [] ) { + // accounting is done, now do the same for all bindings - intersectObject( object, this, intersects, recursive ); + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - intersects.sort( ascSort ); + const bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; - return intersects; + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; - }, + } - intersectObjects: function ( objects, recursive = false, intersects = [] ) { + } - for ( let i = 0, l = objects.length; i < l; i ++ ) { + } // for arguments - intersectObject( objects[ i ], this, intersects, recursive ); + this.nCachedObjects_ = nCachedObjects; - } + } - intersects.sort( ascSort ); + // remove & forget + uncache() { - return intersects; + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - } + let nCachedObjects = this.nCachedObjects_, + nObjects = objects.length; -} ); + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { -/** - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. - * The azimuthal angle (theta) is measured from the positive z-axis. - */ + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; -class Spherical { + if ( index !== undefined ) { - constructor( radius = 1, phi = 0, theta = 0 ) { + delete indicesByUUID[ uuid ]; - this.radius = radius; - this.phi = phi; // polar angle - this.theta = theta; // azimuthal angle + if ( index < nCachedObjects ) { - return this; + // object is cached, shrink the CACHED region - } + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - set( radius, phi, theta ) { + // last cached object takes this object's place + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - this.radius = radius; - this.phi = phi; - this.theta = theta; + // last object goes to the activated slot and pop + indicesByUUID[ lastObject.uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = lastObject; + objects.pop(); - return this; + // accounting is done, now do the same for all bindings - } + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - copy( other ) { + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; - this.radius = other.radius; - this.phi = other.phi; - this.theta = other.theta; + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); - return this; + } - } + } else { - // restrict phi to be betwee EPS and PI-EPS - makeSafe() { + // object is active, just swap with the last and pop - const EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + const lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - return this; + if ( lastIndex > 0 ) { - } + indicesByUUID[ lastObject.uuid ] = index; - setFromVector3( v ) { + } - return this.setFromCartesianCoords( v.x, v.y, v.z ); + objects[ index ] = lastObject; + objects.pop(); - } + // accounting is done, now do the same for all bindings - setFromCartesianCoords( x, y, z ) { + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - this.radius = Math.sqrt( x * x + y * y + z * z ); + const bindingsForPath = bindings[ j ]; - if ( this.radius === 0 ) { + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); - this.theta = 0; - this.phi = 0; + } - } else { + } // cached or active - this.theta = Math.atan2( x, z ); - this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) ); + } // if object is known - } + } // for arguments - return this; + this.nCachedObjects_ = nCachedObjects; } - clone() { + // Internal interface used by befriended PropertyBinding.Composite: - return new this.constructor().copy( this ); + subscribe_( path, parsedPath ) { - } + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group -} + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[ path ]; + const bindings = this._bindings; -/** - * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system - */ + if ( index !== undefined ) return bindings[ index ]; -class Cylindrical { + const paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); - constructor( radius = 1, theta = 0, y = 0 ) { + index = bindings.length; - this.radius = radius; // distance from the origin to a point in the x-z plane - this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis - this.y = y; // height above the x-z plane + indicesByPath[ path ] = index; - return this; + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); - } + for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { - set( radius, theta, y ) { + const object = objects[ i ]; + bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); - this.radius = radius; - this.theta = theta; - this.y = y; + } - return this; + return bindingsForPath; } - copy( other ) { - - this.radius = other.radius; - this.theta = other.theta; - this.y = other.y; - - return this; - - } + unsubscribe_( path ) { - setFromVector3( v ) { + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' - return this.setFromCartesianCoords( v.x, v.y, v.z ); + const indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; - } + if ( index !== undefined ) { - setFromCartesianCoords( x, y, z ) { + const paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; - this.radius = Math.sqrt( x * x + z * z ); - this.theta = Math.atan2( x, z ); - this.y = y; + indicesByPath[ lastBindingsPath ] = index; - return this; + bindings[ index ] = lastBindings; + bindings.pop(); - } + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); - clone() { + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); - return new this.constructor().copy( this ); + } } } -const _vector$8 = /*@__PURE__*/ new Vector2(); +class AnimationAction { -class Box2 { + constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { - constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; - this.min = min; - this.max = max; + const tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); - } + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; - set( min, max ) { + for ( let i = 0; i !== nTracks; ++ i ) { - this.min.copy( min ); - this.max.copy( max ); + const interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; - return this; + } - } + this._interpolantSettings = interpolantSettings; - setFromPoints( points ) { + this._interpolants = interpolants; // bound by the mixer - this.makeEmpty(); + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); - for ( let i = 0, il = points.length; i < il; i ++ ) { + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager - this.expandByPoint( points[ i ] ); + this._timeScaleInterpolant = null; + this._weightInterpolant = null; - } + this.loop = LoopRepeat; + this._loopCount = - 1; - return this; + // 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; - setFromCenterAndSize( center, size ) { + this.timeScale = 1; + this._effectiveTimeScale = 1; - const halfSize = _vector$8.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + this.weight = 1; + this._effectiveWeight = 1; - return this; + this.repetitions = Infinity; // no. of repetitions when looping - } + this.paused = false; // true -> zero effective time scale + this.enabled = true; // false -> zero effective weight - clone() { + this.clampWhenFinished = false;// keep feeding the last frame? - return new this.constructor().copy( this ); + this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true;// clips for start, loop and end } - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - } + // State & Scheduling - makeEmpty() { + play() { - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; + this._mixer._activateAction( this ); return this; } - isEmpty() { + stop() { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + this._mixer._deactivateAction( this ); - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + return this.reset(); } - getCenter( target ) { - - if ( target === undefined ) { + reset() { - console.warn( 'THREE.Box2: .getCenter() target is now required' ); - target = new Vector2(); + this.paused = false; + this.enabled = true; - } + this.time = 0; // restart clip + this._loopCount = - 1;// forget previous loops + this._startTime = null;// forget scheduling - return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + return this.stopFading().stopWarping(); } - getSize( target ) { + isRunning() { - if ( target === undefined ) { + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); - console.warn( 'THREE.Box2: .getSize() target is now required' ); - target = new Vector2(); + } - } + // return true when play has been called + isScheduled() { - return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + return this._mixer._isActiveAction( this ); } - expandByPoint( point ) { + startAt( time ) { - this.min.min( point ); - this.max.max( point ); + this._startTime = time; return this; } - expandByVector( vector ) { + setLoop( mode, repetitions ) { - this.min.sub( vector ); - this.max.add( vector ); + this.loop = mode; + this.repetitions = repetitions; return this; } - expandByScalar( scalar ) { - - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + // Weight - return this; + // 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( weight ) { - } + this.weight = weight; - containsPoint( point ) { + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ? false : true; + return this.stopFading(); } - containsBox( box ) { + // return the weight considering fading and .enabled + getEffectiveWeight() { - return 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._effectiveWeight; } - getParameter( point, target ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + fadeIn( duration ) { - if ( target === undefined ) { + return this._scheduleFading( duration, 0, 1 ); - console.warn( 'THREE.Box2: .getParameter() target is now required' ); - target = new Vector2(); + } - } + fadeOut( duration ) { - return target.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._scheduleFading( duration, 1, 0 ); } - intersectsBox( box ) { - - // using 4 splitting planes to rule out intersections + crossFadeFrom( fadeOutAction, duration, warp ) { - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); - } + if ( warp ) { - clampPoint( point, target ) { + const fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, - if ( target === undefined ) { + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; - console.warn( 'THREE.Box2: .clampPoint() target is now required' ); - target = new Vector2(); + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); } - return target.copy( point ).clamp( this.min, this.max ); + return this; } - distanceToPoint( point ) { + crossFadeTo( fadeInAction, duration, warp ) { - const clampedPoint = _vector$8.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + return fadeInAction.crossFadeFrom( this, duration, warp ); } - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); + stopFading() { - return this; + const weightInterpolant = this._weightInterpolant; - } + if ( weightInterpolant !== null ) { - union( box ) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); - this.min.min( box.min ); - this.max.max( box.max ); + } return this; } - translate( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; + // Time Scale Control - } + // set the time scale 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( timeScale ) { - equals( box ) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; - return box.min.equals( this.min ) && box.max.equals( this.max ); + return this.stopWarping(); } -} - -Box2.prototype.isBox2 = true; - -const _startP = /*@__PURE__*/ new Vector3(); -const _startEnd = /*@__PURE__*/ new Vector3(); - -class Line3 { - - constructor( start = new Vector3(), end = new Vector3() ) { + // return the time scale considering warping and .paused + getEffectiveTimeScale() { - this.start = start; - this.end = end; + return this._effectiveTimeScale; } - set( start, end ) { + setDuration( duration ) { - this.start.copy( start ); - this.end.copy( end ); + this.timeScale = this._clip.duration / duration; - return this; + return this.stopWarping(); } - copy( line ) { + syncWith( action ) { - this.start.copy( line.start ); - this.end.copy( line.end ); + this.time = action.time; + this.timeScale = action.timeScale; - return this; + return this.stopWarping(); } - getCenter( target ) { - - if ( target === undefined ) { + halt( duration ) { - console.warn( 'THREE.Line3: .getCenter() target is now required' ); - target = new Vector3(); + return this.warp( this._effectiveTimeScale, 0, duration ); - } + } - return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + warp( startTimeScale, endTimeScale, duration ) { - } + const mixer = this._mixer, + now = mixer.time, + timeScale = this.timeScale; - delta( target ) { + let interpolant = this._timeScaleInterpolant; - if ( target === undefined ) { + if ( interpolant === null ) { - console.warn( 'THREE.Line3: .delta() target is now required' ); - target = new Vector3(); + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; } - return target.subVectors( this.end, this.start ); + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; - } + times[ 0 ] = now; + times[ 1 ] = now + duration; - distanceSq() { + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; - return this.start.distanceToSquared( this.end ); + return this; } - distance() { - - return this.start.distanceTo( this.end ); - - } + stopWarping() { - at( t, target ) { + const timeScaleInterpolant = this._timeScaleInterpolant; - if ( target === undefined ) { + if ( timeScaleInterpolant !== null ) { - console.warn( 'THREE.Line3: .at() target is now required' ); - target = new Vector3(); + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); } - return this.delta( target ).multiplyScalar( t ).add( this.start ); + return this; } - closestPointToPointParameter( point, clampToLine ) { - - _startP.subVectors( point, this.start ); - _startEnd.subVectors( this.end, this.start ); - - const startEnd2 = _startEnd.dot( _startEnd ); - const startEnd_startP = _startEnd.dot( _startP ); - - let t = startEnd_startP / startEnd2; - - if ( clampToLine ) { - - t = MathUtils.clamp( t, 0, 1 ); + // Object Accessors - } + getMixer() { - return t; + return this._mixer; } - closestPointToPoint( point, clampToLine, target ) { - - const t = this.closestPointToPointParameter( point, clampToLine ); + getClip() { - if ( target === undefined ) { + return this._clip; - console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' ); - target = new Vector3(); + } - } + getRoot() { - return this.delta( target ).multiplyScalar( t ).add( this.start ); + return this._localRoot || this._mixer._root; } - applyMatrix4( matrix ) { - - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); - - return this; + // Interna - } + _update( time, deltaTime, timeDirection, accuIndex ) { - equals( line ) { + // called by the mixer - return line.start.equals( this.start ) && line.end.equals( this.end ); + if ( ! this.enabled ) { - } + // call ._updateWeight() to update ._effectiveWeight - clone() { + this._updateWeight( time ); + return; - return new this.constructor().copy( this ); + } - } + const startTime = this._startTime; -} + if ( startTime !== null ) { -function ImmediateRenderObject( material ) { + // check for scheduled start of action - Object3D.call( this ); + const timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { - this.material = material; - this.render = function ( /* renderCallback */ ) {}; + deltaTime = 0; - this.hasPositions = false; - this.hasNormals = false; - this.hasColors = false; - this.hasUvs = false; + } else { - this.positionArray = null; - this.normalArray = null; - this.colorArray = null; - this.uvArray = null; - this.count = 0; + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; -} + } -ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); -ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + } -ImmediateRenderObject.prototype.isImmediateRenderObject = true; + // apply time scale and advance time -const _vector$9 = /*@__PURE__*/ new Vector3(); + deltaTime *= this._updateTimeScale( time ); + const clipTime = this._updateTime( deltaTime ); -class SpotLightHelper extends Object3D { + // note: _updateTime may disable the action resulting in + // an effective weight of 0 - constructor( light, color ) { + const weight = this._updateWeight( time ); - super(); - this.light = light; - this.light.updateMatrixWorld(); + if ( weight > 0 ) { - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; - this.color = color; + switch ( this.blendMode ) { - const geometry = new BufferGeometry(); + case AdditiveAnimationBlendMode: - const 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 ( let j = 0, m = interpolants.length; j !== m; ++ j ) { - for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulateAdditive( weight ); - const p1 = ( i / l ) * Math.PI * 2; - const p2 = ( j / l ) * Math.PI * 2; + } - positions.push( - Math.cos( p1 ), Math.sin( p1 ), 1, - Math.cos( p2 ), Math.sin( p2 ), 1 - ); + break; - } + case NormalAnimationBlendMode: + default: - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { - const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); - this.cone = new LineSegments( geometry, material ); - this.add( this.cone ); + } - this.update(); + } + + } } - dispose() { + _updateWeight( time ) { - this.cone.geometry.dispose(); - this.cone.material.dispose(); + let weight = 0; - } + if ( this.enabled ) { - update() { + weight = this.weight; + const interpolant = this._weightInterpolant; - this.light.updateMatrixWorld(); + if ( interpolant !== null ) { - const coneLength = this.light.distance ? this.light.distance : 1000; - const coneWidth = coneLength * Math.tan( this.light.angle ); + const interpolantValue = interpolant.evaluate( time )[ 0 ]; - this.cone.scale.set( coneWidth, coneWidth, coneLength ); + weight *= interpolantValue; - _vector$9.setFromMatrixPosition( this.light.target.matrixWorld ); + if ( time > interpolant.parameterPositions[ 1 ] ) { - this.cone.lookAt( _vector$9 ); + this.stopFading(); - if ( this.color !== undefined ) { + if ( interpolantValue === 0 ) { - this.cone.material.color.set( this.color ); + // faded out, disable + this.enabled = false; - } else { + } - this.cone.material.color.copy( this.light.color ); + } + + } } + this._effectiveWeight = weight; + return weight; + } -} + _updateTimeScale( time ) { -const _vector$a = /*@__PURE__*/ new Vector3(); -const _boneMatrix = /*@__PURE__*/ new Matrix4(); -const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + let timeScale = 0; + if ( ! this.paused ) { -class SkeletonHelper extends LineSegments { + timeScale = this.timeScale; - constructor( object ) { + const interpolant = this._timeScaleInterpolant; - const bones = getBoneList( object ); + if ( interpolant !== null ) { - const geometry = new BufferGeometry(); + const interpolantValue = interpolant.evaluate( time )[ 0 ]; - const vertices = []; - const colors = []; + timeScale *= interpolantValue; - const color1 = new Color( 0, 0, 1 ); - const color2 = new Color( 0, 1, 0 ); + if ( time > interpolant.parameterPositions[ 1 ] ) { - for ( let i = 0; i < bones.length; i ++ ) { + this.stopWarping(); - const bone = bones[ i ]; + if ( timeScale === 0 ) { - if ( bone.parent && bone.parent.isBone ) { + // motion has halted, pause + this.paused = true; - vertices.push( 0, 0, 0 ); - vertices.push( 0, 0, 0 ); - colors.push( color1.r, color1.g, color1.b ); - colors.push( color2.r, color2.g, color2.b ); + } else { + + // warp done - apply final time scale + this.timeScale = timeScale; + + } + + } } } - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + this._effectiveTimeScale = timeScale; + return timeScale; - const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); + } - super( geometry, material ); + _updateTime( deltaTime ) { - this.type = 'SkeletonHelper'; - this.isSkeletonHelper = true; + const duration = this._clip.duration; + const loop = this.loop; - this.root = object; - this.bones = bones; + let time = this.time + deltaTime; + let loopCount = this._loopCount; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + const pingPong = ( loop === LoopPingPong ); - } + if ( deltaTime === 0 ) { - updateMatrixWorld( force ) { + if ( loopCount === - 1 ) return time; - const bones = this.bones; + return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; - const geometry = this.geometry; - const position = geometry.getAttribute( 'position' ); + } - _matrixWorldInv.copy( this.root.matrixWorld ).invert(); + if ( loop === LoopOnce ) { - for ( let i = 0, j = 0; i < bones.length; i ++ ) { + if ( loopCount === - 1 ) { - const bone = bones[ i ]; + // just started - if ( bone.parent && bone.parent.isBone ) { + this._loopCount = 0; + this._setEndings( true, true, false ); - _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); - _vector$a.setFromMatrixPosition( _boneMatrix ); - position.setXYZ( j, _vector$a.x, _vector$a.y, _vector$a.z ); + } - _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); - _vector$a.setFromMatrixPosition( _boneMatrix ); - position.setXYZ( j + 1, _vector$a.x, _vector$a.y, _vector$a.z ); + handle_stop: { - j += 2; + if ( time >= duration ) { - } + time = duration; - } + } else if ( time < 0 ) { - geometry.getAttribute( 'position' ).needsUpdate = true; + time = 0; - super.updateMatrixWorld( force ); + } else { - } + this.time = time; -} + break handle_stop; + } -function getBoneList( object ) { + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - const boneList = []; + this.time = time; - if ( object && object.isBone ) { + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? - 1 : 1 + } ); - boneList.push( object ); + } - } + } else { // repetitive Repeat or PingPong - for ( let i = 0; i < object.children.length; i ++ ) { + if ( loopCount === - 1 ) { - boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); + // just started - } + if ( deltaTime >= 0 ) { - return boneList; + loopCount = 0; -} + this._setEndings( true, this.repetitions === 0, pingPong ); -class PointLightHelper extends Mesh { + } else { - constructor( light, sphereSize, color ) { + // when looping in reverse direction, the initial + // transition through zero counts as a repetition, + // so leave loopCount at -1 - const geometry = new SphereGeometry( sphereSize, 4, 2 ); - const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + this._setEndings( this.repetitions === 0, true, pingPong ); - super( geometry, material ); + } - this.light = light; - this.light.updateMatrixWorld(); + } - this.color = color; + if ( time >= duration || time < 0 ) { - this.type = 'PointLightHelper'; + // wrap around - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + const loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; - this.update(); + loopCount += Math.abs( loopDelta ); + const pending = this.repetitions - loopCount; - /* - // TODO: delete this comment? - const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 ); - const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + if ( pending <= 0 ) { - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + // have to stop (switch state, clamp time, fire event) - const d = light.distance; + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - if ( d === 0.0 ) { + time = deltaTime > 0 ? duration : 0; - this.lightDistance.visible = false; + this.time = time; - } else { + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : - 1 + } ); - this.lightDistance.scale.set( d, d, d ); + } else { - } + // keep running - this.add( this.lightDistance ); - */ + if ( pending === 1 ) { - } + // entering the last round - dispose() { + const atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); - this.geometry.dispose(); - this.material.dispose(); + } else { - } + this._setEndings( false, false, pingPong ); - update() { + } - if ( this.color !== undefined ) { + this._loopCount = loopCount; - this.material.color.set( this.color ); + this.time = time; - } else { + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); - this.material.color.copy( this.light.color ); + } - } + } else { - /* - const d = this.light.distance; + this.time = time; - if ( d === 0.0 ) { + } - this.lightDistance.visible = false; + if ( pingPong && ( loopCount & 1 ) === 1 ) { - } else { + // invert time for the "pong round" - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + return duration - time; + + } } - */ + + return time; } -} + _setEndings( atStart, atEnd, pingPong ) { -const _vector$b = /*@__PURE__*/ new Vector3(); -const _color1 = /*@__PURE__*/ new Color(); -const _color2 = /*@__PURE__*/ new Color(); + const settings = this._interpolantSettings; -class HemisphereLightHelper extends Object3D { + if ( pingPong ) { - constructor( light, size, color ) { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; - super(); - this.light = light; - this.light.updateMatrixWorld(); + } else { - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + // assuming for LoopOnce atStart == atEnd == true - this.color = color; + if ( atStart ) { - const geometry = new OctahedronGeometry( size ); - geometry.rotateY( Math.PI * 0.5 ); + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; - this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); - if ( this.color === undefined ) this.material.vertexColors = true; + } else { - const position = geometry.getAttribute( 'position' ); - const colors = new Float32Array( position.count * 3 ); + settings.endingStart = WrapAroundEnding; - geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); + } - this.add( new Mesh( geometry, this.material ) ); + if ( atEnd ) { - this.update(); + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; - } + } else { - dispose() { + settings.endingEnd = WrapAroundEnding; - this.children[ 0 ].geometry.dispose(); - this.children[ 0 ].material.dispose(); + } + + } } - update() { + _scheduleFading( duration, weightNow, weightThen ) { - const mesh = this.children[ 0 ]; + const mixer = this._mixer, now = mixer.time; + let interpolant = this._weightInterpolant; - if ( this.color !== undefined ) { + if ( interpolant === null ) { - this.material.color.set( this.color ); + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; - } else { + } - const colors = mesh.geometry.getAttribute( 'color' ); + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; - _color1.copy( this.light.color ); - _color2.copy( this.light.groundColor ); + times[ 0 ] = now; + values[ 0 ] = weightNow; + times[ 1 ] = now + duration; + values[ 1 ] = weightThen; - for ( let i = 0, l = colors.count; i < l; i ++ ) { + return this; - const color = ( i < ( l / 2 ) ) ? _color1 : _color2; + } - colors.setXYZ( i, color.r, color.g, color.b ); +} - } +const _controlInterpolantsResultBuffer = new Float32Array( 1 ); - colors.needsUpdate = true; - } +class AnimationMixer extends EventDispatcher { - mesh.lookAt( _vector$b.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + constructor( root ) { - } + super(); -} + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1.0; -class GridHelper extends LineSegments { + } - constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { + _bindAction( action, prototypeAction ) { - color1 = new Color( color1 ); - color2 = new Color( color2 ); + const root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName; - const center = divisions / 2; - const step = size / divisions; - const halfSize = size / 2; + let bindingsByName = bindingsByRoot[ rootUuid ]; - const vertices = [], colors = []; + if ( bindingsByName === undefined ) { - for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; - vertices.push( - halfSize, 0, k, halfSize, 0, k ); - vertices.push( k, 0, - halfSize, k, 0, halfSize ); + } - const color = i === center ? color1 : color2; + for ( let i = 0; i !== nTracks; ++ i ) { - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; + const track = tracks[ i ], + trackName = track.name; - } + let binding = bindingsByName[ trackName ]; - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + if ( binding !== undefined ) { - const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + ++ binding.referenceCount; + bindings[ i ] = binding; - super( geometry, material ); + } else { - this.type = 'GridHelper'; + binding = bindings[ i ]; - } + if ( binding !== undefined ) { -} + // existing binding, make sure the cache knows -class PolarGridHelper extends LineSegments { + if ( binding._cacheIndex === null ) { - constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - color1 = new Color( color1 ); - color2 = new Color( color2 ); + } - const vertices = []; - const colors = []; + continue; - // create the radials + } - for ( let i = 0; i <= radials; i ++ ) { + const path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; - const v = ( i / radials ) * ( Math.PI * 2 ); + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); - const x = Math.sin( v ) * radius; - const z = Math.cos( v ) * radius; + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - vertices.push( 0, 0, 0 ); - vertices.push( x, 0, z ); + bindings[ i ] = binding; - const color = ( i & 1 ) ? color1 : color2; + } - colors.push( color.r, color.g, color.b ); - colors.push( color.r, color.g, color.b ); + interpolants[ i ].resultBuffer = binding.buffer; } - // create the circles - - for ( let i = 0; i <= circles; i ++ ) { + } - const color = ( i & 1 ) ? color1 : color2; + _activateAction( action ) { - const r = radius - ( radius / circles * i ); + if ( ! this._isActiveAction( action ) ) { - for ( let j = 0; j < divisions; j ++ ) { + if ( action._cacheIndex === null ) { - // first vertex + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind - let v = ( j / divisions ) * ( Math.PI * 2 ); + const rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; - let x = Math.sin( v ) * r; - let z = Math.cos( v ) * r; + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); - vertices.push( x, 0, z ); - colors.push( color.r, color.g, color.b ); + this._addInactiveAction( action, clipUuid, rootUuid ); - // second vertex + } - v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); + const bindings = action._propertyBindings; - x = Math.sin( v ) * r; - z = Math.cos( v ) * r; + // increment reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { - vertices.push( x, 0, z ); - colors.push( color.r, color.g, color.b ); + const binding = bindings[ i ]; - } + if ( binding.useCount ++ === 0 ) { - } + this._lendBinding( binding ); + binding.saveOriginalState(); - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + } - const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + } - super( geometry, material ); + this._lendAction( action ); - this.type = 'PolarGridHelper'; + } } -} - -const _v1$6 = /*@__PURE__*/ new Vector3(); -const _v2$3 = /*@__PURE__*/ new Vector3(); -const _v3$1 = /*@__PURE__*/ new Vector3(); + _deactivateAction( action ) { -class DirectionalLightHelper extends Object3D { + if ( this._isActiveAction( action ) ) { - constructor( light, size, color ) { + const bindings = action._propertyBindings; - super(); - this.light = light; - this.light.updateMatrixWorld(); + // decrement reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + const binding = bindings[ i ]; - this.color = color; + if ( -- binding.useCount === 0 ) { - if ( size === undefined ) size = 1; + binding.restoreOriginalState(); + this._takeBackBinding( binding ); - let geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( [ - - size, size, 0, - size, size, 0, - size, - size, 0, - - size, - size, 0, - - size, size, 0 - ], 3 ) ); + } - const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + } - this.lightPlane = new Line( geometry, material ); - this.add( this.lightPlane ); + this._takeBackAction( action ); - geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + } - this.targetLine = new Line( geometry, material ); - this.add( this.targetLine ); + } - this.update(); + // Memory manager - } + _initMemoryManager() { - dispose() { + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; - this.lightPlane.geometry.dispose(); - this.lightPlane.material.dispose(); - this.targetLine.geometry.dispose(); - this.targetLine.material.dispose(); + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< AnimationAction > - used as prototypes + // actionByRoot: AnimationAction - lookup + // } - } - update() { + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; - _v1$6.setFromMatrixPosition( this.light.matrixWorld ); - _v2$3.setFromMatrixPosition( this.light.target.matrixWorld ); - _v3$1.subVectors( _v2$3, _v1$6 ); + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > - this.lightPlane.lookAt( _v2$3 ); - if ( this.color !== undefined ) { + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; - this.lightPlane.material.color.set( this.color ); - this.targetLine.material.color.set( this.color ); + const scope = this; - } else { + this.stats = { - this.lightPlane.material.color.copy( this.light.color ); - this.targetLine.material.color.copy( this.light.color ); + actions: { + get total() { - } + return scope._actions.length; - this.targetLine.lookAt( _v2$3 ); - this.targetLine.scale.z = _v3$1.length(); + }, + get inUse() { - } + return scope._nActiveActions; -} + } + }, + bindings: { + get total() { -const _vector$c = /*@__PURE__*/ new Vector3(); -const _camera = /*@__PURE__*/ new Camera(); + return scope._bindings.length; -/** - * - 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 - */ + }, + get inUse() { -class CameraHelper extends LineSegments { + return scope._nActiveBindings; - constructor( camera ) { + } + }, + controlInterpolants: { + get total() { - const geometry = new BufferGeometry(); - const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); + return scope._controlInterpolants.length; - const vertices = []; - const colors = []; + }, + get inUse() { - const pointMap = {}; + return scope._nActiveControlInterpolants; - // colors + } + } - const colorFrustum = new Color( 0xffaa00 ); - const colorCone = new Color( 0xff0000 ); - const colorUp = new Color( 0x00aaff ); - const colorTarget = new Color( 0xffffff ); - const colorCross = new Color( 0x333333 ); + }; - // near + } - addLine( 'n1', 'n2', colorFrustum ); - addLine( 'n2', 'n4', colorFrustum ); - addLine( 'n4', 'n3', colorFrustum ); - addLine( 'n3', 'n1', colorFrustum ); + // Memory management for AnimationAction objects - // far + _isActiveAction( action ) { - addLine( 'f1', 'f2', colorFrustum ); - addLine( 'f2', 'f4', colorFrustum ); - addLine( 'f4', 'f3', colorFrustum ); - addLine( 'f3', 'f1', colorFrustum ); + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; - // sides + } - addLine( 'n1', 'f1', colorFrustum ); - addLine( 'n2', 'f2', colorFrustum ); - addLine( 'n3', 'f3', colorFrustum ); - addLine( 'n4', 'f4', colorFrustum ); + _addInactiveAction( action, clipUuid, rootUuid ) { - // cone + const actions = this._actions, + actionsByClip = this._actionsByClip; - addLine( 'p', 'n1', colorCone ); - addLine( 'p', 'n2', colorCone ); - addLine( 'p', 'n3', colorCone ); - addLine( 'p', 'n4', colorCone ); + let actionsForClip = actionsByClip[ clipUuid ]; - // up + if ( actionsForClip === undefined ) { - addLine( 'u1', 'u2', colorUp ); - addLine( 'u2', 'u3', colorUp ); - addLine( 'u3', 'u1', colorUp ); + actionsForClip = { - // target + knownActions: [ action ], + actionByRoot: {} - addLine( 'c', 't', colorTarget ); - addLine( 'p', 'c', colorCross ); + }; - // cross + action._byClipCacheIndex = 0; - addLine( 'cn1', 'cn2', colorCross ); - addLine( 'cn3', 'cn4', colorCross ); + actionsByClip[ clipUuid ] = actionsForClip; - addLine( 'cf1', 'cf2', colorCross ); - addLine( 'cf3', 'cf4', colorCross ); + } else { - function addLine( a, b, color ) { + const knownActions = actionsForClip.knownActions; - addPoint( a, color ); - addPoint( b, color ); + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); } - function addPoint( id, color ) { + action._cacheIndex = actions.length; + actions.push( action ); - vertices.push( 0, 0, 0 ); - colors.push( color.r, color.g, color.b ); + actionsForClip.actionByRoot[ rootUuid ] = action; - if ( pointMap[ id ] === undefined ) { + } - pointMap[ id ] = []; + _removeInactiveAction( action ) { - } + const actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; - pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - } + action._cacheIndex = null; - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - super( geometry, material ); + const clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, - this.type = 'CameraHelper'; + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], - this.camera = camera; - if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + byClipCacheIndex = action._byClipCacheIndex; - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); - this.pointMap = pointMap; + action._byClipCacheIndex = null; - this.update(); - } + const actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( action._localRoot || this._root ).uuid; - update() { + delete actionByRoot[ rootUuid ]; - const geometry = this.geometry; - const pointMap = this.pointMap; + if ( knownActionsForClip.length === 0 ) { - const w = 1, h = 1; + delete actionsByClip[ clipUuid ]; - // we need just camera projection matrix inverse - // world matrix must be identity + } - _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); + this._removeInactiveBindingsForAction( action ); - // center / target + } - setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); - setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); + _removeInactiveBindingsForAction( action ) { - // near + const bindings = action._propertyBindings; - setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); - setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); - setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); - setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { - // far + const binding = bindings[ i ]; - setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); - setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); - setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); - setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); + if ( -- binding.referenceCount === 0 ) { - // up + this._removeInactiveBinding( binding ); - setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); - setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); - setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); + } - // cross + } - setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); - setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); - setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); - setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); + } - setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); - setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); - setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); - setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); + _lendAction( action ) { - geometry.getAttribute( 'position' ).needsUpdate = true; + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s - } + const actions = this._actions, + prevIndex = action._cacheIndex, -} + lastActiveIndex = this._nActiveActions ++, + firstInactiveAction = actions[ lastActiveIndex ]; -function setPoint( point, pointMap, geometry, camera, x, y, z ) { + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; - _vector$c.set( x, y, z ).unproject( camera ); + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; - const points = pointMap[ point ]; + } - if ( points !== undefined ) { + _takeBackAction( action ) { - const position = geometry.getAttribute( 'position' ); + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a - for ( let i = 0, l = points.length; i < l; i ++ ) { + const actions = this._actions, + prevIndex = action._cacheIndex, - position.setXYZ( points[ i ], _vector$c.x, _vector$c.y, _vector$c.z ); + firstInactiveIndex = -- this._nActiveActions, - } + lastActiveAction = actions[ firstInactiveIndex ]; - } + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; -} + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; -const _box$3 = /*@__PURE__*/ new Box3(); + } -class BoxHelper extends LineSegments { + // Memory management for PropertyMixer objects - constructor( object, color = 0xffff00 ) { + _addInactiveBinding( binding, rootUuid, trackName ) { - const 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 ] ); - const positions = new Float32Array( 8 * 3 ); + const bindingsByRoot = this._bindingsByRootAndName, + bindings = this._bindings; - const geometry = new BufferGeometry(); - geometry.setIndex( new BufferAttribute( indices, 1 ) ); - geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + let bindingByName = bindingsByRoot[ rootUuid ]; - super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + if ( bindingByName === undefined ) { - this.object = object; - this.type = 'BoxHelper'; + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; - this.matrixAutoUpdate = false; + } - this.update(); + bindingByName[ trackName ] = binding; + + binding._cacheIndex = bindings.length; + bindings.push( binding ); } - update( object ) { + _removeInactiveBinding( binding ) { - if ( object !== undefined ) { + const bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; - } + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); - if ( this.object !== undefined ) { + delete bindingByName[ trackName ]; + + if ( Object.keys( bindingByName ).length === 0 ) { - _box$3.setFromObject( this.object ); + delete bindingsByRoot[ rootUuid ]; } - if ( _box$3.isEmpty() ) return; + } - const min = _box$3.min; - const max = _box$3.max; + _lendBinding( binding ) { - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ + const bindings = this._bindings, + prevIndex = binding._cacheIndex, - 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 - */ + lastActiveIndex = this._nActiveBindings ++, - const position = this.geometry.attributes.position; - const array = position.array; + firstInactiveBinding = bindings[ lastActiveIndex ]; - 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; + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; - position.needsUpdate = true; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; - this.geometry.computeBoundingSphere(); + } + _takeBackBinding( binding ) { - } + const bindings = this._bindings, + prevIndex = binding._cacheIndex, - setFromObject( object ) { + firstInactiveIndex = -- this._nActiveBindings, - this.object = object; - this.update(); + lastActiveBinding = bindings[ firstInactiveIndex ]; - return this; + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; + + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; } - copy( source ) { - LineSegments.prototype.copy.call( this, source ); + // Memory management of Interpolants for weight and time scale - this.object = source.object; + _lendControlInterpolant() { - return this; + const interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++; - } + let interpolant = interpolants[ lastActiveIndex ]; -} + if ( interpolant === undefined ) { -class Box3Helper extends LineSegments { + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, _controlInterpolantsResultBuffer ); - constructor( box, color = 0xffff00 ) { + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; - const 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 ] ); + } - const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; + return interpolant; - const geometry = new BufferGeometry(); + } - geometry.setIndex( new BufferAttribute( indices, 1 ) ); + _takeBackControlInterpolant( interpolant ) { - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + const interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, - super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + firstInactiveIndex = -- this._nActiveControlInterpolants, - this.box = box; + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; - this.type = 'Box3Helper'; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; - this.geometry.computeBoundingSphere(); + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; } - updateMatrixWorld( force ) { + // 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( clip, optionalRoot, blendMode ) { - const box = this.box; + const root = optionalRoot || this._root, + rootUuid = root.uuid; - if ( box.isEmpty() ) return; + let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; - box.getCenter( this.position ); + const clipUuid = clipObject !== null ? clipObject.uuid : clip; - box.getSize( this.scale ); + const actionsForClip = this._actionsByClip[ clipUuid ]; + let prototypeAction = null; - this.scale.multiplyScalar( 0.5 ); + if ( blendMode === undefined ) { - super.updateMatrixWorld( force ); + if ( clipObject !== null ) { - } + blendMode = clipObject.blendMode; -} + } else { -class PlaneHelper extends Line { + blendMode = NormalAnimationBlendMode; - constructor( plane, size = 1, hex = 0xffff00 ) { + } - const color = hex; + } - const positions = [ 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, 0, 1, 0, 0, 0 ]; + if ( actionsForClip !== undefined ) { - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); - geometry.computeBoundingSphere(); + const existingAction = actionsForClip.actionByRoot[ rootUuid ]; - super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { - this.type = 'PlaneHelper'; + return existingAction; - this.plane = plane; + } - this.size = size; + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; - const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ]; + // also, take the clip from the prototype action + if ( clipObject === null ) + clipObject = prototypeAction._clip; - const geometry2 = new BufferGeometry(); - geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); - geometry2.computeBoundingSphere(); + } - this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); + // clip must be known when specified via string + if ( clipObject === null ) return null; - } + // allocate all resources required to run it + const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); - updateMatrixWorld( force ) { + this._bindAction( newAction, prototypeAction ); - let scale = - this.plane.constant; + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); - if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter + return newAction; - this.scale.set( 0.5 * this.size, 0.5 * this.size, scale ); + } - this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here + // get an existing action + existingAction( clip, optionalRoot ) { - this.lookAt( this.plane.normal ); + const root = optionalRoot || this._root, + rootUuid = root.uuid, - super.updateMatrixWorld( force ); + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - } + clipUuid = clipObject ? clipObject.uuid : clip, -} + actionsForClip = this._actionsByClip[ clipUuid ]; -const _axis = /*@__PURE__*/ new Vector3(); -let _lineGeometry, _coneGeometry; + if ( actionsForClip !== undefined ) { -class ArrowHelper extends Object3D { + return actionsForClip.actionByRoot[ rootUuid ] || null; - // dir is assumed to be normalized + } - constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + return null; - super(); + } - this.type = 'ArrowHelper'; + // deactivates all previously scheduled actions + stopAllAction() { - if ( _lineGeometry === undefined ) { + const actions = this._actions, + nActions = this._nActiveActions; - _lineGeometry = new BufferGeometry(); - _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + for ( let i = nActions - 1; i >= 0; -- i ) { - _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 ); - _coneGeometry.translate( 0, - 0.5, 0 ); + actions[ i ].stop(); } - this.position.copy( origin ); + return this; - this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + } - this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + // advance the time and update apply the animation + update( deltaTime ) { - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + deltaTime *= this.timeScale; - } + const actions = this._actions, + nActions = this._nActiveActions, - setDirection( dir ) { + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), - // dir is assumed to be normalized + accuIndex = this._accuIndex ^= 1; - if ( dir.y > 0.99999 ) { + // run active actions - this.quaternion.set( 0, 0, 0, 1 ); + for ( let i = 0; i !== nActions; ++ i ) { - } else if ( dir.y < - 0.99999 ) { + const action = actions[ i ]; - this.quaternion.set( 1, 0, 0, 0 ); + action._update( time, deltaTime, timeDirection, accuIndex ); - } else { + } - _axis.set( dir.z, 0, - dir.x ).normalize(); + // update scene graph - const radians = Math.acos( dir.y ); + const bindings = this._bindings, + nBindings = this._nActiveBindings; + + for ( let i = 0; i !== nBindings; ++ i ) { - this.quaternion.setFromAxisAngle( _axis, radians ); + bindings[ i ].apply( accuIndex ); } + return this; + } - setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + // Allows you to seek to a specific time in an animation. + setTime( timeInSeconds ) { - this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 - this.line.updateMatrix(); + this.time = 0; // Zero out time attribute for AnimationMixer object; + for ( let i = 0; i < this._actions.length; i ++ ) { - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); + this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + + } + + return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. } - setColor( color ) { + // return this mixer's root target object + getRoot() { - this.line.material.color.set( color ); - this.cone.material.color.set( color ); + return this._root; } - copy( source ) { - - super.copy( source, false ); + // free all resources specific to a particular clip + uncacheClip( clip ) { - this.line.copy( source.line ); - this.cone.copy( source.cone ); + const actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - return this; + if ( actionsForClip !== undefined ) { - } + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away -} + const actionsToRemove = actionsForClip.knownActions; -class AxesHelper extends LineSegments { + for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { - constructor( size = 1 ) { + const action = actionsToRemove[ i ]; - const vertices = [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ]; + this._deactivateAction( action ); - const colors = [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 - ]; + const cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + action._cacheIndex = null; + action._byClipCacheIndex = null; - const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - super( geometry, material ); + this._removeInactiveBindingsForAction( action ); - this.type = 'AxesHelper'; + } - } + delete actionsByClip[ clipUuid ]; -} + } -const _floatView = new Float32Array( 1 ); -const _int32View = new Int32Array( _floatView.buffer ); + } -const DataUtils = { + // free all resources specific to a particular root target object + uncacheRoot( root ) { - // Converts float32 to float16 (stored as uint16 value). + const rootUuid = root.uuid, + actionsByClip = this._actionsByClip; - toHalfFloat: function ( val ) { + for ( const clipUuid in actionsByClip ) { - // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410 + const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; - /* This method is faster than the OpenEXR implementation (very often - * used, eg. in Ogre), with the additional benefit of rounding, inspired - * by James Tursa?s half-precision code. */ + if ( action !== undefined ) { - _floatView[ 0 ] = val; - const x = _int32View[ 0 ]; + this._deactivateAction( action ); + this._removeInactiveAction( action ); - let bits = ( x >> 16 ) & 0x8000; /* Get the sign */ - let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */ - const e = ( x >> 23 ) & 0xff; /* Using int is faster here */ + } - /* If zero, or denormal, or exponent underflows too much for a denormal - * half, return signed zero. */ - if ( e < 103 ) return bits; + } - /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */ - if ( e > 142 ) { + const bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; - bits |= 0x7c00; - /* If exponent was 0xff and one mantissa bit was set, it means NaN, - * not Inf, so make sure we set one mantissa bit too. */ - bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff ); - return bits; + if ( bindingByName !== undefined ) { - } + for ( const trackName in bindingByName ) { - /* If exponent underflows but not too much, return a denormal */ - if ( e < 113 ) { + const binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); - m |= 0x0800; - /* Extra rounding may overflow and set mantissa to 0 and exponent - * to 1, which is OK. */ - bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 ); - return bits; + } } - bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 ); - /* Extra rounding. An overflow will set mantissa to 0 and increment - * the exponent, which is OK. */ - bits += m & 1; - return bits; - } -}; + // remove a targeted clip from the cache + uncacheAction( clip, optionalRoot ) { -const LOD_MIN = 4; -const LOD_MAX = 8; -const SIZE_MAX = Math.pow( 2, LOD_MAX ); + const action = this.existingAction( clip, optionalRoot ); -// The standard deviations (radians) associated with the extra mips. These are -// chosen to approximate a Trowbridge-Reitz distribution function times the -// geometric shadowing function. These sigma values squared must match the -// variance #defines in cube_uv_reflection_fragment.glsl.js. -const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + if ( action !== null ) { -const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + this._deactivateAction( action ); + this._removeInactiveAction( action ); -// The maximum length of the blur for loop. Smaller sigmas will use fewer -// samples and exit early, but not recompile the shader. -const MAX_SAMPLES = 20; + } -const ENCODINGS = { - [ LinearEncoding ]: 0, - [ sRGBEncoding ]: 1, - [ RGBEEncoding ]: 2, - [ RGBM7Encoding ]: 3, - [ RGBM16Encoding ]: 4, - [ RGBDEncoding ]: 5, - [ GammaEncoding ]: 6 -}; + } -const backgroundMaterial = new MeshBasicMaterial( { - side: BackSide, - depthWrite: false, - depthTest: false, -} ); -const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); +} -const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); -const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes(); -const _clearColor = /*@__PURE__*/ new Color(); -let _oldTarget = null; +class Uniform { -// Golden Ratio -const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; -const INV_PHI = 1 / PHI; + constructor( value ) { -// Vertices of a dodecahedron (except the opposites, which represent the -// same axis), used as axis directions evenly spread on a sphere. -const _axisDirections = [ - /*@__PURE__*/ new Vector3( 1, 1, 1 ), - /*@__PURE__*/ new Vector3( - 1, 1, 1 ), - /*@__PURE__*/ new Vector3( 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), - /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), - /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), - /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; + this.value = value; -/** - * This class generates a Prefiltered, Mipmapped Radiance Environment Map - * (PMREM) from a cubeMap environment texture. This allows different levels of - * blur to be quickly accessed based on material roughness. It is packed into a - * special CubeUV format that allows us to perform custom interpolation so that - * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap - * chain, it only goes down to the LOD_MIN level (above), and then creates extra - * even more filtered 'mips' at the same LOD_MIN resolution, associated with - * higher roughness levels. In this way we maintain resolution to smoothly - * interpolate diffuse lighting while limiting sampling computation. - */ + } -function convertLinearToRGBE( color ) { + clone() { - const maxComponent = Math.max( color.r, color.g, color.b ); - const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 ); - color.multiplyScalar( Math.pow( 2.0, - fExp ) ); + return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); - const alpha = ( fExp + 128.0 ) / 255.0; - return alpha; + } } -class PMREMGenerator { - - constructor( renderer ) { +let id = 0; - this._renderer = renderer; - this._pingPongRenderTarget = null; +class UniformsGroup extends EventDispatcher { - this._blurMaterial = _getBlurShader( MAX_SAMPLES ); - this._equirectShader = null; - this._cubemapShader = null; + constructor() { - this._compileMaterial( this._blurMaterial ); + super(); - } + this.isUniformsGroup = true; - /** - * Generates a PMREM from a supplied Scene, which can be faster than using an - * image if networking bandwidth is low. Optional sigma specifies a blur radius - * in radians to be applied to the scene before PMREM generation. Optional near - * and far planes ensure the scene is rendered in its entirety (the cubeCamera - * is placed at the origin). - */ - fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { + Object.defineProperty( this, 'id', { value: id ++ } ); - _oldTarget = this._renderer.getRenderTarget(); - const cubeUVRenderTarget = this._allocateTargets(); + this.name = ''; - this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); - if ( sigma > 0 ) { + this.usage = StaticDrawUsage; + this.uniforms = []; - this._blur( cubeUVRenderTarget, 0, 0, sigma ); + } - } + add( uniform ) { - this._applyPMREM( cubeUVRenderTarget ); - this._cleanup( cubeUVRenderTarget ); + this.uniforms.push( uniform ); - return cubeUVRenderTarget; + return this; } - /** - * Generates a PMREM from an equirectangular texture, which can be either LDR - * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512), - * as this matches best with the 256 x 256 cubemap output. - */ - fromEquirectangular( equirectangular ) { - - return this._fromTexture( equirectangular ); + remove( uniform ) { - } + const index = this.uniforms.indexOf( uniform ); - /** - * Generates a PMREM from an cubemap texture, which can be either LDR - * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256, - * as this matches best with the 256 x 256 cubemap output. - */ - fromCubemap( cubemap ) { + if ( index !== - 1 ) this.uniforms.splice( index, 1 ); - return this._fromTexture( cubemap ); + return this; } - /** - * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - compileCubemapShader() { - - if ( this._cubemapShader === null ) { + setName( name ) { - this._cubemapShader = _getCubemapShader(); - this._compileMaterial( this._cubemapShader ); + this.name = name; - } + return this; } - /** - * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - compileEquirectangularShader() { - - if ( this._equirectShader === null ) { + setUsage( value ) { - this._equirectShader = _getEquirectShader(); - this._compileMaterial( this._equirectShader ); + this.usage = value; - } + return this; } - /** - * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, - * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on - * one of them will cause any others to also become unusable. - */ dispose() { - this._blurMaterial.dispose(); + this.dispatchEvent( { type: 'dispose' } ); + + return this; + + } - if ( this._cubemapShader !== null ) this._cubemapShader.dispose(); - if ( this._equirectShader !== null ) this._equirectShader.dispose(); + copy( source ) { - for ( let i = 0; i < _lodPlanes.length; i ++ ) { + this.name = source.name; + this.usage = source.usage; - _lodPlanes[ i ].dispose(); + const uniformsSource = source.uniforms; - } + this.uniforms.length = 0; - } + for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) { - // private interface + this.uniforms.push( uniformsSource[ i ].clone() ); - _cleanup( outputTarget ) { + } - this._pingPongRenderTarget.dispose(); - this._renderer.setRenderTarget( _oldTarget ); - outputTarget.scissorTest = false; - _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + return this; } - _fromTexture( texture ) { - - _oldTarget = this._renderer.getRenderTarget(); - const cubeUVRenderTarget = this._allocateTargets( texture ); - this._textureToCubeUV( texture, cubeUVRenderTarget ); - this._applyPMREM( cubeUVRenderTarget ); - this._cleanup( cubeUVRenderTarget ); + clone() { - return cubeUVRenderTarget; + return new this.constructor().copy( this ); } - _allocateTargets( texture ) { // warning: null texture is valid +} - const params = { - magFilter: NearestFilter, - minFilter: NearestFilter, - generateMipmaps: false, - type: UnsignedByteType, - format: RGBEFormat, - encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding, - depthBuffer: false - }; +class InstancedInterleavedBuffer extends InterleavedBuffer { - const cubeUVRenderTarget = _createRenderTarget( params ); - cubeUVRenderTarget.depthBuffer = texture ? false : true; - this._pingPongRenderTarget = _createRenderTarget( params ); - return cubeUVRenderTarget; + constructor( array, stride, meshPerAttribute = 1 ) { - } + super( array, stride ); - _compileMaterial( material ) { + this.isInstancedInterleavedBuffer = true; - const tmpMesh = new Mesh( _lodPlanes[ 0 ], material ); - this._renderer.compile( tmpMesh, _flatCamera ); + this.meshPerAttribute = meshPerAttribute; } - _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { - - const fov = 90; - const aspect = 1; - const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); - const upSign = [ 1, - 1, 1, 1, 1, 1 ]; - const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; - const renderer = this._renderer; + copy( source ) { - const originalAutoClear = renderer.autoClear; - const outputEncoding = renderer.outputEncoding; - const toneMapping = renderer.toneMapping; - renderer.getClearColor( _clearColor ); + super.copy( source ); - renderer.toneMapping = NoToneMapping; - renderer.outputEncoding = LinearEncoding; - renderer.autoClear = false; + this.meshPerAttribute = source.meshPerAttribute; - let useSolidColor = false; - const background = scene.background; - if ( background ) { + return this; - if ( background.isColor ) { + } - backgroundMaterial.color.copy( background ).convertSRGBToLinear(); - scene.background = null; + clone( data ) { - const alpha = convertLinearToRGBE( backgroundMaterial.color ); - backgroundMaterial.opacity = alpha; - useSolidColor = true; + const ib = super.clone( data ); - } + ib.meshPerAttribute = this.meshPerAttribute; - } else { + return ib; - backgroundMaterial.color.copy( _clearColor ).convertSRGBToLinear(); + } - const alpha = convertLinearToRGBE( backgroundMaterial.color ); - backgroundMaterial.opacity = alpha; - useSolidColor = true; + toJSON( data ) { - } + const json = super.toJSON( data ); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; - for ( let i = 0; i < 6; i ++ ) { + return json; - const col = i % 3; - if ( col == 0 ) { + } - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); +} - } else if ( col == 1 ) { +class GLBufferAttribute { - cubeCamera.up.set( 0, 0, upSign[ i ] ); - cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + constructor( buffer, type, itemSize, elementSize, count ) { - } else { + this.isGLBufferAttribute = true; - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; - } + this.version = 0; - _setViewport( cubeUVRenderTarget, - col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX ); - renderer.setRenderTarget( cubeUVRenderTarget ); + } - if ( useSolidColor ) { + set needsUpdate( value ) { - renderer.render( backgroundBox, cubeCamera ); + if ( value === true ) this.version ++; - } + } - renderer.render( scene, cubeCamera ); + setBuffer( buffer ) { - } + this.buffer = buffer; - renderer.toneMapping = toneMapping; - renderer.outputEncoding = outputEncoding; - renderer.autoClear = originalAutoClear; + return this; } - _textureToCubeUV( texture, cubeUVRenderTarget ) { + setType( type, elementSize ) { - const renderer = this._renderer; + this.type = type; + this.elementSize = elementSize; - if ( texture.isCubeTexture ) { + return this; - if ( this._cubemapShader == null ) { + } - this._cubemapShader = _getCubemapShader(); + setItemSize( itemSize ) { - } + this.itemSize = itemSize; - } else { + return this; - if ( this._equirectShader == null ) { + } - this._equirectShader = _getEquirectShader(); + setCount( count ) { - } + this.count = count; - } + return this; - const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader; - const mesh = new Mesh( _lodPlanes[ 0 ], material ); + } - const uniforms = material.uniforms; +} - uniforms[ 'envMap' ].value = texture; +class Raycaster { - if ( ! texture.isCubeTexture ) { + constructor( origin, direction, near = 0, far = Infinity ) { - uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height ); + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - } + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + + } - uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ]; - uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ]; + set( origin, direction ) { - _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX ); + // direction is assumed to be normalized (for accurate distance calculations) - renderer.setRenderTarget( cubeUVRenderTarget ); - renderer.render( mesh, _flatCamera ); + this.ray.set( origin, direction ); } - _applyPMREM( cubeUVRenderTarget ) { + setFromCamera( coords, camera ) { - const renderer = this._renderer; - const autoClear = renderer.autoClear; - renderer.autoClear = false; + if ( camera.isPerspectiveCamera ) { - for ( let i = 1; i < TOTAL_LODS; i ++ ) { + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; - const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] ); + } else if ( camera.isOrthographicCamera ) { - const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; + 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 ); + this.camera = camera; - this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + } else { - } + console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); - renderer.autoClear = autoClear; + } } - /** - * This is a two-pass Gaussian blur for a cubemap. Normally this is done - * vertically and horizontally, but this breaks down on a cube. Here we apply - * the blur latitudinally (around the poles), and then longitudinally (towards - * the poles) to approximate the orthogonally-separable blur. It is least - * accurate at the poles, but still does a decent job. - */ - _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { + intersectObject( object, recursive = true, intersects = [] ) { - const pingPongRenderTarget = this._pingPongRenderTarget; + intersectObject( object, this, intersects, recursive ); - this._halfBlur( - cubeUVRenderTarget, - pingPongRenderTarget, - lodIn, - lodOut, - sigma, - 'latitudinal', - poleAxis ); + intersects.sort( ascSort ); - this._halfBlur( - pingPongRenderTarget, - cubeUVRenderTarget, - lodOut, - lodOut, - sigma, - 'longitudinal', - poleAxis ); + return intersects; } - _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { - - const renderer = this._renderer; - const blurMaterial = this._blurMaterial; + intersectObjects( objects, recursive = true, intersects = [] ) { - if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { + for ( let i = 0, l = objects.length; i < l; i ++ ) { - console.error( - 'blur direction must be either latitudinal or longitudinal!' ); + intersectObject( objects[ i ], this, intersects, recursive ); } - // Number of standard deviations at which to cut off the discrete approximation. - const STANDARD_DEVIATIONS = 3; - - const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial ); - const blurUniforms = blurMaterial.uniforms; - - const pixels = _sizeLods[ lodIn ] - 1; - const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); - const sigmaPixels = sigmaRadians / radiansPerPixel; - const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; + intersects.sort( ascSort ); - if ( samples > MAX_SAMPLES ) { + return intersects; - console.warn( `sigmaRadians, ${ - sigmaRadians}, is too large and will clip, as it requested ${ - samples} samples when the maximum is set to ${MAX_SAMPLES}` ); + } - } +} - const weights = []; - let sum = 0; +function ascSort( a, b ) { - for ( let i = 0; i < MAX_SAMPLES; ++ i ) { + return a.distance - b.distance; - const x = i / sigmaPixels; - const weight = Math.exp( - x * x / 2 ); - weights.push( weight ); +} - if ( i == 0 ) { +function intersectObject( object, raycaster, intersects, recursive ) { - sum += weight; + if ( object.layers.test( raycaster.layers ) ) { - } else if ( i < samples ) { + object.raycast( raycaster, intersects ); - sum += 2 * weight; + } - } + if ( recursive === true ) { - } + const children = object.children; - for ( let i = 0; i < weights.length; i ++ ) { + for ( let i = 0, l = children.length; i < l; i ++ ) { - weights[ i ] = weights[ i ] / sum; + intersectObject( children[ i ], raycaster, intersects, true ); } - blurUniforms[ 'envMap' ].value = targetIn.texture; - blurUniforms[ 'samples' ].value = samples; - blurUniforms[ 'weights' ].value = weights; - blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; + } - if ( poleAxis ) { +} - blurUniforms[ 'poleAxis' ].value = poleAxis; +/** + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. + * The azimuthal angle (theta) is measured from the positive z-axis. + */ - } +class Spherical { - blurUniforms[ 'dTheta' ].value = radiansPerPixel; - blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn; - blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; - blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; + constructor( radius = 1, phi = 0, theta = 0 ) { - const outputSize = _sizeLods[ lodOut ]; - const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize ); - const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 ); + this.radius = radius; + this.phi = phi; // polar angle + this.theta = theta; // azimuthal angle - _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); - renderer.setRenderTarget( targetOut ); - renderer.render( blurMesh, _flatCamera ); + return this; } -} - -function _isLDR( texture ) { + set( radius, phi, theta ) { - if ( texture === undefined || texture.type !== UnsignedByteType ) return false; + this.radius = radius; + this.phi = phi; + this.theta = theta; - return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding; + return this; -} + } -function _createPlanes() { + copy( other ) { - const _lodPlanes = []; - const _sizeLods = []; - const _sigmas = []; + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; - let lod = LOD_MAX; + return this; - for ( let i = 0; i < TOTAL_LODS; i ++ ) { + } - const sizeLod = Math.pow( 2, lod ); - _sizeLods.push( sizeLod ); - let sigma = 1.0 / sizeLod; + // restrict phi to be between EPS and PI-EPS + makeSafe() { - if ( i > LOD_MAX - LOD_MIN ) { + const EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ]; + return this; - } else if ( i == 0 ) { + } - sigma = 0; + setFromVector3( v ) { - } + return this.setFromCartesianCoords( v.x, v.y, v.z ); - _sigmas.push( sigma ); + } - const texelSize = 1.0 / ( sizeLod - 1 ); - const min = - texelSize / 2; - const max = 1 + texelSize / 2; - const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + setFromCartesianCoords( x, y, z ) { - const cubeFaces = 6; - const vertices = 6; - const positionSize = 3; - const uvSize = 2; - const faceIndexSize = 1; + this.radius = Math.sqrt( x * x + y * y + z * z ); - const position = new Float32Array( positionSize * vertices * cubeFaces ); - const uv = new Float32Array( uvSize * vertices * cubeFaces ); - const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + if ( this.radius === 0 ) { - for ( let face = 0; face < cubeFaces; face ++ ) { + this.theta = 0; + this.phi = 0; - const x = ( face % 3 ) * 2 / 3 - 1; - const y = face > 2 ? 0 : - 1; - const coordinates = [ - x, y, 0, - x + 2 / 3, y, 0, - x + 2 / 3, y + 1, 0, - x, y, 0, - x + 2 / 3, y + 1, 0, - x, y + 1, 0 - ]; - position.set( coordinates, positionSize * vertices * face ); - uv.set( uv1, uvSize * vertices * face ); - const fill = [ face, face, face, face, face, face ]; - faceIndex.set( fill, faceIndexSize * vertices * face ); + } else { + + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); } - const planes = new BufferGeometry(); - planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); - planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); - planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); - _lodPlanes.push( planes ); + return this; - if ( lod > LOD_MIN ) { + } - lod --; + clone() { - } + return new this.constructor().copy( this ); } - return { _lodPlanes, _sizeLods, _sigmas }; - } -function _createRenderTarget( params ) { +/** + * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system + */ - const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params ); - cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; - cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; - cubeUVRenderTarget.scissorTest = true; - return cubeUVRenderTarget; +class Cylindrical { -} + constructor( radius = 1, theta = 0, y = 0 ) { -function _setViewport( target, x, y, width, height ) { + this.radius = radius; // distance from the origin to a point in the x-z plane + this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis + this.y = y; // height above the x-z plane - target.viewport.set( x, y, width, height ); - target.scissor.set( x, y, width, height ); + return this; -} + } -function _getBlurShader( maxSamples ) { + set( radius, theta, y ) { - const weights = new Float32Array( maxSamples ); - const poleAxis = new Vector3( 0, 1, 0 ); - const shaderMaterial = new RawShaderMaterial( { + this.radius = radius; + this.theta = theta; + this.y = y; - name: 'SphericalGaussianBlur', + return this; - defines: { 'n': maxSamples }, + } - uniforms: { - 'envMap': { value: null }, - 'samples': { value: 1 }, - 'weights': { value: weights }, - 'latitudinal': { value: false }, - 'dTheta': { value: 0 }, - 'mipInt': { value: 0 }, - 'poleAxis': { value: poleAxis }, - 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, - 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } - }, + copy( other ) { - vertexShader: _getCommonVertexShader(), + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; - fragmentShader: /* glsl */` + return this; - precision mediump float; - precision mediump int; + } - varying vec3 vOutputDirection; + setFromVector3( v ) { - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; + return this.setFromCartesianCoords( v.x, v.y, v.z ); - ${ _getEncodings() } + } - #define ENVMAP_TYPE_CUBE_UV - #include + setFromCartesianCoords( x, y, z ) { - vec3 getSample( float theta, vec3 axis ) { + this.radius = Math.sqrt( x * x + z * z ); + this.theta = Math.atan2( x, z ); + this.y = y; - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + return this; - return bilinearCubeUV( envMap, sampleDirection, mipInt ); + } - } + clone() { - void main() { + return new this.constructor().copy( this ); - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + } - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { +} - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); +const _vector$4 = /*@__PURE__*/ new Vector2(); - } +class Box2 { - axis = normalize( axis ); + constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + this.isBox2 = true; - for ( int i = 1; i < n; i++ ) { + this.min = min; + this.max = max; - if ( i >= samples ) { + } - break; + set( min, max ) { - } + this.min.copy( min ); + this.max.copy( max ); - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + return this; - } + } - gl_FragColor = linearToOutputTexel( gl_FragColor ); + setFromPoints( points ) { - } - `, + this.makeEmpty(); - blending: NoBlending, - depthTest: false, - depthWrite: false + for ( let i = 0, il = points.length; i < il; i ++ ) { - } ); + this.expandByPoint( points[ i ] ); - return shaderMaterial; + } -} + return this; -function _getEquirectShader() { + } - const texelSize = new Vector2( 1, 1 ); - const shaderMaterial = new RawShaderMaterial( { + setFromCenterAndSize( center, size ) { - name: 'EquirectangularToCubeUV', + const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - uniforms: { - 'envMap': { value: null }, - 'texelSize': { value: texelSize }, - 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, - 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } - }, + return this; - vertexShader: _getCommonVertexShader(), + } - fragmentShader: /* glsl */` + clone() { - precision mediump float; - precision mediump int; + return new this.constructor().copy( this ); - varying vec3 vOutputDirection; + } - uniform sampler2D envMap; - uniform vec2 texelSize; + copy( box ) { - ${ _getEncodings() } + this.min.copy( box.min ); + this.max.copy( box.max ); - #include + return this; - void main() { + } - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + makeEmpty() { - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - vec2 f = fract( uv / texelSize - 0.5 ); - uv -= f * texelSize; - vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; - uv.x += texelSize.x; - vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; - uv.y += texelSize.y; - vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; - uv.x -= texelSize.x; - vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; + return this; - vec3 tm = mix( tl, tr, f.x ); - vec3 bm = mix( bl, br, f.x ); - gl_FragColor.rgb = mix( tm, bm, f.y ); + } - gl_FragColor = linearToOutputTexel( gl_FragColor ); + isEmpty() { - } - `, + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - blending: NoBlending, - depthTest: false, - depthWrite: false + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - } ); + } - return shaderMaterial; + getCenter( target ) { -} + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); -function _getCubemapShader() { + } - const shaderMaterial = new RawShaderMaterial( { + getSize( target ) { - name: 'CubemapToCubeUV', + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); - uniforms: { - 'envMap': { value: null }, - 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, - 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } - }, + } - vertexShader: _getCommonVertexShader(), + expandByPoint( point ) { - fragmentShader: /* glsl */` + this.min.min( point ); + this.max.max( point ); - precision mediump float; - precision mediump int; + return this; - varying vec3 vOutputDirection; + } - uniform samplerCube envMap; + expandByVector( vector ) { - ${ _getEncodings() } + this.min.sub( vector ); + this.max.add( vector ); - void main() { + return this; - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb; - gl_FragColor = linearToOutputTexel( gl_FragColor ); + } - } - `, + expandByScalar( scalar ) { - blending: NoBlending, - depthTest: false, - depthWrite: false + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } ); + return this; - return shaderMaterial; + } -} + containsPoint( point ) { -function _getCommonVertexShader() { + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; - return /* glsl */` + } - precision mediump float; - precision mediump int; + containsBox( box ) { - attribute vec3 position; - attribute vec2 uv; - attribute float faceIndex; + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; - varying vec3 vOutputDirection; + } - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { + getParameter( point, target ) { - uv = 2.0 * uv - 1.0; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - vec3 direction = vec3( uv, 1.0 ); + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); - if ( face == 0.0 ) { + } - direction = direction.zyx; // ( 1, v, u ) pos x + intersectsBox( box ) { - } else if ( face == 1.0 ) { + // using 4 splitting planes to rule out intersections - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; - } else if ( face == 2.0 ) { + } - direction.x *= -1.0; // ( -u, v, 1 ) pos z + clampPoint( point, target ) { - } else if ( face == 3.0 ) { + return target.copy( point ).clamp( this.min, this.max ); - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x + } - } else if ( face == 4.0 ) { + distanceToPoint( point ) { - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y + const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - } else if ( face == 5.0 ) { + } - direction.z *= -1.0; // ( u, v, -1 ) neg z + intersect( box ) { - } + this.min.max( box.min ); + this.max.min( box.max ); - return direction; + return this; - } + } - void main() { + union( box ) { - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); + this.min.min( box.min ); + this.max.max( box.max ); - } - `; + return this; -} + } -function _getEncodings() { + translate( offset ) { - return /* glsl */` + this.min.add( offset ); + this.max.add( offset ); + + return this; - uniform int inputEncoding; - uniform int outputEncoding; + } + + equals( box ) { - #include + return box.min.equals( this.min ) && box.max.equals( this.max ); - vec4 inputTexelToLinear( vec4 value ) { + } - if ( inputEncoding == 0 ) { +} - return value; +const _startP = /*@__PURE__*/ new Vector3(); +const _startEnd = /*@__PURE__*/ new Vector3(); - } else if ( inputEncoding == 1 ) { +class Line3 { - return sRGBToLinear( value ); + constructor( start = new Vector3(), end = new Vector3() ) { - } else if ( inputEncoding == 2 ) { + this.start = start; + this.end = end; - return RGBEToLinear( value ); + } - } else if ( inputEncoding == 3 ) { + set( start, end ) { - return RGBMToLinear( value, 7.0 ); + this.start.copy( start ); + this.end.copy( end ); - } else if ( inputEncoding == 4 ) { + return this; - return RGBMToLinear( value, 16.0 ); + } - } else if ( inputEncoding == 5 ) { + copy( line ) { - return RGBDToLinear( value, 256.0 ); + this.start.copy( line.start ); + this.end.copy( line.end ); - } else { + return this; - return GammaToLinear( value, 2.2 ); + } - } + getCenter( target ) { - } + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - vec4 linearToOutputTexel( vec4 value ) { + } - if ( outputEncoding == 0 ) { + delta( target ) { - return value; + return target.subVectors( this.end, this.start ); - } else if ( outputEncoding == 1 ) { + } - return LinearTosRGB( value ); + distanceSq() { - } else if ( outputEncoding == 2 ) { + return this.start.distanceToSquared( this.end ); - return LinearToRGBE( value ); + } - } else if ( outputEncoding == 3 ) { + distance() { - return LinearToRGBM( value, 7.0 ); + return this.start.distanceTo( this.end ); - } else if ( outputEncoding == 4 ) { + } - return LinearToRGBM( value, 16.0 ); + at( t, target ) { - } else if ( outputEncoding == 5 ) { + return this.delta( target ).multiplyScalar( t ).add( this.start ); - return LinearToRGBD( value, 256.0 ); + } - } else { + closestPointToPointParameter( point, clampToLine ) { - return LinearToGamma( value, 2.2 ); + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); - } + const startEnd2 = _startEnd.dot( _startEnd ); + const startEnd_startP = _startEnd.dot( _startP ); - } + let t = startEnd_startP / startEnd2; - vec4 envMapTexelToLinear( vec4 color ) { + if ( clampToLine ) { - return inputTexelToLinear( color ); + t = clamp( t, 0, 1 ); } - `; -} + return t; -const LineStrip = 0; -const LinePieces = 1; -const NoColors = 0; -const FaceColors = 1; -const VertexColors = 2; + } -function MeshFaceMaterial( materials ) { + closestPointToPoint( point, clampToLine, target ) { - console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); - return materials; + const t = this.closestPointToPointParameter( point, clampToLine ); -} + return this.delta( target ).multiplyScalar( t ).add( this.start ); -function MultiMaterial( materials = [] ) { + } - console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); - materials.isMultiMaterial = true; - materials.materials = materials; - materials.clone = function () { + applyMatrix4( matrix ) { - return materials.slice(); + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - }; + return this; - return materials; + } -} + equals( line ) { -function PointCloud( geometry, material ) { + return line.start.equals( this.start ) && line.end.equals( this.end ); - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - return new Points( geometry, material ); + } -} + clone() { -function Particle( material ) { + return new this.constructor().copy( this ); - console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); - return new Sprite( material ); + } } -function ParticleSystem( geometry, material ) { +const _vector$3 = /*@__PURE__*/ new Vector3(); - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - return new Points( geometry, material ); +class SpotLightHelper extends Object3D { -} + constructor( light, color ) { -function PointCloudMaterial( parameters ) { + super(); - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + this.light = light; + this.light.updateMatrixWorld(); -} + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; -function ParticleBasicMaterial( parameters ) { + this.color = color; - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + const geometry = new BufferGeometry(); -} + const 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 + ]; -function ParticleSystemMaterial( parameters ) { + for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + const p1 = ( i / l ) * Math.PI * 2; + const p2 = ( j / l ) * Math.PI * 2; -} + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); -function Vertex( x, y, z ) { + } - console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); - return new Vector3( x, y, z ); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); -} + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); -// + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); -function DynamicBufferAttribute( array, itemSize ) { + this.update(); - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' ); - return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage ); + } -} + dispose() { -function Int8Attribute( array, itemSize ) { + this.cone.geometry.dispose(); + this.cone.material.dispose(); - console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); - return new Int8BufferAttribute( array, itemSize ); + } -} + update() { -function Uint8Attribute( array, itemSize ) { + this.light.updateMatrixWorld(); - console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); - return new Uint8BufferAttribute( array, itemSize ); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan( this.light.angle ); -} + this.cone.scale.set( coneWidth, coneWidth, coneLength ); -function Uint8ClampedAttribute( array, itemSize ) { + _vector$3.setFromMatrixPosition( this.light.target.matrixWorld ); - console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); - return new Uint8ClampedBufferAttribute( array, itemSize ); + this.cone.lookAt( _vector$3 ); -} + if ( this.color !== undefined ) { -function Int16Attribute( array, itemSize ) { + this.cone.material.color.set( this.color ); - console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); - return new Int16BufferAttribute( array, itemSize ); + } else { -} + this.cone.material.color.copy( this.light.color ); -function Uint16Attribute( array, itemSize ) { + } - console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); - return new Uint16BufferAttribute( array, itemSize ); + } } -function Int32Attribute( array, itemSize ) { +const _vector$2 = /*@__PURE__*/ new Vector3(); +const _boneMatrix = /*@__PURE__*/ new Matrix4(); +const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + - console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); - return new Int32BufferAttribute( array, itemSize ); +class SkeletonHelper extends LineSegments { -} + constructor( object ) { -function Uint32Attribute( array, itemSize ) { + const bones = getBoneList( object ); - console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); - return new Uint32BufferAttribute( array, itemSize ); + const geometry = new BufferGeometry(); -} + const vertices = []; + const colors = []; + + const color1 = new Color( 0, 0, 1 ); + const color2 = new Color( 0, 1, 0 ); -function Float32Attribute( array, itemSize ) { + for ( let i = 0; i < bones.length; i ++ ) { - console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); - return new Float32BufferAttribute( array, itemSize ); + const bone = bones[ i ]; -} + if ( bone.parent && bone.parent.isBone ) { -function Float64Attribute( array, itemSize ) { + vertices.push( 0, 0, 0 ); + vertices.push( 0, 0, 0 ); + colors.push( color1.r, color1.g, color1.b ); + colors.push( color2.r, color2.g, color2.b ); - console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); - return new Float64BufferAttribute( array, itemSize ); + } -} + } -// + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -Curve.create = function ( construct, getPoint ) { + const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); - console.log( 'THREE.Curve.create() has been deprecated' ); + super( geometry, material ); - construct.prototype = Object.create( Curve.prototype ); - construct.prototype.constructor = construct; - construct.prototype.getPoint = getPoint; + this.isSkeletonHelper = true; - return construct; + this.type = 'SkeletonHelper'; -}; + this.root = object; + this.bones = bones; -// + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; -Path.prototype.fromPoints = function ( points ) { + } - console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); - return this.setFromPoints( points ); + updateMatrixWorld( force ) { -}; + const bones = this.bones; -// + const geometry = this.geometry; + const position = geometry.getAttribute( 'position' ); -function AxisHelper( size ) { + _matrixWorldInv.copy( this.root.matrixWorld ).invert(); - console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); - return new AxesHelper( size ); + for ( let i = 0, j = 0; i < bones.length; i ++ ) { -} + const bone = bones[ i ]; -function BoundingBoxHelper( object, color ) { + if ( bone.parent && bone.parent.isBone ) { - console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); - return new BoxHelper( object, color ); + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z ); -} + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z ); -function EdgesHelper( object, hex ) { + j += 2; - console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); - return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + } -} + } -GridHelper.prototype.setColors = function () { + geometry.getAttribute( 'position' ).needsUpdate = true; - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); + super.updateMatrixWorld( force ); -}; + } -SkeletonHelper.prototype.update = function () { +} - console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); -}; +function getBoneList( object ) { -function WireframeHelper( object, hex ) { + const boneList = []; - console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); - return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + if ( object.isBone === true ) { -} + boneList.push( object ); -// + } -Loader.prototype.extractUrlBase = function ( url ) { + for ( let i = 0; i < object.children.length; i ++ ) { - console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); - return LoaderUtils.extractUrlBase( url ); + boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); -}; + } -Loader.Handlers = { + return boneList; - add: function ( /* regex, loader */ ) { +} - console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' ); +class PointLightHelper extends Mesh { - }, + constructor( light, sphereSize, color ) { - get: function ( /* file */ ) { + const geometry = new SphereGeometry( sphereSize, 4, 2 ); + const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); - console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' ); + super( geometry, material ); - } + this.light = light; + this.light.updateMatrixWorld(); -}; + this.color = color; -function XHRLoader( manager ) { + this.type = 'PointLightHelper'; - console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); - return new FileLoader( manager ); + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; -} + this.update(); -function BinaryTextureLoader( manager ) { - console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); - return new DataTextureLoader( manager ); + /* + // TODO: delete this comment? + const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); -} + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); -// + const d = light.distance; -Box2.prototype.center = function ( optionalTarget ) { + if ( d === 0.0 ) { - console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + this.lightDistance.visible = false; -}; + } else { -Box2.prototype.empty = function () { + this.lightDistance.scale.set( d, d, d ); - console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); + } -}; + this.add( this.lightDistance ); + */ -Box2.prototype.isIntersectionBox = function ( box ) { + } - console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + dispose() { -}; + this.geometry.dispose(); + this.material.dispose(); -Box2.prototype.size = function ( optionalTarget ) { + } - console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); + update() { -}; + if ( this.color !== undefined ) { -// + this.material.color.set( this.color ); -Box3.prototype.center = function ( optionalTarget ) { + } else { - console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + this.material.color.copy( this.light.color ); -}; + } -Box3.prototype.empty = function () { + /* + const d = this.light.distance; - console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); + if ( d === 0.0 ) { -}; + this.lightDistance.visible = false; -Box3.prototype.isIntersectionBox = function ( box ) { + } else { - console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); -}; + } + */ -Box3.prototype.isIntersectionSphere = function ( sphere ) { + } - console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); +} -}; +const _vector$1 = /*@__PURE__*/ new Vector3(); +const _color1 = /*@__PURE__*/ new Color(); +const _color2 = /*@__PURE__*/ new Color(); -Box3.prototype.size = function ( optionalTarget ) { +class HemisphereLightHelper extends Object3D { - console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); + constructor( light, size, color ) { -}; + super(); -// + this.light = light; + this.light.updateMatrixWorld(); -Sphere.prototype.empty = function () { + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); + this.color = color; -}; + const geometry = new OctahedronGeometry( size ); + geometry.rotateY( Math.PI * 0.5 ); -// + this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + if ( this.color === undefined ) this.material.vertexColors = true; -Frustum.prototype.setFromMatrix = function ( m ) { + const position = geometry.getAttribute( 'position' ); + const colors = new Float32Array( position.count * 3 ); - console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' ); - return this.setFromProjectionMatrix( m ); + geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); -}; + this.add( new Mesh( geometry, this.material ) ); -// + this.update(); -Line3.prototype.center = function ( optionalTarget ) { + } - console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + dispose() { -}; + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); -// + } -MathUtils.random16 = function () { + update() { - console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); + const mesh = this.children[ 0 ]; -}; + if ( this.color !== undefined ) { -MathUtils.nearestPowerOfTwo = function ( value ) { + this.material.color.set( this.color ); - console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' ); - return MathUtils.floorPowerOfTwo( value ); + } else { -}; + const colors = mesh.geometry.getAttribute( 'color' ); -MathUtils.nextPowerOfTwo = function ( value ) { + _color1.copy( this.light.color ); + _color2.copy( this.light.groundColor ); - console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' ); - return MathUtils.ceilPowerOfTwo( value ); + for ( let i = 0, l = colors.count; i < l; i ++ ) { -}; + const color = ( i < ( l / 2 ) ) ? _color1 : _color2; -// + colors.setXYZ( i, color.r, color.g, color.b ); -Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) { + } - console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); + colors.needsUpdate = true; -}; + } -Matrix3.prototype.multiplyVector3 = function ( vector ) { + mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); + } -}; +} -Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) { +class GridHelper extends LineSegments { - console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); + constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { -}; + color1 = new Color( color1 ); + color2 = new Color( color2 ); -Matrix3.prototype.applyToBufferAttribute = function ( attribute ) { + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; - console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' ); - return attribute.applyMatrix3( this ); + const vertices = [], colors = []; -}; + for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { -Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { + vertices.push( - halfSize, 0, k, halfSize, 0, k ); + vertices.push( k, 0, - halfSize, k, 0, halfSize ); - console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); + const color = i === center ? color1 : color2; -}; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; -Matrix3.prototype.getInverse = function ( matrix ) { + } - console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -}; + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); -// + super( geometry, material ); -Matrix4.prototype.extractPosition = function ( m ) { + this.type = 'GridHelper'; - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); + } -}; +} -Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) { +class PolarGridHelper extends LineSegments { - console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); + constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { -}; + color1 = new Color( color1 ); + color2 = new Color( color2 ); -Matrix4.prototype.getPosition = function () { + const vertices = []; + const colors = []; - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - return new Vector3().setFromMatrixColumn( this, 3 ); + // create the sectors -}; + if ( sectors > 1 ) { -Matrix4.prototype.setRotationFromQuaternion = function ( q ) { + for ( let i = 0; i < sectors; i ++ ) { - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - return this.makeRotationFromQuaternion( q ); + const v = ( i / sectors ) * ( Math.PI * 2 ); -}; + const x = Math.sin( v ) * radius; + const z = Math.cos( v ) * radius; -Matrix4.prototype.multiplyToArray = function () { + vertices.push( 0, 0, 0 ); + vertices.push( x, 0, z ); - console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); + const color = ( i & 1 ) ? color1 : color2; -}; + colors.push( color.r, color.g, color.b ); + colors.push( color.r, color.g, color.b ); -Matrix4.prototype.multiplyVector3 = function ( vector ) { + } - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + } -}; + // create the rings -Matrix4.prototype.multiplyVector4 = function ( vector ) { + for ( let i = 0; i < rings; i ++ ) { - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + const color = ( i & 1 ) ? color1 : color2; -}; + const r = radius - ( radius / rings * i ); -Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) { + for ( let j = 0; j < divisions; j ++ ) { - console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); + // first vertex -}; + let v = ( j / divisions ) * ( Math.PI * 2 ); -Matrix4.prototype.rotateAxis = function ( v ) { + let x = Math.sin( v ) * r; + let z = Math.cos( v ) * r; - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - v.transformDirection( this ); + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); -}; + // second vertex -Matrix4.prototype.crossVector = function ( vector ) { + v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; -}; + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); -Matrix4.prototype.translate = function () { + } - console.error( 'THREE.Matrix4: .translate() has been removed.' ); + } -}; + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -Matrix4.prototype.rotateX = function () { + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); + super( geometry, material ); -}; + this.type = 'PolarGridHelper'; -Matrix4.prototype.rotateY = function () { + } - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); +} -}; +const _v1 = /*@__PURE__*/ new Vector3(); +const _v2 = /*@__PURE__*/ new Vector3(); +const _v3 = /*@__PURE__*/ new Vector3(); -Matrix4.prototype.rotateZ = function () { +class DirectionalLightHelper extends Object3D { - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); + constructor( light, size, color ) { -}; + super(); -Matrix4.prototype.rotateByAxis = function () { + this.light = light; + this.light.updateMatrixWorld(); - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; -}; + this.color = color; -Matrix4.prototype.applyToBufferAttribute = function ( attribute ) { + if ( size === undefined ) size = 1; - console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' ); - return attribute.applyMatrix4( this ); + let geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); -}; + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); -Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); - console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); + geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); -}; + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); -Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) { + this.update(); - console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); - return this.makePerspective( left, right, top, bottom, near, far ); + } -}; + dispose() { -Matrix4.prototype.getInverse = function ( matrix ) { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); - console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); + } -}; + update() { -// + _v1.setFromMatrixPosition( this.light.matrixWorld ); + _v2.setFromMatrixPosition( this.light.target.matrixWorld ); + _v3.subVectors( _v2, _v1 ); -Plane.prototype.isIntersectionLine = function ( line ) { + this.lightPlane.lookAt( _v2 ); - console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); - return this.intersectsLine( line ); + if ( this.color !== undefined ) { -}; + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); -// + } else { -Quaternion.prototype.multiplyVector3 = function ( vector ) { + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); + } -}; + this.targetLine.lookAt( _v2 ); + this.targetLine.scale.z = _v3.length(); -Quaternion.prototype.inverse = function ( ) { + } - console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' ); - return this.invert(); +} -}; +const _vector = /*@__PURE__*/ new Vector3(); +const _camera = /*@__PURE__*/ new Camera(); -// +/** + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html + */ -Ray.prototype.isIntersectionBox = function ( box ) { +class CameraHelper extends LineSegments { - console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + constructor( camera ) { -}; + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); -Ray.prototype.isIntersectionPlane = function ( plane ) { + const vertices = []; + const colors = []; - console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); - return this.intersectsPlane( plane ); + const pointMap = {}; -}; + // near -Ray.prototype.isIntersectionSphere = function ( sphere ) { + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); - console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); + // far -}; + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); -// + // sides -Triangle.prototype.area = function () { + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); - console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); - return this.getArea(); + // cone -}; + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); -Triangle.prototype.barycoordFromPoint = function ( point, target ) { + // up - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return this.getBarycoord( point, target ); + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); -}; + // target -Triangle.prototype.midpoint = function ( target ) { + addLine( 'c', 't' ); + addLine( 'p', 'c' ); - console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); - return this.getMidpoint( target ); + // cross -}; + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); -Triangle.prototypenormal = function ( target ) { + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return this.getNormal( target ); + function addLine( a, b ) { -}; + addPoint( a ); + addPoint( b ); -Triangle.prototype.plane = function ( target ) { + } - console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); - return this.getPlane( target ); + function addPoint( id ) { -}; + vertices.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); -Triangle.barycoordFromPoint = function ( point, a, b, c, target ) { + if ( pointMap[ id ] === undefined ) { - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return Triangle.getBarycoord( point, a, b, c, target ); + pointMap[ id ] = []; -}; + } -Triangle.normal = function ( a, b, c, target ) { + pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return Triangle.getNormal( a, b, c, target ); + } -}; + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -// + super( geometry, material ); -Shape.prototype.extractAllPoints = function ( divisions ) { + this.type = 'CameraHelper'; - console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); - return this.extractPoints( divisions ); + this.camera = camera; + if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); -}; + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; -Shape.prototype.extrude = function ( options ) { + this.pointMap = pointMap; - console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); - return new ExtrudeGeometry( this, options ); + this.update(); -}; + // colors -Shape.prototype.makeGeometry = function ( options ) { + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); - console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); - return new ShapeGeometry( this, options ); + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); -}; + } -// + setColors( frustum, cone, up, target, cross ) { -Vector2.prototype.fromAttribute = function ( attribute, index, offset ) { + const geometry = this.geometry; - console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + const colorAttribute = geometry.getAttribute( 'color' ); -}; + // near -Vector2.prototype.distanceToManhattan = function ( v ) { + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 - console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); + // far -}; + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 -Vector2.prototype.lengthManhattan = function () { + // sides - console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 -}; + // cone -// + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 -Vector3.prototype.setEulerFromRotationMatrix = function () { + // up - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 -}; + // target -Vector3.prototype.setEulerFromQuaternion = function () { + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); + // cross -}; + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 -Vector3.prototype.getPositionFromMatrix = function ( m ) { + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - return this.setFromMatrixPosition( m ); + colorAttribute.needsUpdate = true; -}; + } -Vector3.prototype.getScaleFromMatrix = function ( m ) { + update() { - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - return this.setFromMatrixScale( m ); + const geometry = this.geometry; + const pointMap = this.pointMap; -}; + const w = 1, h = 1; -Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) { + // we need just camera projection matrix inverse + // world matrix must be identity - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - return this.setFromMatrixColumn( matrix, index ); + _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); -}; + // center / target -Vector3.prototype.applyProjection = function ( m ) { + setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); + setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); - console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); - return this.applyMatrix4( m ); + // near -}; + setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); + setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); + setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); + setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); -Vector3.prototype.fromAttribute = function ( attribute, index, offset ) { + // far - console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); + setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); + setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); + setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); -}; + // up -Vector3.prototype.distanceToManhattan = function ( v ) { + setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); + setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); + setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); - console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); + // cross -}; + setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); + setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); + setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); + setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); -Vector3.prototype.lengthManhattan = function () { + setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); + setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); + setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); + setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); - console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); + geometry.getAttribute( 'position' ).needsUpdate = true; -}; + } -// + dispose() { -Vector4.prototype.fromAttribute = function ( attribute, index, offset ) { + this.geometry.dispose(); + this.material.dispose(); - console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + } -}; +} -Vector4.prototype.lengthManhattan = function () { - console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); +function setPoint( point, pointMap, geometry, camera, x, y, z ) { -}; + _vector.set( x, y, z ).unproject( camera ); -// + const points = pointMap[ point ]; -Object3D.prototype.getChildByName = function ( name ) { + if ( points !== undefined ) { - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); + const position = geometry.getAttribute( 'position' ); -}; + for ( let i = 0, l = points.length; i < l; i ++ ) { -Object3D.prototype.renderDepth = function () { + position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z ); - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); + } -}; + } -Object3D.prototype.translate = function ( distance, axis ) { +} - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); +const _box = /*@__PURE__*/ new Box3(); -}; +class BoxHelper extends LineSegments { -Object3D.prototype.getWorldRotation = function () { + constructor( object, color = 0xffff00 ) { - console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); + const 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 ] ); + const positions = new Float32Array( 8 * 3 ); -}; + const geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); -Object3D.prototype.applyMatrix = function ( matrix ) { + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); + this.object = object; + this.type = 'BoxHelper'; -}; + this.matrixAutoUpdate = false; -Object.defineProperties( Object3D.prototype, { + this.update(); - eulerOrder: { - get: function () { + } - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - return this.rotation.order; + update( object ) { - }, - set: function ( value ) { + if ( object !== undefined ) { - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - this.rotation.order = value; + console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); } - }, - useQuaternion: { - get: function () { - - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - }, - set: function () { + if ( this.object !== undefined ) { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + _box.setFromObject( this.object ); } - } -} ); + if ( _box.isEmpty() ) return; -Mesh.prototype.setDrawMode = function () { + const min = _box.min; + const max = _box.max; - console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); + /* + 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 + */ -Object.defineProperties( Mesh.prototype, { + const position = this.geometry.attributes.position; + const array = position.array; - drawMode: { - get: function () { + 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; - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' ); - return TrianglesDrawMode; + position.needsUpdate = true; - }, - set: function () { + this.geometry.computeBoundingSphere(); - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); - } } -} ); - -Object.defineProperties( LOD.prototype, { + setFromObject( object ) { - objects: { - get: function () { + this.object = object; + this.update(); - console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); - return this.levels; + return this; - } } -} ); - -Object.defineProperty( Skeleton.prototype, 'useVertexTexture', { - - get: function () { + copy( source, recursive ) { - console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); + super.copy( source, recursive ); - }, - set: function () { + this.object = source.object; - console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); + return this; } -} ); - -SkinnedMesh.prototype.initBones = function () { - - console.error( 'THREE.SkinnedMesh: initBones() has been removed.' ); +} -}; +class Box3Helper extends LineSegments { -Object.defineProperty( Curve.prototype, '__arcLengthDivisions', { + constructor( box, color = 0xffff00 ) { - get: function () { + const 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 ] ); - console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); - return this.arcLengthDivisions; + const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; - }, - set: function ( value ) { + const geometry = new BufferGeometry(); - console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); - this.arcLengthDivisions = value; + geometry.setIndex( new BufferAttribute( indices, 1 ) ); - } + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); -} ); + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); -// + this.box = box; -PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { + this.type = 'Box3Helper'; - console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' + - 'Use .setFocalLength and .filmGauge for a photographic setup.' ); + this.geometry.computeBoundingSphere(); - if ( filmGauge !== undefined ) this.filmGauge = filmGauge; - this.setFocalLength( focalLength ); + } -}; + updateMatrixWorld( force ) { -// + const box = this.box; -Object.defineProperties( Light.prototype, { - onlyShadow: { - set: function () { + if ( box.isEmpty() ) return; - console.warn( 'THREE.Light: .onlyShadow has been removed.' ); + box.getCenter( this.position ); - } - }, - shadowCameraFov: { - set: function ( value ) { + box.getSize( this.scale ); - console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); - this.shadow.camera.fov = value; + this.scale.multiplyScalar( 0.5 ); - } - }, - shadowCameraLeft: { - set: function ( value ) { + super.updateMatrixWorld( force ); - 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; +class PlaneHelper extends Line { - } - }, - shadowCameraTop: { - set: function ( value ) { + constructor( plane, size = 1, hex = 0xffff00 ) { - console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); - this.shadow.camera.top = value; + const color = hex; - } - }, - shadowCameraBottom: { - set: function ( value ) { + const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; - console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); - this.shadow.camera.bottom = value; + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); - } - }, - shadowCameraNear: { - set: function ( value ) { + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); - this.shadow.camera.near = value; + this.type = 'PlaneHelper'; - } - }, - shadowCameraFar: { - set: function ( value ) { + this.plane = plane; - console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); - this.shadow.camera.far = value; + this.size = size; - } - }, - shadowCameraVisible: { - set: function () { + const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; - console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); - } - }, - shadowBias: { - set: function ( value ) { + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); - console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); - this.shadow.bias = value; + } - } - }, - shadowDarkness: { - set: function () { + updateMatrixWorld( force ) { - console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); + this.position.set( 0, 0, 0 ); - } - }, - shadowMapWidth: { - set: function ( value ) { + this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 ); - console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); - this.shadow.mapSize.width = value; + this.lookAt( this.plane.normal ); - } - }, - shadowMapHeight: { - set: function ( value ) { + this.translateZ( - this.plane.constant ); - console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); - this.shadow.mapSize.height = value; + super.updateMatrixWorld( force ); - } } -} ); -// - -Object.defineProperties( BufferAttribute.prototype, { +} - length: { - get: function () { +const _axis = /*@__PURE__*/ new Vector3(); +let _lineGeometry, _coneGeometry; - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); - return this.array.length; +class ArrowHelper extends Object3D { - } - }, - dynamic: { - get: function () { + // dir is assumed to be normalized - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; + constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { - }, - set: function ( /* value */ ) { + super(); - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - this.setUsage( DynamicDrawUsage ); + this.type = 'ArrowHelper'; - } - } + if ( _lineGeometry === undefined ) { -} ); + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); -BufferAttribute.prototype.setDynamic = function ( value ) { + _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 ); + _coneGeometry.translate( 0, - 0.5, 0 ); - console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; + } -}; + this.position.copy( origin ); -BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) { + this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); - console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); + this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); -}, + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); -BufferAttribute.prototype.setArray = function ( /* array */ ) { + } - console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); + setDirection( dir ) { -}; + // dir is assumed to be normalized -// + if ( dir.y > 0.99999 ) { -BufferGeometry.prototype.addIndex = function ( index ) { + this.quaternion.set( 0, 0, 0, 1 ); - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); + } else if ( dir.y < - 0.99999 ) { -}; + this.quaternion.set( 1, 0, 0, 0 ); -BufferGeometry.prototype.addAttribute = function ( name, attribute ) { + } else { - console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' ); + _axis.set( dir.z, 0, - dir.x ).normalize(); - if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { + const radians = Math.acos( dir.y ); - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + this.quaternion.setFromAxisAngle( _axis, radians ); - return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + } } - if ( name === 'index' ) { + setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 + this.line.updateMatrix(); - return this; + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); } - return this.setAttribute( name, attribute ); + setColor( color ) { -}; + this.line.material.color.set( color ); + this.cone.material.color.set( color ); + + } -BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) { + copy( source ) { + + super.copy( source, false ); - if ( indexOffset !== undefined ) { + this.line.copy( source.line ); + this.cone.copy( source.cone ); - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); + return this; } - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); +} -}; +class AxesHelper extends LineSegments { -BufferGeometry.prototype.clearDrawCalls = function () { + constructor( size = 1 ) { - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); + const vertices = [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ]; -}; + const colors = [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ]; -BufferGeometry.prototype.computeOffsets = function () { + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); -}; + super( geometry, material ); -BufferGeometry.prototype.removeAttribute = function ( name ) { + this.type = 'AxesHelper'; - console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' ); + } - return this.deleteAttribute( name ); + setColors( xAxisColor, yAxisColor, zAxisColor ) { -}; + const color = new Color(); + const array = this.geometry.attributes.color.array; -BufferGeometry.prototype.applyMatrix = function ( matrix ) { + color.set( xAxisColor ); + color.toArray( array, 0 ); + color.toArray( array, 3 ); - console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); + color.set( yAxisColor ); + color.toArray( array, 6 ); + color.toArray( array, 9 ); -}; + color.set( zAxisColor ); + color.toArray( array, 12 ); + color.toArray( array, 15 ); -Object.defineProperties( BufferGeometry.prototype, { + this.geometry.attributes.color.needsUpdate = true; - drawcalls: { - get: function () { + return this; - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; + } - } - }, - offsets: { - get: function () { + dispose() { - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; + this.geometry.dispose(); + this.material.dispose(); - } } -} ); +} -Object.defineProperties( InstancedBufferGeometry.prototype, { +class ShapePath { - maxInstancedCount: { - get: function () { + constructor() { - console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' ); - return this.instanceCount; + this.type = 'ShapePath'; - }, - set: function ( value ) { + this.color = new Color(); - console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' ); - this.instanceCount = value; + this.subPaths = []; + this.currentPath = null; - } } -} ); + moveTo( x, y ) { + + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); -Object.defineProperties( Raycaster.prototype, { + return this; - linePrecision: { - get: function () { + } - console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' ); - return this.params.Line.threshold; + lineTo( x, y ) { - }, - set: function ( value ) { + this.currentPath.lineTo( x, y ); - console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' ); - this.params.Line.threshold = value; + return this; - } } -} ); + quadraticCurveTo( aCPx, aCPy, aX, aY ) { -Object.defineProperties( InterleavedBuffer.prototype, { + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); - dynamic: { - get: function () { + return this; - console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; + } - }, - set: function ( value ) { + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); - this.setUsage( value ); + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); - } - } + return this; -} ); + } -InterleavedBuffer.prototype.setDynamic = function ( value ) { + splineThru( pts ) { - console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; + this.currentPath.splineThru( pts ); -}; + return this; -InterleavedBuffer.prototype.setArray = function ( /* array */ ) { + } - console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); + toShapes( isCCW ) { -}; + function toShapesNoHoles( inSubpaths ) { -// + const shapes = []; -ExtrudeGeometry.prototype.getArrays = function () { + for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { - console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' ); + const tmpPath = inSubpaths[ i ]; -}; + const tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; -ExtrudeGeometry.prototype.addShapeList = function () { + shapes.push( tmpShape ); - console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' ); + } -}; + return shapes; -ExtrudeGeometry.prototype.addShape = function () { + } - console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' ); + function isPointInsidePolygon( inPt, inPolygon ) { -}; + const 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 + let inside = false; + for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { -Scene.prototype.dispose = function () { + let edgeLowPt = inPolygon[ p ]; + let edgeHighPt = inPolygon[ q ]; - console.error( 'THREE.Scene: .dispose() has been removed.' ); + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; -}; + if ( Math.abs( edgeDy ) > Number.EPSILON ) { -// + // not parallel + if ( edgeDy < 0 ) { -Object.defineProperties( Uniform.prototype, { + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; - dynamic: { - set: function () { + } - console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' ); + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; - } - }, - onUpdate: { - value: function () { + if ( inPt.y === edgeLowPt.y ) { - console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); - return this; + if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! - } - } + } else { -} ); + const 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 -// + } -Object.defineProperties( Material.prototype, { + } else { - wrapAround: { - get: function () { + // 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.Material: .wrapAround has been removed.' ); + } - }, - set: function () { + } - console.warn( 'THREE.Material: .wrapAround has been removed.' ); + return inside; } - }, - - overdraw: { - get: function () { - console.warn( 'THREE.Material: .overdraw has been removed.' ); - - }, - set: function () { + const isClockWise = ShapeUtils.isClockWise; - console.warn( 'THREE.Material: .overdraw has been removed.' ); + const subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - } - }, + let solid, tmpPath, tmpShape; + const shapes = []; - wrapRGB: { - get: function () { + if ( subPaths.length === 1 ) { - console.warn( 'THREE.Material: .wrapRGB has been removed.' ); - return new Color(); + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; } - }, - shading: { - get: function () { - - console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - }, - set: function ( value ) { + // console.log("Holes first", holesFirst); - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( value === FlatShading ); + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; - } - }, + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - stencilMask: { - get: function () { + for ( let i = 0, l = subPaths.length; i < l; i ++ ) { - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - return this.stencilFuncMask; + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - }, - set: function ( value ) { + if ( solid ) { - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - this.stencilFuncMask = value; + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - } - } + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; -} ); + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; -Object.defineProperties( MeshPhongMaterial.prototype, { + //console.log('cw', i); - metal: { - get: function () { + } else { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); - return false; + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); - }, - set: function () { + //console.log('ccw', i); - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); + } } - } -} ); + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); -Object.defineProperties( MeshPhysicalMaterial.prototype, { - transparency: { - get: function () { + if ( newShapes.length > 1 ) { - console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' ); - return this.transmission; + let ambiguous = false; + let toChange = 0; - }, - set: function ( value ) { + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' ); - this.transmission = value; + betterShapeHoles[ sIdx ] = []; - } - } + } -} ); + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { -Object.defineProperties( ShaderMaterial.prototype, { + const sho = newShapeHoles[ sIdx ]; - derivatives: { - get: function () { + for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { - console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - return this.extensions.derivatives; + const ho = sho[ hIdx ]; + let hole_unassigned = true; - }, - set: function ( value ) { + for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - this.extensions.derivatives = value; + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { - } - } + if ( sIdx !== s2Idx ) toChange ++; -} ); + if ( hole_unassigned ) { -// + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); -WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) { + } else { - console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' ); - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + ambiguous = true; -}; + } -WebGLRenderer.prototype.animate = function ( callback ) { + } - console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' ); - this.setAnimationLoop( callback ); + } -}; + if ( hole_unassigned ) { -WebGLRenderer.prototype.getCurrentRenderTarget = function () { + betterShapeHoles[ sIdx ].push( ho ); - console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); - return this.getRenderTarget(); + } -}; + } -WebGLRenderer.prototype.getMaxAnisotropy = function () { + } - console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); - return this.capabilities.getMaxAnisotropy(); + if ( toChange > 0 && ambiguous === false ) { -}; + newShapeHoles = betterShapeHoles; -WebGLRenderer.prototype.getPrecision = function () { + } - console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); - return this.capabilities.precision; + } -}; + let tmpHoles; -WebGLRenderer.prototype.resetGLState = function () { + for ( let i = 0, il = newShapes.length; i < il; i ++ ) { - console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); - return this.state.reset(); + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; -}; + for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { -WebGLRenderer.prototype.supportsFloatTextures = function () { + tmpShape.holes.push( tmpHoles[ j ].h ); - console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); - return this.extensions.get( 'OES_texture_float' ); + } -}; + } -WebGLRenderer.prototype.supportsHalfFloatTextures = function () { + //console.log("shape", shapes); - console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); - return this.extensions.get( 'OES_texture_half_float' ); + return shapes; -}; + } -WebGLRenderer.prototype.supportsStandardDerivatives = function () { +} - console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); - return this.extensions.get( 'OES_standard_derivatives' ); +// Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf -}; +const _tables = /*@__PURE__*/ _generateTables(); -WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () { +function _generateTables() { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); + // float32 to float16 helpers -}; + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); -WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () { + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + for ( let i = 0; i < 256; ++ i ) { -}; + const e = i - 127; -WebGLRenderer.prototype.supportsBlendMinMax = function () { + // very small number (0, -0) - console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); - return this.extensions.get( 'EXT_blend_minmax' ); + if ( e < - 27 ) { -}; + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -WebGLRenderer.prototype.supportsVertexTextures = function () { + // small number (denorm) - console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); - return this.capabilities.vertexTextures; + } else if ( e < - 14 ) { -}; + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; -WebGLRenderer.prototype.supportsInstancedArrays = function () { + // normal number - console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); - return this.extensions.get( 'ANGLE_instanced_arrays' ); + } else if ( e <= 15 ) { -}; + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; -WebGLRenderer.prototype.enableScissorTest = function ( boolean ) { + // large number (Infinity, -Infinity) - console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); - this.setScissorTest( boolean ); + } else if ( e < 128 ) { -}; + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -WebGLRenderer.prototype.initMaterial = function () { + // stay (NaN, Infinity, -Infinity) - console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); + } else { -}; + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; -WebGLRenderer.prototype.addPrePlugin = function () { + } - console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); + } -}; + // float16 to float32 helpers -WebGLRenderer.prototype.addPostPlugin = function () { + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); - console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); + for ( let i = 1; i < 1024; ++ i ) { -}; + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent -WebGLRenderer.prototype.updateShadowMap = function () { + // normalized + while ( ( m & 0x00800000 ) === 0 ) { - console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); + m <<= 1; + e -= 0x00800000; // decrement exponent -}; + } -WebGLRenderer.prototype.setFaceCulling = function () { + m &= ~ 0x00800000; // clear leading 1 bit + e += 0x38800000; // adjust bias - console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); + mantissaTable[ i ] = m | e; -}; + } -WebGLRenderer.prototype.allocTextureUnit = function () { + for ( let i = 1024; i < 2048; ++ i ) { - console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' ); + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); -}; + } -WebGLRenderer.prototype.setTexture = function () { + for ( let i = 1; i < 31; ++ i ) { - console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' ); + exponentTable[ i ] = i << 23; -}; + } -WebGLRenderer.prototype.setTexture2D = function () { + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; - console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' ); + for ( let i = 33; i < 63; ++ i ) { -}; + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); -WebGLRenderer.prototype.setTextureCube = function () { + } - console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' ); + exponentTable[ 63 ] = 0xc7800000; -}; + for ( let i = 1; i < 64; ++ i ) { -WebGLRenderer.prototype.getActiveMipMapLevel = function () { + if ( i !== 32 ) { - console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' ); - return this.getActiveMipmapLevel(); + offsetTable[ i ] = 1024; -}; + } -Object.defineProperties( WebGLRenderer.prototype, { + } - shadowMapEnabled: { - get: function () { + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable + }; - return this.shadowMap.enabled; +} - }, - set: function ( value ) { +// float32 to float16 - console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); - this.shadowMap.enabled = value; +function toHalfFloat( val ) { - } - }, - shadowMapType: { - get: function () { + if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); - return this.shadowMap.type; + val = clamp( val, - 65504, 65504 ); - }, - set: function ( value ) { + _tables.floatView[ 0 ] = val; + const f = _tables.uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] ); - console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); - this.shadowMap.type = value; +} - } - }, - shadowMapCullFace: { - get: function () { +// float16 to float32 - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; +function fromHalfFloat( val ) { - }, - set: function ( /* value */ ) { + const m = val >> 10; + _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ]; + return _tables.floatView[ 0 ]; - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); +} - } - }, - context: { - get: function () { +var DataUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + toHalfFloat: toHalfFloat, + fromHalfFloat: fromHalfFloat +}); - console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' ); - return this.getContext(); +// r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0 - } - }, - vr: { - get: function () { +function ImmediateRenderObject() { - console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' ); - return this.xr; + console.error( 'THREE.ImmediateRenderObject has been removed.' ); - } - }, - gammaInput: { - get: function () { +} - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); - return false; +// r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17 - }, - set: function () { +class WebGLMultisampleRenderTarget extends WebGLRenderTarget { - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); + constructor( width, height, options ) { - } - }, - gammaOutput: { - get: function () { + console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' ); + super( width, height, options ); + this.samples = 4; - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - return false; + } - }, - set: function ( value ) { +} - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding; +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce - } - }, - toneMappingWhitePoint: { - get: function () { +class DataTexture2DArray extends DataArrayTexture { - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); - return 1.0; + constructor( data, width, height, depth ) { - }, - set: function () { + console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' ); + super( data, width, height, depth ); - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); + } - } - }, +} -} ); +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce -Object.defineProperties( WebGLShadowMap.prototype, { +class DataTexture3D extends Data3DTexture { - cullFace: { - get: function () { + constructor( data, width, height, depth ) { - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; + console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' ); + super( data, width, height, depth ); - }, - set: function ( /* cullFace */ ) { + } - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); +} - } - }, - renderReverseSided: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - return undefined; +class BoxBufferGeometry extends BoxGeometry { - }, - set: function () { + constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) { - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); + console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' ); + super( width, height, depth, widthSegments, heightSegments, depthSegments ); - } - }, - renderSingleSided: { - get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - return undefined; + } - }, - set: function () { +} - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); +// r144 - } - } +class CapsuleBufferGeometry extends CapsuleGeometry { -} ); + constructor( radius, length, capSegments, radialSegments ) { -function WebGLRenderTargetCube( width, height, options ) { + console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' ); + super( radius, length, capSegments, radialSegments ); - console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' ); - return new WebGLCubeRenderTarget( width, options ); + } } -// - -Object.defineProperties( WebGLRenderTarget.prototype, { +// r144 - wrapS: { - get: function () { +class CircleBufferGeometry extends CircleGeometry { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - return this.texture.wrapS; - - }, - set: function ( value ) { + constructor( radius, segments, thetaStart, thetaLength ) { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - this.texture.wrapS = value; + console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' ); + super( radius, segments, thetaStart, thetaLength ); - } - }, - wrapT: { - get: function () { + } - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - return this.texture.wrapT; +} - }, - set: function ( value ) { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - this.texture.wrapT = value; +class ConeBufferGeometry extends ConeGeometry { - } - }, - magFilter: { - get: function () { + constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - return this.texture.magFilter; + console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' ); + super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - }, - set: function ( value ) { + } - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - this.texture.magFilter = value; +} - } - }, - minFilter: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - return this.texture.minFilter; +class CylinderBufferGeometry extends CylinderGeometry { - }, - set: function ( value ) { + constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - this.texture.minFilter = value; + console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' ); + super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - } - }, - anisotropy: { - get: function () { + } - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - return this.texture.anisotropy; +} - }, - set: function ( value ) { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - this.texture.anisotropy = value; +class DodecahedronBufferGeometry extends DodecahedronGeometry { - } - }, - offset: { - get: function () { + constructor( radius, detail ) { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - return this.texture.offset; + console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' ); + super( radius, detail ); - }, - set: function ( value ) { + } - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - this.texture.offset = value; +} - } - }, - repeat: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - return this.texture.repeat; +class ExtrudeBufferGeometry extends ExtrudeGeometry { - }, - set: function ( value ) { + constructor( shapes, options ) { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - this.texture.repeat = value; + console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' ); + super( shapes, options ); - } - }, - format: { - get: function () { + } - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - return this.texture.format; +} - }, - set: function ( value ) { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - this.texture.format = value; +class IcosahedronBufferGeometry extends IcosahedronGeometry { - } - }, - type: { - get: function () { + constructor( radius, detail ) { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - return this.texture.type; + console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' ); + super( radius, detail ); - }, - set: function ( value ) { + } - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - this.texture.type = value; +} - } - }, - generateMipmaps: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - return this.texture.generateMipmaps; +class LatheBufferGeometry extends LatheGeometry { - }, - set: function ( value ) { + constructor( points, segments, phiStart, phiLength ) { - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - this.texture.generateMipmaps = value; + console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' ); + super( points, segments, phiStart, phiLength ); - } } -} ); - -// +} -Object.defineProperties( Audio.prototype, { +// r144 - load: { - value: function ( file ) { +class OctahedronBufferGeometry extends OctahedronGeometry { - console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); - const scope = this; - const audioLoader = new AudioLoader(); - audioLoader.load( file, function ( buffer ) { + constructor( radius, detail ) { - scope.setBuffer( buffer ); + console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' ); + super( radius, detail ); - } ); - return this; + } - } - }, - startTime: { - set: function () { +} - console.warn( 'THREE.Audio: .startTime is now .play( delay ).' ); +// r144 - } - } +class PlaneBufferGeometry extends PlaneGeometry { -} ); + constructor( width, height, widthSegments, heightSegments ) { -AudioAnalyser.prototype.getData = function () { + console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' ); + super( width, height, widthSegments, heightSegments ); - console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); - return this.getFrequencyData(); + } -}; +} -// +// r144 -CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { +class PolyhedronBufferGeometry extends PolyhedronGeometry { - console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); - return this.update( renderer, scene ); + constructor( vertices, indices, radius, detail ) { -}; + console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' ); + super( vertices, indices, radius, detail ); -CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) { + } - console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' ); - return this.renderTarget.clear( renderer, color, depth, stencil ); +} -}; +// r144 -ImageUtils.crossOrigin = undefined; +class RingBufferGeometry extends RingGeometry { -ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) { + constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); + console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' ); + super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ); - const loader = new TextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); + } - const texture = loader.load( url, onLoad, undefined, onError ); +} - if ( mapping ) texture.mapping = mapping; +// r144 - return texture; +class ShapeBufferGeometry extends ShapeGeometry { -}; + constructor( shapes, curveSegments ) { -ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) { + console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' ); + super( shapes, curveSegments ); - console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); + } - const loader = new CubeTextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); +} - const texture = loader.load( urls, onLoad, undefined, onError ); +// r144 - if ( mapping ) texture.mapping = mapping; +class SphereBufferGeometry extends SphereGeometry { - return texture; + constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { -}; + console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' ); + super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ); -ImageUtils.loadCompressedTexture = function () { + } - console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); +} -}; +// r144 -ImageUtils.loadCompressedTextureCube = function () { +class TetrahedronBufferGeometry extends TetrahedronGeometry { - console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); + constructor( radius, detail ) { -}; + console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' ); + super( radius, detail ); -// + } -function CanvasRenderer() { +} - console.error( 'THREE.CanvasRenderer has been removed' ); +// r144 -} +class TorusBufferGeometry extends TorusGeometry { -// + constructor( radius, tube, radialSegments, tubularSegments, arc ) { -function JSONLoader() { + console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' ); + super( radius, tube, radialSegments, tubularSegments, arc ); - console.error( 'THREE.JSONLoader has been removed.' ); + } } -// +// r144 -const SceneUtils = { +class TorusKnotBufferGeometry extends TorusKnotGeometry { - createMultiMaterialObject: function ( /* geometry, materials */ ) { + constructor( radius, tube, tubularSegments, radialSegments, p, q ) { - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); + console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' ); + super( radius, tube, tubularSegments, radialSegments, p, q ); - }, + } - detach: function ( /* child, parent, scene */ ) { +} - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); +// r144 - }, +class TubeBufferGeometry extends TubeGeometry { - attach: function ( /* child, scene, parent */ ) { + constructor( path, tubularSegments, radius, radialSegments, closed ) { - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); + console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' ); + super( path, tubularSegments, radius, radialSegments, closed ); } -}; - -// - -function LensFlare() { - - console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' ); - } if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - /* eslint-disable no-undef */ __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { revision: REVISION, } } ) ); - /* eslint-enable no-undef */ } @@ -48957,18 +49675,15 @@ var THREE = /*#__PURE__*/Object.freeze({ AudioListener: AudioListener, AudioLoader: AudioLoader, AxesHelper: AxesHelper, - AxisHelper: AxisHelper, BackSide: BackSide, BasicDepthPacking: BasicDepthPacking, BasicShadowMap: BasicShadowMap, - BinaryTextureLoader: BinaryTextureLoader, Bone: Bone, BooleanKeyframeTrack: BooleanKeyframeTrack, - BoundingBoxHelper: BoundingBoxHelper, Box2: Box2, Box3: Box3, Box3Helper: Box3Helper, - BoxBufferGeometry: BoxGeometry, + BoxBufferGeometry: BoxBufferGeometry, BoxGeometry: BoxGeometry, BoxHelper: BoxHelper, BufferAttribute: BufferAttribute, @@ -48978,19 +49693,21 @@ var THREE = /*#__PURE__*/Object.freeze({ Cache: Cache, Camera: Camera, CameraHelper: CameraHelper, - CanvasRenderer: CanvasRenderer, CanvasTexture: CanvasTexture, + CapsuleBufferGeometry: CapsuleBufferGeometry, + CapsuleGeometry: CapsuleGeometry, CatmullRomCurve3: CatmullRomCurve3, CineonToneMapping: CineonToneMapping, - CircleBufferGeometry: CircleGeometry, + CircleBufferGeometry: CircleBufferGeometry, CircleGeometry: CircleGeometry, ClampToEdgeWrapping: ClampToEdgeWrapping, Clock: Clock, Color: Color, ColorKeyframeTrack: ColorKeyframeTrack, + ColorManagement: ColorManagement, CompressedTexture: CompressedTexture, CompressedTextureLoader: CompressedTextureLoader, - ConeBufferGeometry: ConeGeometry, + ConeBufferGeometry: ConeBufferGeometry, ConeGeometry: ConeGeometry, CubeCamera: CubeCamera, CubeReflectionMapping: CubeReflectionMapping, @@ -48998,7 +49715,6 @@ var THREE = /*#__PURE__*/Object.freeze({ CubeTexture: CubeTexture, CubeTextureLoader: CubeTextureLoader, CubeUVReflectionMapping: CubeUVReflectionMapping, - CubeUVRefractionMapping: CubeUVRefractionMapping, CubicBezierCurve: CubicBezierCurve, CubicBezierCurve3: CubicBezierCurve3, CubicInterpolant: CubicInterpolant, @@ -49010,9 +49726,11 @@ var THREE = /*#__PURE__*/Object.freeze({ CurvePath: CurvePath, CustomBlending: CustomBlending, CustomToneMapping: CustomToneMapping, - CylinderBufferGeometry: CylinderGeometry, + CylinderBufferGeometry: CylinderBufferGeometry, CylinderGeometry: CylinderGeometry, Cylindrical: Cylindrical, + Data3DTexture: Data3DTexture, + DataArrayTexture: DataArrayTexture, DataTexture: DataTexture, DataTexture2DArray: DataTexture2DArray, DataTexture3D: DataTexture3D, @@ -49027,17 +49745,15 @@ var THREE = /*#__PURE__*/Object.freeze({ DirectionalLight: DirectionalLight, DirectionalLightHelper: DirectionalLightHelper, DiscreteInterpolant: DiscreteInterpolant, - DodecahedronBufferGeometry: DodecahedronGeometry, + DodecahedronBufferGeometry: DodecahedronBufferGeometry, DodecahedronGeometry: DodecahedronGeometry, DoubleSide: DoubleSide, DstAlphaFactor: DstAlphaFactor, DstColorFactor: DstColorFactor, - DynamicBufferAttribute: DynamicBufferAttribute, DynamicCopyUsage: DynamicCopyUsage, DynamicDrawUsage: DynamicDrawUsage, DynamicReadUsage: DynamicReadUsage, EdgesGeometry: EdgesGeometry, - EdgesHelper: EdgesHelper, EllipseCurve: EllipseCurve, EqualDepth: EqualDepth, EqualStencilFunc: EqualStencilFunc, @@ -49045,27 +49761,21 @@ var THREE = /*#__PURE__*/Object.freeze({ EquirectangularRefractionMapping: EquirectangularRefractionMapping, Euler: Euler, EventDispatcher: EventDispatcher, - ExtrudeBufferGeometry: ExtrudeGeometry, + ExtrudeBufferGeometry: ExtrudeBufferGeometry, ExtrudeGeometry: ExtrudeGeometry, - FaceColors: FaceColors, FileLoader: FileLoader, - FlatShading: FlatShading, Float16BufferAttribute: Float16BufferAttribute, - Float32Attribute: Float32Attribute, Float32BufferAttribute: Float32BufferAttribute, - Float64Attribute: Float64Attribute, Float64BufferAttribute: Float64BufferAttribute, FloatType: FloatType, Fog: Fog, FogExp2: FogExp2, - Font: Font, - FontLoader: FontLoader, + FramebufferTexture: FramebufferTexture, FrontSide: FrontSide, Frustum: Frustum, GLBufferAttribute: GLBufferAttribute, GLSL1: GLSL1, GLSL3: GLSL3, - GammaEncoding: GammaEncoding, GreaterDepth: GreaterDepth, GreaterEqualDepth: GreaterEqualDepth, GreaterEqualStencilFunc: GreaterEqualStencilFunc, @@ -49076,7 +49786,7 @@ var THREE = /*#__PURE__*/Object.freeze({ HemisphereLight: HemisphereLight, HemisphereLightHelper: HemisphereLightHelper, HemisphereLightProbe: HemisphereLightProbe, - IcosahedronBufferGeometry: IcosahedronGeometry, + IcosahedronBufferGeometry: IcosahedronBufferGeometry, IcosahedronGeometry: IcosahedronGeometry, ImageBitmapLoader: ImageBitmapLoader, ImageLoader: ImageLoader, @@ -49088,11 +49798,8 @@ var THREE = /*#__PURE__*/Object.freeze({ InstancedBufferGeometry: InstancedBufferGeometry, InstancedInterleavedBuffer: InstancedInterleavedBuffer, InstancedMesh: InstancedMesh, - Int16Attribute: Int16Attribute, Int16BufferAttribute: Int16BufferAttribute, - Int32Attribute: Int32Attribute, Int32BufferAttribute: Int32BufferAttribute, - Int8Attribute: Int8Attribute, Int8BufferAttribute: Int8BufferAttribute, IntType: IntType, InterleavedBuffer: InterleavedBuffer, @@ -49102,14 +49809,12 @@ var THREE = /*#__PURE__*/Object.freeze({ InterpolateLinear: InterpolateLinear, InterpolateSmooth: InterpolateSmooth, InvertStencilOp: InvertStencilOp, - JSONLoader: JSONLoader, KeepStencilOp: KeepStencilOp, KeyframeTrack: KeyframeTrack, LOD: LOD, - LatheBufferGeometry: LatheGeometry, + LatheBufferGeometry: LatheBufferGeometry, LatheGeometry: LatheGeometry, Layers: Layers, - LensFlare: LensFlare, LessDepth: LessDepth, LessEqualDepth: LessEqualDepth, LessEqualStencilFunc: LessEqualStencilFunc, @@ -49123,9 +49828,7 @@ var THREE = /*#__PURE__*/Object.freeze({ LineCurve3: LineCurve3, LineDashedMaterial: LineDashedMaterial, LineLoop: LineLoop, - LinePieces: LinePieces, LineSegments: LineSegments, - LineStrip: LineStrip, LinearEncoding: LinearEncoding, LinearFilter: LinearFilter, LinearInterpolant: LinearInterpolant, @@ -49133,11 +49836,11 @@ var THREE = /*#__PURE__*/Object.freeze({ LinearMipMapNearestFilter: LinearMipMapNearestFilter, LinearMipmapLinearFilter: LinearMipmapLinearFilter, LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearSRGBColorSpace: LinearSRGBColorSpace, LinearToneMapping: LinearToneMapping, Loader: Loader, LoaderUtils: LoaderUtils, LoadingManager: LoadingManager, - LogLuvEncoding: LogLuvEncoding, LoopOnce: LoopOnce, LoopPingPong: LoopPingPong, LoopRepeat: LoopRepeat, @@ -49146,7 +49849,6 @@ var THREE = /*#__PURE__*/Object.freeze({ MOUSE: MOUSE, Material: Material, MaterialLoader: MaterialLoader, - Math: MathUtils, MathUtils: MathUtils, Matrix3: Matrix3, Matrix4: Matrix4, @@ -49155,7 +49857,6 @@ var THREE = /*#__PURE__*/Object.freeze({ MeshBasicMaterial: MeshBasicMaterial, MeshDepthMaterial: MeshDepthMaterial, MeshDistanceMaterial: MeshDistanceMaterial, - MeshFaceMaterial: MeshFaceMaterial, MeshLambertMaterial: MeshLambertMaterial, MeshMatcapMaterial: MeshMatcapMaterial, MeshNormalMaterial: MeshNormalMaterial, @@ -49166,7 +49867,6 @@ var THREE = /*#__PURE__*/Object.freeze({ MinEquation: MinEquation, MirroredRepeatWrapping: MirroredRepeatWrapping, MixOperation: MixOperation, - MultiMaterial: MultiMaterial, MultiplyBlending: MultiplyBlending, MultiplyOperation: MultiplyOperation, NearestFilter: NearestFilter, @@ -49177,7 +49877,7 @@ var THREE = /*#__PURE__*/Object.freeze({ NeverDepth: NeverDepth, NeverStencilFunc: NeverStencilFunc, NoBlending: NoBlending, - NoColors: NoColors, + NoColorSpace: NoColorSpace, NoToneMapping: NoToneMapping, NormalAnimationBlendMode: NormalAnimationBlendMode, NormalBlending: NormalBlending, @@ -49187,7 +49887,7 @@ var THREE = /*#__PURE__*/Object.freeze({ Object3D: Object3D, ObjectLoader: ObjectLoader, ObjectSpaceNormalMap: ObjectSpaceNormalMap, - OctahedronBufferGeometry: OctahedronGeometry, + OctahedronBufferGeometry: OctahedronBufferGeometry, OctahedronGeometry: OctahedronGeometry, OneFactor: OneFactor, OneMinusDstAlphaFactor: OneMinusDstAlphaFactor, @@ -49198,26 +49898,18 @@ var THREE = /*#__PURE__*/Object.freeze({ PCFShadowMap: PCFShadowMap, PCFSoftShadowMap: PCFSoftShadowMap, PMREMGenerator: PMREMGenerator, - ParametricBufferGeometry: ParametricGeometry, - ParametricGeometry: ParametricGeometry, - Particle: Particle, - ParticleBasicMaterial: ParticleBasicMaterial, - ParticleSystem: ParticleSystem, - ParticleSystemMaterial: ParticleSystemMaterial, Path: Path, PerspectiveCamera: PerspectiveCamera, Plane: Plane, - PlaneBufferGeometry: PlaneGeometry, + PlaneBufferGeometry: PlaneBufferGeometry, PlaneGeometry: PlaneGeometry, PlaneHelper: PlaneHelper, - PointCloud: PointCloud, - PointCloudMaterial: PointCloudMaterial, PointLight: PointLight, PointLightHelper: PointLightHelper, Points: Points, PointsMaterial: PointsMaterial, PolarGridHelper: PolarGridHelper, - PolyhedronBufferGeometry: PolyhedronGeometry, + PolyhedronBufferGeometry: PolyhedronBufferGeometry, PolyhedronGeometry: PolyhedronGeometry, PositionalAudio: PositionalAudio, PropertyBinding: PropertyBinding, @@ -49252,13 +49944,7 @@ var THREE = /*#__PURE__*/Object.freeze({ RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, - RGBDEncoding: RGBDEncoding, - RGBEEncoding: RGBEEncoding, - RGBEFormat: RGBEFormat, RGBFormat: RGBFormat, - RGBIntegerFormat: RGBIntegerFormat, - RGBM16Encoding: RGBM16Encoding, - RGBM7Encoding: RGBM7Encoding, RGB_ETC1_Format: RGB_ETC1_Format, RGB_ETC2_Format: RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format, @@ -49276,30 +49962,16 @@ var THREE = /*#__PURE__*/Object.freeze({ RepeatWrapping: RepeatWrapping, ReplaceStencilOp: ReplaceStencilOp, ReverseSubtractEquation: ReverseSubtractEquation, - RingBufferGeometry: RingGeometry, + RingBufferGeometry: RingBufferGeometry, RingGeometry: RingGeometry, - SRGB8_ALPHA8_ASTC_10x10_Format: SRGB8_ALPHA8_ASTC_10x10_Format, - SRGB8_ALPHA8_ASTC_10x5_Format: SRGB8_ALPHA8_ASTC_10x5_Format, - SRGB8_ALPHA8_ASTC_10x6_Format: SRGB8_ALPHA8_ASTC_10x6_Format, - SRGB8_ALPHA8_ASTC_10x8_Format: SRGB8_ALPHA8_ASTC_10x8_Format, - SRGB8_ALPHA8_ASTC_12x10_Format: SRGB8_ALPHA8_ASTC_12x10_Format, - SRGB8_ALPHA8_ASTC_12x12_Format: SRGB8_ALPHA8_ASTC_12x12_Format, - SRGB8_ALPHA8_ASTC_4x4_Format: SRGB8_ALPHA8_ASTC_4x4_Format, - SRGB8_ALPHA8_ASTC_5x4_Format: SRGB8_ALPHA8_ASTC_5x4_Format, - SRGB8_ALPHA8_ASTC_5x5_Format: SRGB8_ALPHA8_ASTC_5x5_Format, - SRGB8_ALPHA8_ASTC_6x5_Format: SRGB8_ALPHA8_ASTC_6x5_Format, - SRGB8_ALPHA8_ASTC_6x6_Format: SRGB8_ALPHA8_ASTC_6x6_Format, - SRGB8_ALPHA8_ASTC_8x5_Format: SRGB8_ALPHA8_ASTC_8x5_Format, - SRGB8_ALPHA8_ASTC_8x6_Format: SRGB8_ALPHA8_ASTC_8x6_Format, - SRGB8_ALPHA8_ASTC_8x8_Format: SRGB8_ALPHA8_ASTC_8x8_Format, + SRGBColorSpace: SRGBColorSpace, Scene: Scene, - SceneUtils: SceneUtils, ShaderChunk: ShaderChunk, ShaderLib: ShaderLib, ShaderMaterial: ShaderMaterial, ShadowMaterial: ShadowMaterial, Shape: Shape, - ShapeBufferGeometry: ShapeGeometry, + ShapeBufferGeometry: ShapeBufferGeometry, ShapeGeometry: ShapeGeometry, ShapePath: ShapePath, ShapeUtils: ShapeUtils, @@ -49307,9 +49979,9 @@ var THREE = /*#__PURE__*/Object.freeze({ Skeleton: Skeleton, SkeletonHelper: SkeletonHelper, SkinnedMesh: SkinnedMesh, - SmoothShading: SmoothShading, + Source: Source, Sphere: Sphere, - SphereBufferGeometry: SphereGeometry, + SphereBufferGeometry: SphereBufferGeometry, SphereGeometry: SphereGeometry, Spherical: Spherical, SphericalHarmonics3: SphericalHarmonics3, @@ -49333,32 +50005,27 @@ var THREE = /*#__PURE__*/Object.freeze({ SubtractiveBlending: SubtractiveBlending, TOUCH: TOUCH, TangentSpaceNormalMap: TangentSpaceNormalMap, - TetrahedronBufferGeometry: TetrahedronGeometry, + TetrahedronBufferGeometry: TetrahedronBufferGeometry, TetrahedronGeometry: TetrahedronGeometry, - TextBufferGeometry: TextGeometry, - TextGeometry: TextGeometry, Texture: Texture, TextureLoader: TextureLoader, - TorusBufferGeometry: TorusGeometry, + TorusBufferGeometry: TorusBufferGeometry, TorusGeometry: TorusGeometry, - TorusKnotBufferGeometry: TorusKnotGeometry, + TorusKnotBufferGeometry: TorusKnotBufferGeometry, TorusKnotGeometry: TorusKnotGeometry, Triangle: Triangle, TriangleFanDrawMode: TriangleFanDrawMode, TriangleStripDrawMode: TriangleStripDrawMode, TrianglesDrawMode: TrianglesDrawMode, - TubeBufferGeometry: TubeGeometry, + TubeBufferGeometry: TubeBufferGeometry, TubeGeometry: TubeGeometry, UVMapping: UVMapping, - Uint16Attribute: Uint16Attribute, Uint16BufferAttribute: Uint16BufferAttribute, - Uint32Attribute: Uint32Attribute, Uint32BufferAttribute: Uint32BufferAttribute, - Uint8Attribute: Uint8Attribute, Uint8BufferAttribute: Uint8BufferAttribute, - Uint8ClampedAttribute: Uint8ClampedAttribute, Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute, Uniform: Uniform, + UniformsGroup: UniformsGroup, UniformsLib: UniformsLib, UniformsUtils: UniformsUtils, UnsignedByteType: UnsignedByteType, @@ -49366,31 +50033,29 @@ var THREE = /*#__PURE__*/Object.freeze({ UnsignedIntType: UnsignedIntType, UnsignedShort4444Type: UnsignedShort4444Type, UnsignedShort5551Type: UnsignedShort5551Type, - UnsignedShort565Type: UnsignedShort565Type, UnsignedShortType: UnsignedShortType, VSMShadowMap: VSMShadowMap, Vector2: Vector2, Vector3: Vector3, Vector4: Vector4, VectorKeyframeTrack: VectorKeyframeTrack, - Vertex: Vertex, - VertexColors: VertexColors, VideoTexture: VideoTexture, WebGL1Renderer: WebGL1Renderer, + WebGL3DRenderTarget: WebGL3DRenderTarget, + WebGLArrayRenderTarget: WebGLArrayRenderTarget, WebGLCubeRenderTarget: WebGLCubeRenderTarget, + WebGLMultipleRenderTargets: WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget, WebGLRenderTarget: WebGLRenderTarget, - WebGLRenderTargetCube: WebGLRenderTargetCube, WebGLRenderer: WebGLRenderer, WebGLUtils: WebGLUtils, WireframeGeometry: WireframeGeometry, - WireframeHelper: WireframeHelper, WrapAroundEnding: WrapAroundEnding, - XHRLoader: XHRLoader, ZeroCurvatureEnding: ZeroCurvatureEnding, ZeroFactor: ZeroFactor, ZeroSlopeEnding: ZeroSlopeEnding, ZeroStencilOp: ZeroStencilOp, + _SRGBAFormat: _SRGBAFormat, sRGBEncoding: sRGBEncoding }); @@ -49401,1190 +50066,1207 @@ var THREE = /*#__PURE__*/Object.freeze({ // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move -var OrbitControls = function ( object, domElement ) { +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; - if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); - if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); +class OrbitControls extends EventDispatcher { - this.object = object; - this.domElement = domElement; + constructor( object, domElement ) { - // Set to false to disable this control - this.enabled = true; + super(); - // "target" sets the location of focus, where the object orbits around - this.target = new Vector3(); + this.object = object; + this.domElement = domElement; + this.domElement.style.touchAction = 'none'; // disable touch scroll - // How far you can dolly in and out ( PerspectiveCamera only ) - this.minDistance = 0; - this.maxDistance = Infinity; + // Set to false to disable this control + this.enabled = true; - // How far you can zoom in and out ( OrthographicCamera only ) - this.minZoom = 0; - this.maxZoom = Infinity; + // "target" sets the location of focus, where the object orbits around + this.target = new Vector3(); - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - this.minPolarAngle = 0; // radians - this.maxPolarAngle = Math.PI; // radians + // How far you can dolly in and out ( PerspectiveCamera only ) + this.minDistance = 0; + this.maxDistance = Infinity; - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - this.minAzimuthAngle = - Infinity; // radians - this.maxAzimuthAngle = Infinity; // radians + // How far you can zoom in and out ( OrthographicCamera only ) + this.minZoom = 0; + this.maxZoom = Infinity; - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - this.enableDamping = false; - this.dampingFactor = 0.05; + // How far you can orbit vertically, upper and lower limits. + // Range is 0 to Math.PI radians. + this.minPolarAngle = 0; // radians + this.maxPolarAngle = Math.PI; // radians - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - this.enableZoom = true; - this.zoomSpeed = 1.0; + // How far you can orbit horizontally, upper and lower limits. + // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) + this.minAzimuthAngle = - Infinity; // radians + this.maxAzimuthAngle = Infinity; // radians - // Set to false to disable rotating - this.enableRotate = true; - this.rotateSpeed = 1.0; + // Set to true to enable damping (inertia) + // If damping is enabled, you must call controls.update() in your animation loop + this.enableDamping = false; + this.dampingFactor = 0.05; - // Set to false to disable panning - this.enablePan = true; - this.panSpeed = 1.0; - this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up - this.keyPanSpeed = 7.0; // pixels moved per arrow key push + // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. + // Set to false to disable zooming + this.enableZoom = true; + this.zoomSpeed = 1.0; - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - this.autoRotate = false; - this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 + // Set to false to disable rotating + this.enableRotate = true; + this.rotateSpeed = 1.0; - // The four arrow keys - this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; + // Set to false to disable panning + this.enablePan = true; + this.panSpeed = 1.0; + this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up + this.keyPanSpeed = 7.0; // pixels moved per arrow key push - // Mouse buttons - this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + // Set to true to automatically rotate around the target + // If auto-rotate is enabled, you must call controls.update() in your animation loop + this.autoRotate = false; + this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 - // Touch fingers - this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + // The four arrow keys + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; - // for reset - this.target0 = this.target.clone(); - this.position0 = this.object.position.clone(); - this.zoom0 = this.object.zoom; + // Mouse buttons + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; - // the target DOM element for key events - this._domElementKeyEvents = null; + // Touch fingers + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; - // - // public methods - // + // for reset + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; - this.getPolarAngle = function () { + // the target DOM element for key events + this._domElementKeyEvents = null; - return spherical.phi; + // + // public methods + // - }; + this.getPolarAngle = function () { - this.getAzimuthalAngle = function () { + return spherical.phi; - return spherical.theta; + }; - }; + this.getAzimuthalAngle = function () { - this.listenToKeyEvents = function ( domElement ) { + return spherical.theta; - domElement.addEventListener( 'keydown', onKeyDown ); - this._domElementKeyEvents = domElement; + }; - }; + this.getDistance = function () { - this.saveState = function () { + return this.object.position.distanceTo( this.target ); - scope.target0.copy( scope.target ); - scope.position0.copy( scope.object.position ); - scope.zoom0 = scope.object.zoom; + }; - }; + this.listenToKeyEvents = function ( domElement ) { - this.reset = function () { + domElement.addEventListener( 'keydown', onKeyDown ); + this._domElementKeyEvents = domElement; - scope.target.copy( scope.target0 ); - scope.object.position.copy( scope.position0 ); - scope.object.zoom = scope.zoom0; + }; - scope.object.updateProjectionMatrix(); - scope.dispatchEvent( changeEvent ); + this.saveState = function () { - scope.update(); + scope.target0.copy( scope.target ); + scope.position0.copy( scope.object.position ); + scope.zoom0 = scope.object.zoom; - state = STATE.NONE; + }; - }; + this.reset = function () { - // this method is exposed, but perhaps it would be better if we can make it private... - this.update = function () { + scope.target.copy( scope.target0 ); + scope.object.position.copy( scope.position0 ); + scope.object.zoom = scope.zoom0; - var offset = new Vector3(); + scope.object.updateProjectionMatrix(); + scope.dispatchEvent( _changeEvent ); - // so camera.up is the orbit axis - var quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); - var quatInverse = quat.clone().invert(); + scope.update(); - var lastPosition = new Vector3(); - var lastQuaternion = new Quaternion(); + state = STATE.NONE; - var twoPI = 2 * Math.PI; + }; - return function update() { + // this method is exposed, but perhaps it would be better if we can make it private... + this.update = function () { - var position = scope.object.position; + const offset = new Vector3(); - offset.copy( position ).sub( scope.target ); + // so camera.up is the orbit axis + const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + const quatInverse = quat.clone().invert(); - // rotate offset to "y-axis-is-up" space - offset.applyQuaternion( quat ); + const lastPosition = new Vector3(); + const lastQuaternion = new Quaternion(); - // angle from z-axis around y-axis - spherical.setFromVector3( offset ); + const twoPI = 2 * Math.PI; - if ( scope.autoRotate && state === STATE.NONE ) { + return function update() { - rotateLeft( getAutoRotationAngle() ); + const position = scope.object.position; - } + offset.copy( position ).sub( scope.target ); - if ( scope.enableDamping ) { + // rotate offset to "y-axis-is-up" space + offset.applyQuaternion( quat ); - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; + // angle from z-axis around y-axis + spherical.setFromVector3( offset ); - } else { + if ( scope.autoRotate && state === STATE.NONE ) { - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; + rotateLeft( getAutoRotationAngle() ); - } + } - // restrict theta to be between desired limits + if ( scope.enableDamping ) { - var min = scope.minAzimuthAngle; - var max = scope.maxAzimuthAngle; + spherical.theta += sphericalDelta.theta * scope.dampingFactor; + spherical.phi += sphericalDelta.phi * scope.dampingFactor; - if ( isFinite( min ) && isFinite( max ) ) { + } else { - if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; + spherical.theta += sphericalDelta.theta; + spherical.phi += sphericalDelta.phi; - if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; + } - if ( min <= max ) { + // restrict theta to be between desired limits - spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); + let min = scope.minAzimuthAngle; + let max = scope.maxAzimuthAngle; - } else { + if ( isFinite( min ) && isFinite( max ) ) { + + if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; + + if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; - spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? - Math.max( min, spherical.theta ) : - Math.min( max, spherical.theta ); + if ( min <= max ) { + + spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); + + } else { + + spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, spherical.theta ) : + Math.min( max, spherical.theta ); + + } } - } + // restrict phi to be between desired limits + spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); - // restrict phi to be between desired limits - spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); + spherical.makeSafe(); - spherical.makeSafe(); + spherical.radius *= scale; - spherical.radius *= scale; + // restrict radius to be between desired limits + spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); - // restrict radius to be between desired limits - spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); + // move target to panned location - // move target to panned location + if ( scope.enableDamping === true ) { - if ( scope.enableDamping === true ) { + scope.target.addScaledVector( panOffset, scope.dampingFactor ); - scope.target.addScaledVector( panOffset, scope.dampingFactor ); + } else { - } else { + scope.target.add( panOffset ); - scope.target.add( panOffset ); + } - } + offset.setFromSpherical( spherical ); - offset.setFromSpherical( spherical ); + // rotate offset back to "camera-up-vector-is-up" space + offset.applyQuaternion( quatInverse ); - // rotate offset back to "camera-up-vector-is-up" space - offset.applyQuaternion( quatInverse ); + position.copy( scope.target ).add( offset ); - position.copy( scope.target ).add( offset ); + scope.object.lookAt( scope.target ); - scope.object.lookAt( scope.target ); + if ( scope.enableDamping === true ) { - if ( scope.enableDamping === true ) { + sphericalDelta.theta *= ( 1 - scope.dampingFactor ); + sphericalDelta.phi *= ( 1 - scope.dampingFactor ); - sphericalDelta.theta *= ( 1 - scope.dampingFactor ); - sphericalDelta.phi *= ( 1 - scope.dampingFactor ); + panOffset.multiplyScalar( 1 - scope.dampingFactor ); - panOffset.multiplyScalar( 1 - scope.dampingFactor ); + } else { - } else { + sphericalDelta.set( 0, 0, 0 ); - sphericalDelta.set( 0, 0, 0 ); + panOffset.set( 0, 0, 0 ); - panOffset.set( 0, 0, 0 ); + } - } + scale = 1; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + lastPosition.distanceToSquared( scope.object.position ) > EPS || + 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastQuaternion.copy( scope.object.quaternion ); + zoomChanged = false; + + return true; + + } + + return false; + + }; + + }(); + + this.dispose = function () { - scale = 1; + scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); - // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); + scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.removeEventListener( 'wheel', onMouseWheel ); - if ( zoomChanged || - lastPosition.distanceToSquared( scope.object.position ) > EPS || - 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - scope.dispatchEvent( changeEvent ); - lastPosition.copy( scope.object.position ); - lastQuaternion.copy( scope.object.quaternion ); - zoomChanged = false; + if ( scope._domElementKeyEvents !== null ) { - return true; + scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); } - return false; + //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? }; - }(); + // + // internals + // - this.dispose = function () { + const scope = this; - scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); + const STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 + }; - scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); - scope.domElement.removeEventListener( 'wheel', onMouseWheel ); + let state = STATE.NONE; - scope.domElement.removeEventListener( 'touchstart', onTouchStart ); - scope.domElement.removeEventListener( 'touchend', onTouchEnd ); - scope.domElement.removeEventListener( 'touchmove', onTouchMove ); + const EPS = 0.000001; - scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp ); + // current position in spherical coordinates + const spherical = new Spherical(); + const sphericalDelta = new Spherical(); + let scale = 1; + const panOffset = new Vector3(); + let zoomChanged = false; - if ( scope._domElementKeyEvents !== null ) { + const rotateStart = new Vector2(); + const rotateEnd = new Vector2(); + const rotateDelta = new Vector2(); - scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); + const panStart = new Vector2(); + const panEnd = new Vector2(); + const panDelta = new Vector2(); - } + const dollyStart = new Vector2(); + const dollyEnd = new Vector2(); + const dollyDelta = new Vector2(); - //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? + const pointers = []; + const pointerPositions = {}; - }; + function getAutoRotationAngle() { - // - // internals - // + return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - var scope = this; - - var changeEvent = { type: 'change' }; - var startEvent = { type: 'start' }; - var endEvent = { type: 'end' }; - - var STATE = { - NONE: - 1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; + } - var state = STATE.NONE; + function getZoomScale() { - var EPS = 0.000001; + return Math.pow( 0.95, scope.zoomSpeed ); - // current position in spherical coordinates - var spherical = new Spherical(); - var sphericalDelta = new Spherical(); + } - var scale = 1; - var panOffset = new Vector3(); - var zoomChanged = false; + function rotateLeft( angle ) { - var rotateStart = new Vector2(); - var rotateEnd = new Vector2(); - var rotateDelta = new Vector2(); + sphericalDelta.theta -= angle; - var panStart = new Vector2(); - var panEnd = new Vector2(); - var panDelta = new Vector2(); + } - var dollyStart = new Vector2(); - var dollyEnd = new Vector2(); - var dollyDelta = new Vector2(); + function rotateUp( angle ) { - function getAutoRotationAngle() { + sphericalDelta.phi -= angle; - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; + } - } + const panLeft = function () { - function getZoomScale() { + const v = new Vector3(); - return Math.pow( 0.95, scope.zoomSpeed ); + return function panLeft( distance, objectMatrix ) { - } + v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + v.multiplyScalar( - distance ); - function rotateLeft( angle ) { + panOffset.add( v ); - sphericalDelta.theta -= angle; + }; - } + }(); - function rotateUp( angle ) { + const panUp = function () { - sphericalDelta.phi -= angle; + const v = new Vector3(); - } + return function panUp( distance, objectMatrix ) { - var panLeft = function () { + if ( scope.screenSpacePanning === true ) { - var v = new Vector3(); + v.setFromMatrixColumn( objectMatrix, 1 ); - return function panLeft( distance, objectMatrix ) { + } else { - v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix - v.multiplyScalar( - distance ); + v.setFromMatrixColumn( objectMatrix, 0 ); + v.crossVectors( scope.object.up, v ); - panOffset.add( v ); + } - }; + v.multiplyScalar( distance ); - }(); + panOffset.add( v ); - var panUp = function () { + }; - var v = new Vector3(); + }(); - return function panUp( distance, objectMatrix ) { + // deltaX and deltaY are in pixels; right and down are positive + const pan = function () { - if ( scope.screenSpacePanning === true ) { + const offset = new Vector3(); - v.setFromMatrixColumn( objectMatrix, 1 ); + return function pan( deltaX, deltaY ) { - } else { + const element = scope.domElement; - v.setFromMatrixColumn( objectMatrix, 0 ); - v.crossVectors( scope.object.up, v ); + if ( scope.object.isPerspectiveCamera ) { - } + // perspective + const position = scope.object.position; + offset.copy( position ).sub( scope.target ); + let targetDistance = offset.length(); - v.multiplyScalar( distance ); + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); - panOffset.add( v ); + // we use only clientHeight here so aspect ratio does not distort speed + panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); + panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); - }; + } else if ( scope.object.isOrthographicCamera ) { - }(); + // orthographic + panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); + panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); - // deltaX and deltaY are in pixels; right and down are positive - var pan = function () { + } else { - var offset = new Vector3(); + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + scope.enablePan = false; - return function pan( deltaX, deltaY ) { + } - var element = scope.domElement; + }; - if ( scope.object.isPerspectiveCamera ) { + }(); - // perspective - var position = scope.object.position; - offset.copy( position ).sub( scope.target ); - var targetDistance = offset.length(); + function dollyOut( dollyScale ) { - // half of the fov is center to top of screen - targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); + if ( scope.object.isPerspectiveCamera ) { - // we use only clientHeight here so aspect ratio does not distort speed - panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); - panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); + scale /= dollyScale; } else if ( scope.object.isOrthographicCamera ) { - // orthographic - panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); - panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; } else { - // camera neither orthographic nor perspective - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); - scope.enablePan = false; + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; } - }; + } - }(); + function dollyIn( dollyScale ) { - function dollyOut( dollyScale ) { + if ( scope.object.isPerspectiveCamera ) { - if ( scope.object.isPerspectiveCamera ) { + scale *= dollyScale; - scale /= dollyScale; + } else if ( scope.object.isOrthographicCamera ) { - } else if ( scope.object.isOrthographicCamera ) { + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; + } else { - } else { + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; + } } - } + // + // event callbacks - update the object state + // - function dollyIn( dollyScale ) { + function handleMouseDownRotate( event ) { - if ( scope.object.isPerspectiveCamera ) { + rotateStart.set( event.clientX, event.clientY ); - scale *= dollyScale; + } - } else if ( scope.object.isOrthographicCamera ) { + function handleMouseDownDolly( event ) { - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; + dollyStart.set( event.clientX, event.clientY ); - } else { + } - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; + function handleMouseDownPan( event ) { - } + panStart.set( event.clientX, event.clientY ); - } + } - // - // event callbacks - update the object state - // + function handleMouseMoveRotate( event ) { - function handleMouseDownRotate( event ) { + rotateEnd.set( event.clientX, event.clientY ); - rotateStart.set( event.clientX, event.clientY ); + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - } + const element = scope.domElement; - function handleMouseDownDolly( event ) { + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - dollyStart.set( event.clientX, event.clientY ); + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - } + rotateStart.copy( rotateEnd ); - function handleMouseDownPan( event ) { + scope.update(); - panStart.set( event.clientX, event.clientY ); + } - } + function handleMouseMoveDolly( event ) { - function handleMouseMoveRotate( event ) { + dollyEnd.set( event.clientX, event.clientY ); - rotateEnd.set( event.clientX, event.clientY ); + dollyDelta.subVectors( dollyEnd, dollyStart ); - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); + if ( dollyDelta.y > 0 ) { - var element = scope.domElement; + dollyOut( getZoomScale() ); - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height + } else if ( dollyDelta.y < 0 ) { - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); + dollyIn( getZoomScale() ); - rotateStart.copy( rotateEnd ); + } - scope.update(); + dollyStart.copy( dollyEnd ); - } + scope.update(); - function handleMouseMoveDolly( event ) { + } - dollyEnd.set( event.clientX, event.clientY ); + function handleMouseMovePan( event ) { - dollyDelta.subVectors( dollyEnd, dollyStart ); + panEnd.set( event.clientX, event.clientY ); - if ( dollyDelta.y > 0 ) { + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - dollyOut( getZoomScale() ); + pan( panDelta.x, panDelta.y ); - } else if ( dollyDelta.y < 0 ) { + panStart.copy( panEnd ); - dollyIn( getZoomScale() ); + scope.update(); } - dollyStart.copy( dollyEnd ); + function handleMouseWheel( event ) { - scope.update(); + if ( event.deltaY < 0 ) { - } + dollyIn( getZoomScale() ); - function handleMouseMovePan( event ) { + } else if ( event.deltaY > 0 ) { - panEnd.set( event.clientX, event.clientY ); + dollyOut( getZoomScale() ); - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); + } - pan( panDelta.x, panDelta.y ); + scope.update(); - panStart.copy( panEnd ); + } - scope.update(); + function handleKeyDown( event ) { - } + let needsUpdate = false; - function handleMouseUp( /*event*/ ) { + switch ( event.code ) { - // no-op + case scope.keys.UP: + pan( 0, scope.keyPanSpeed ); + needsUpdate = true; + break; - } + case scope.keys.BOTTOM: + pan( 0, - scope.keyPanSpeed ); + needsUpdate = true; + break; - function handleMouseWheel( event ) { + case scope.keys.LEFT: + pan( scope.keyPanSpeed, 0 ); + needsUpdate = true; + break; - if ( event.deltaY < 0 ) { + case scope.keys.RIGHT: + pan( - scope.keyPanSpeed, 0 ); + needsUpdate = true; + break; - dollyIn( getZoomScale() ); + } - } else if ( event.deltaY > 0 ) { + if ( needsUpdate ) { - dollyOut( getZoomScale() ); + // prevent the browser from scrolling on cursor keys + event.preventDefault(); - } + scope.update(); - scope.update(); + } - } - function handleKeyDown( event ) { + } - var needsUpdate = false; + function handleTouchStartRotate() { - switch ( event.keyCode ) { + if ( pointers.length === 1 ) { - case scope.keys.UP: - pan( 0, scope.keyPanSpeed ); - needsUpdate = true; - break; + rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - case scope.keys.BOTTOM: - pan( 0, - scope.keyPanSpeed ); - needsUpdate = true; - break; + } else { - case scope.keys.LEFT: - pan( scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - case scope.keys.RIGHT: - pan( - scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; + rotateStart.set( x, y ); + + } } - if ( needsUpdate ) { + function handleTouchStartPan() { - // prevent the browser from scrolling on cursor keys - event.preventDefault(); + if ( pointers.length === 1 ) { - scope.update(); + panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - } + } else { + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - } + panStart.set( x, y ); - function handleTouchStartRotate( event ) { + } - if ( event.touches.length == 1 ) { + } - rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + function handleTouchStartDolly() { - } else { + const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX; + const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY; - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + const distance = Math.sqrt( dx * dx + dy * dy ); - rotateStart.set( x, y ); + dollyStart.set( 0, distance ); } - } + function handleTouchStartDollyPan() { - function handleTouchStartPan( event ) { + if ( scope.enableZoom ) handleTouchStartDolly(); - if ( event.touches.length == 1 ) { + if ( scope.enablePan ) handleTouchStartPan(); - panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + } - } else { + function handleTouchStartDollyRotate() { - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + if ( scope.enableZoom ) handleTouchStartDolly(); - panStart.set( x, y ); + if ( scope.enableRotate ) handleTouchStartRotate(); } - } + function handleTouchMoveRotate( event ) { - function handleTouchStartDolly( event ) { + if ( pointers.length == 1 ) { - var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; - var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; + rotateEnd.set( event.pageX, event.pageY ); - var distance = Math.sqrt( dx * dx + dy * dy ); + } else { - dollyStart.set( 0, distance ); + const position = getSecondPointerPosition( event ); - } + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + rotateEnd.set( x, y ); - function handleTouchStartDollyPan( event ) { + } - if ( scope.enableZoom ) handleTouchStartDolly( event ); + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - if ( scope.enablePan ) handleTouchStartPan( event ); + const element = scope.domElement; - } + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - function handleTouchStartDollyRotate( event ) { + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - if ( scope.enableZoom ) handleTouchStartDolly( event ); + rotateStart.copy( rotateEnd ); - if ( scope.enableRotate ) handleTouchStartRotate( event ); + } - } + function handleTouchMovePan( event ) { - function handleTouchMoveRotate( event ) { + if ( pointers.length === 1 ) { - if ( event.touches.length == 1 ) { + panEnd.set( event.pageX, event.pageY ); - rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + } else { - } else { + const position = getSecondPointerPosition( event ); - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); - rotateEnd.set( x, y ); + panEnd.set( x, y ); - } + } - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - var element = scope.domElement; + pan( panDelta.x, panDelta.y ); - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height + panStart.copy( panEnd ); - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); + } - rotateStart.copy( rotateEnd ); + function handleTouchMoveDolly( event ) { - } + const position = getSecondPointerPosition( event ); - function handleTouchMovePan( event ) { + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; - if ( event.touches.length == 1 ) { + const distance = Math.sqrt( dx * dx + dy * dy ); - panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + dollyEnd.set( 0, distance ); - } else { + dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + dollyOut( dollyDelta.y ); - panEnd.set( x, y ); + dollyStart.copy( dollyEnd ); } - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); + function handleTouchMoveDollyPan( event ) { - pan( panDelta.x, panDelta.y ); + if ( scope.enableZoom ) handleTouchMoveDolly( event ); - panStart.copy( panEnd ); + if ( scope.enablePan ) handleTouchMovePan( event ); - } + } - function handleTouchMoveDolly( event ) { + function handleTouchMoveDollyRotate( event ) { - var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; - var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; + if ( scope.enableZoom ) handleTouchMoveDolly( event ); - var distance = Math.sqrt( dx * dx + dy * dy ); + if ( scope.enableRotate ) handleTouchMoveRotate( event ); - dollyEnd.set( 0, distance ); + } - dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); + // + // event handlers - FSM: listen for events and reset state + // - dollyOut( dollyDelta.y ); + function onPointerDown( event ) { - dollyStart.copy( dollyEnd ); + if ( scope.enabled === false ) return; - } + if ( pointers.length === 0 ) { - function handleTouchMoveDollyPan( event ) { + scope.domElement.setPointerCapture( event.pointerId ); - if ( scope.enableZoom ) handleTouchMoveDolly( event ); + scope.domElement.addEventListener( 'pointermove', onPointerMove ); + scope.domElement.addEventListener( 'pointerup', onPointerUp ); - if ( scope.enablePan ) handleTouchMovePan( event ); + } - } + // - function handleTouchMoveDollyRotate( event ) { + addPointer( event ); - if ( scope.enableZoom ) handleTouchMoveDolly( event ); + if ( event.pointerType === 'touch' ) { - if ( scope.enableRotate ) handleTouchMoveRotate( event ); + onTouchStart( event ); - } + } else { - function handleTouchEnd( /*event*/ ) { + onMouseDown( event ); - // no-op + } - } + } - // - // event handlers - FSM: listen for events and reset state - // + function onPointerMove( event ) { - function onPointerDown( event ) { + if ( scope.enabled === false ) return; - if ( scope.enabled === false ) return; + if ( event.pointerType === 'touch' ) { - switch ( event.pointerType ) { + onTouchMove( event ); - case 'mouse': - case 'pen': - onMouseDown( event ); - break; + } else { - // TODO touch + onMouseMove( event ); - } + } - } + } - function onPointerMove( event ) { + function onPointerUp( event ) { - if ( scope.enabled === false ) return; + removePointer( event ); - switch ( event.pointerType ) { + if ( pointers.length === 0 ) { - case 'mouse': - case 'pen': - onMouseMove( event ); - break; + scope.domElement.releasePointerCapture( event.pointerId ); - // TODO touch + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - } + } - } + scope.dispatchEvent( _endEvent ); - function onPointerUp( event ) { + state = STATE.NONE; - switch ( event.pointerType ) { + } - case 'mouse': - case 'pen': - onMouseUp( event ); - break; + function onPointerCancel( event ) { - // TODO touch + removePointer( event ); } - } + function onMouseDown( event ) { - function onMouseDown( event ) { + let mouseAction; - // Prevent the browser from scrolling. - event.preventDefault(); + switch ( event.button ) { - // Manually set the focus since calling preventDefault above - // prevents the browser from setting it automatically. + case 0: - scope.domElement.focus ? scope.domElement.focus() : window.focus(); + mouseAction = scope.mouseButtons.LEFT; + break; - var mouseAction; + case 1: - switch ( event.button ) { + mouseAction = scope.mouseButtons.MIDDLE; + break; - case 0: + case 2: - mouseAction = scope.mouseButtons.LEFT; - break; + mouseAction = scope.mouseButtons.RIGHT; + break; - case 1: + default: - mouseAction = scope.mouseButtons.MIDDLE; - break; + mouseAction = - 1; - case 2: + } - mouseAction = scope.mouseButtons.RIGHT; - break; + switch ( mouseAction ) { - default: + case MOUSE.DOLLY: - mouseAction = - 1; + if ( scope.enableZoom === false ) return; - } + handleMouseDownDolly( event ); - switch ( mouseAction ) { + state = STATE.DOLLY; - case MOUSE.DOLLY: + break; - if ( scope.enableZoom === false ) return; + case MOUSE.ROTATE: - handleMouseDownDolly( event ); + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - state = STATE.DOLLY; + if ( scope.enablePan === false ) return; - break; + handleMouseDownPan( event ); - case MOUSE.ROTATE: + state = STATE.PAN; - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + } else { - if ( scope.enablePan === false ) return; + if ( scope.enableRotate === false ) return; - handleMouseDownPan( event ); + handleMouseDownRotate( event ); - state = STATE.PAN; + state = STATE.ROTATE; - } else { + } - if ( scope.enableRotate === false ) return; + break; - handleMouseDownRotate( event ); + case MOUSE.PAN: - state = STATE.ROTATE; + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - } + if ( scope.enableRotate === false ) return; - break; + handleMouseDownRotate( event ); - case MOUSE.PAN: + state = STATE.ROTATE; - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + } else { - if ( scope.enableRotate === false ) return; + if ( scope.enablePan === false ) return; - handleMouseDownRotate( event ); + handleMouseDownPan( event ); - state = STATE.ROTATE; + state = STATE.PAN; - } else { + } - if ( scope.enablePan === false ) return; + break; - handleMouseDownPan( event ); + default: - state = STATE.PAN; + state = STATE.NONE; - } + } - break; + if ( state !== STATE.NONE ) { - default: + scope.dispatchEvent( _startEvent ); - state = STATE.NONE; + } } - if ( state !== STATE.NONE ) { + function onMouseMove( event ) { - scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove ); - scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp ); + switch ( state ) { - scope.dispatchEvent( startEvent ); + case STATE.ROTATE: - } + if ( scope.enableRotate === false ) return; - } + handleMouseMoveRotate( event ); + + break; - function onMouseMove( event ) { + case STATE.DOLLY: - if ( scope.enabled === false ) return; + if ( scope.enableZoom === false ) return; - event.preventDefault(); + handleMouseMoveDolly( event ); - switch ( state ) { + break; - case STATE.ROTATE: + case STATE.PAN: - if ( scope.enableRotate === false ) return; + if ( scope.enablePan === false ) return; - handleMouseMoveRotate( event ); + handleMouseMovePan( event ); - break; + break; - case STATE.DOLLY: + } - if ( scope.enableZoom === false ) return; + } - handleMouseMoveDolly( event ); + function onMouseWheel( event ) { - break; + if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return; - case STATE.PAN: + event.preventDefault(); - if ( scope.enablePan === false ) return; + scope.dispatchEvent( _startEvent ); - handleMouseMovePan( event ); + handleMouseWheel( event ); - break; + scope.dispatchEvent( _endEvent ); } - } - - function onMouseUp( event ) { + function onKeyDown( event ) { - scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp ); + if ( scope.enabled === false || scope.enablePan === false ) return; - if ( scope.enabled === false ) return; + handleKeyDown( event ); - handleMouseUp( event ); + } - scope.dispatchEvent( endEvent ); + function onTouchStart( event ) { - state = STATE.NONE; + trackPointer( event ); - } + switch ( pointers.length ) { - function onMouseWheel( event ) { + case 1: - if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return; + switch ( scope.touches.ONE ) { - event.preventDefault(); - event.stopPropagation(); + case TOUCH.ROTATE: - scope.dispatchEvent( startEvent ); + if ( scope.enableRotate === false ) return; - handleMouseWheel( event ); + handleTouchStartRotate(); - scope.dispatchEvent( endEvent ); + state = STATE.TOUCH_ROTATE; - } + break; - function onKeyDown( event ) { + case TOUCH.PAN: - if ( scope.enabled === false || scope.enablePan === false ) return; + if ( scope.enablePan === false ) return; - handleKeyDown( event ); + handleTouchStartPan(); - } + state = STATE.TOUCH_PAN; - function onTouchStart( event ) { + break; - if ( scope.enabled === false ) return; + default: - event.preventDefault(); // prevent scrolling + state = STATE.NONE; - switch ( event.touches.length ) { + } - case 1: + break; - switch ( scope.touches.ONE ) { + case 2: - case TOUCH.ROTATE: + switch ( scope.touches.TWO ) { - if ( scope.enableRotate === false ) return; + case TOUCH.DOLLY_PAN: - handleTouchStartRotate( event ); + if ( scope.enableZoom === false && scope.enablePan === false ) return; - state = STATE.TOUCH_ROTATE; + handleTouchStartDollyPan(); - break; + state = STATE.TOUCH_DOLLY_PAN; - case TOUCH.PAN: + break; - if ( scope.enablePan === false ) return; + case TOUCH.DOLLY_ROTATE: - handleTouchStartPan( event ); + if ( scope.enableZoom === false && scope.enableRotate === false ) return; - state = STATE.TOUCH_PAN; + handleTouchStartDollyRotate(); - break; + state = STATE.TOUCH_DOLLY_ROTATE; - default: + break; - state = STATE.NONE; + default: - } + state = STATE.NONE; - break; + } - case 2: + break; - switch ( scope.touches.TWO ) { + default: - case TOUCH.DOLLY_PAN: + state = STATE.NONE; - if ( scope.enableZoom === false && scope.enablePan === false ) return; + } - handleTouchStartDollyPan( event ); + if ( state !== STATE.NONE ) { - state = STATE.TOUCH_DOLLY_PAN; + scope.dispatchEvent( _startEvent ); - break; + } - case TOUCH.DOLLY_ROTATE: + } - if ( scope.enableZoom === false && scope.enableRotate === false ) return; + function onTouchMove( event ) { - handleTouchStartDollyRotate( event ); + trackPointer( event ); - state = STATE.TOUCH_DOLLY_ROTATE; + switch ( state ) { - break; + case STATE.TOUCH_ROTATE: - default: + if ( scope.enableRotate === false ) return; - state = STATE.NONE; + handleTouchMoveRotate( event ); - } + scope.update(); - break; + break; - default: + case STATE.TOUCH_PAN: - state = STATE.NONE; + if ( scope.enablePan === false ) return; - } + handleTouchMovePan( event ); - if ( state !== STATE.NONE ) { + scope.update(); - scope.dispatchEvent( startEvent ); + break; - } + case STATE.TOUCH_DOLLY_PAN: - } + if ( scope.enableZoom === false && scope.enablePan === false ) return; - function onTouchMove( event ) { + handleTouchMoveDollyPan( event ); - if ( scope.enabled === false ) return; + scope.update(); - event.preventDefault(); // prevent scrolling - event.stopPropagation(); + break; - switch ( state ) { + case STATE.TOUCH_DOLLY_ROTATE: - case STATE.TOUCH_ROTATE: + if ( scope.enableZoom === false && scope.enableRotate === false ) return; - if ( scope.enableRotate === false ) return; + handleTouchMoveDollyRotate( event ); - handleTouchMoveRotate( event ); + scope.update(); - scope.update(); + break; - break; + default: - case STATE.TOUCH_PAN: + state = STATE.NONE; - if ( scope.enablePan === false ) return; + } - handleTouchMovePan( event ); + } - scope.update(); + function onContextMenu( event ) { - break; + if ( scope.enabled === false ) return; - case STATE.TOUCH_DOLLY_PAN: + event.preventDefault(); - if ( scope.enableZoom === false && scope.enablePan === false ) return; + } - handleTouchMoveDollyPan( event ); + function addPointer( event ) { - scope.update(); + pointers.push( event ); - break; + } - case STATE.TOUCH_DOLLY_ROTATE: + function removePointer( event ) { - if ( scope.enableZoom === false && scope.enableRotate === false ) return; + delete pointerPositions[ event.pointerId ]; - handleTouchMoveDollyRotate( event ); + for ( let i = 0; i < pointers.length; i ++ ) { - scope.update(); + if ( pointers[ i ].pointerId == event.pointerId ) { - break; + pointers.splice( i, 1 ); + return; - default: + } - state = STATE.NONE; + } } - } + function trackPointer( event ) { - function onTouchEnd( event ) { + let position = pointerPositions[ event.pointerId ]; - if ( scope.enabled === false ) return; + if ( position === undefined ) { - handleTouchEnd( event ); + position = new Vector2(); + pointerPositions[ event.pointerId ] = position; - scope.dispatchEvent( endEvent ); + } - state = STATE.NONE; + position.set( event.pageX, event.pageY ); - } + } - function onContextMenu( event ) { + function getSecondPointerPosition( event ) { - if ( scope.enabled === false ) return; + const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ]; - event.preventDefault(); - - } + return pointerPositions[ pointer.pointerId ]; - // + } - scope.domElement.addEventListener( 'contextmenu', onContextMenu ); + // - scope.domElement.addEventListener( 'pointerdown', onPointerDown ); - scope.domElement.addEventListener( 'wheel', onMouseWheel ); + scope.domElement.addEventListener( 'contextmenu', onContextMenu ); - scope.domElement.addEventListener( 'touchstart', onTouchStart ); - scope.domElement.addEventListener( 'touchend', onTouchEnd ); - scope.domElement.addEventListener( 'touchmove', onTouchMove ); + scope.domElement.addEventListener( 'pointerdown', onPointerDown ); + scope.domElement.addEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); - // force an update at start + // force an update at start - this.update(); + this.update(); -}; + } -OrbitControls.prototype = Object.create( EventDispatcher.prototype ); -OrbitControls.prototype.constructor = OrbitControls; +} // This set of controls performs orbiting, dollying (zooming), and panning. @@ -50595,28 +51277,29 @@ OrbitControls.prototype.constructor = OrbitControls; // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - left mouse, or arrow keys / touch: one-finger move -var MapControls = function ( object, domElement ) { +class MapControls extends OrbitControls { - OrbitControls.call( this, object, domElement ); + constructor( object, domElement ) { - this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up + super( object, domElement ); - this.mouseButtons.LEFT = MOUSE.PAN; - this.mouseButtons.RIGHT = MOUSE.ROTATE; + this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up - this.touches.ONE = TOUCH.PAN; - this.touches.TWO = TOUCH.DOLLY_ROTATE; + this.mouseButtons.LEFT = MOUSE.PAN; + this.mouseButtons.RIGHT = MOUSE.ROTATE; -}; + this.touches.ONE = TOUCH.PAN; + this.touches.TWO = TOUCH.DOLLY_ROTATE; + + } -MapControls.prototype = Object.create( EventDispatcher.prototype ); -MapControls.prototype.constructor = MapControls; +} -var GLTFLoader = ( function () { +class GLTFLoader extends Loader { - function GLTFLoader( manager ) { + constructor( manager ) { - Loader.call( this, manager ); + super( manager ); this.dracoLoader = null; this.ktx2Loader = null; @@ -50642,12 +51325,48 @@ var GLTFLoader = ( function () { } ); + this.register( function ( parser ) { + + return new GLTFMaterialsSheenExtension( parser ); + + } ); + this.register( function ( parser ) { return new GLTFMaterialsTransmissionExtension( parser ); } ); + this.register( function ( parser ) { + + return new GLTFMaterialsVolumeExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsIorExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsEmissiveStrengthExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsSpecularExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsIridescenceExtension( parser ); + + } ); + this.register( function ( parser ) { return new GLTFLightsExtension( parser ); @@ -50662,320 +51381,336 @@ var GLTFLoader = ( function () { } - GLTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + load( url, onLoad, onProgress, onError ) { - constructor: GLTFLoader, + const scope = this; - load: function ( url, onLoad, onProgress, onError ) { + let resourcePath; - var scope = this; + if ( this.resourcePath !== '' ) { - var resourcePath; + resourcePath = this.resourcePath; - if ( this.resourcePath !== '' ) { + } else if ( this.path !== '' ) { - resourcePath = this.resourcePath; + resourcePath = this.path; - } else if ( this.path !== '' ) { + } else { + + resourcePath = LoaderUtils.extractUrlBase( url ); - resourcePath = this.path; + } + + // Tells the LoadingManager to track an extra item, which resolves after + // the model is fully loaded. This means the count of items loaded will + // be incorrect, but ensures manager.onLoad() does not fire early. + this.manager.itemStart( url ); + + const _onError = function ( e ) { + + if ( onError ) { + + onError( e ); } else { - resourcePath = LoaderUtils.extractUrlBase( url ); + console.error( e ); } - // Tells the LoadingManager to track an extra item, which resolves after - // the model is fully loaded. This means the count of items loaded will - // be incorrect, but ensures manager.onLoad() does not fire early. - this.manager.itemStart( url ); + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - var _onError = function ( e ) { + }; - if ( onError ) { + const loader = new FileLoader( this.manager ); - onError( e ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); - } else { + loader.load( url, function ( data ) { - console.error( e ); + try { - } + scope.parse( data, resourcePath, function ( gltf ) { - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + onLoad( gltf ); - }; + scope.manager.itemEnd( url ); - var loader = new FileLoader( this.manager ); + }, _onError ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); + } catch ( e ) { - loader.load( url, function ( data ) { + _onError( e ); - try { + } - scope.parse( data, resourcePath, function ( gltf ) { + }, onProgress, _onError ); - onLoad( gltf ); + } - scope.manager.itemEnd( url ); + setDRACOLoader( dracoLoader ) { - }, _onError ); + this.dracoLoader = dracoLoader; + return this; - } catch ( e ) { + } - _onError( e ); + setDDSLoader() { - } + throw new Error( - }, onProgress, _onError ); + 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".' - }, + ); - setDRACOLoader: function ( dracoLoader ) { + } - this.dracoLoader = dracoLoader; - return this; + setKTX2Loader( ktx2Loader ) { - }, + this.ktx2Loader = ktx2Loader; + return this; - setDDSLoader: function () { + } - throw new Error( + setMeshoptDecoder( meshoptDecoder ) { - 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".' + this.meshoptDecoder = meshoptDecoder; + return this; - ); + } - }, + register( callback ) { - setKTX2Loader: function ( ktx2Loader ) { + if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) { - this.ktx2Loader = ktx2Loader; - return this; + this.pluginCallbacks.push( callback ); - }, + } - setMeshoptDecoder: function ( meshoptDecoder ) { + return this; - this.meshoptDecoder = meshoptDecoder; - return this; + } - }, + unregister( callback ) { - register: function ( callback ) { + if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) { - if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) { + this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 ); - this.pluginCallbacks.push( callback ); + } - } + return this; - return this; + } - }, + parse( data, path, onLoad, onError ) { - unregister: function ( callback ) { + let content; + const extensions = {}; + const plugins = {}; - if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) { + if ( typeof data === 'string' ) { - this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 ); + content = data; - } + } else { - return this; + const magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); - }, + if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { - parse: function ( data, path, onLoad, onError ) { + try { - var content; - var extensions = {}; - var plugins = {}; + extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); - if ( typeof data === 'string' ) { + } catch ( error ) { - content = data; + if ( onError ) onError( error ); + return; - } else { + } - var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); + content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; - if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { + } else { - try { + content = LoaderUtils.decodeText( new Uint8Array( data ) ); - extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); + } - } catch ( error ) { + } - if ( onError ) onError( error ); - return; + const json = JSON.parse( content ); - } + if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { - content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; + if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) ); + return; - } else { + } - content = LoaderUtils.decodeText( new Uint8Array( data ) ); + const parser = new GLTFParser( json, { - } + path: path || this.resourcePath || '', + crossOrigin: this.crossOrigin, + requestHeader: this.requestHeader, + manager: this.manager, + ktx2Loader: this.ktx2Loader, + meshoptDecoder: this.meshoptDecoder - } + } ); - var json = JSON.parse( content ); + parser.fileLoader.setRequestHeader( this.requestHeader ); - if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { + for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) { - if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) ); - return; + const plugin = this.pluginCallbacks[ i ]( parser ); + plugins[ plugin.name ] = plugin; - } + // Workaround to avoid determining as unknown extension + // in addUnknownExtensionsToUserData(). + // Remove this workaround if we move all the existing + // extension handlers to plugin system + extensions[ plugin.name ] = true; - var parser = new GLTFParser( json, { + } - path: path || this.resourcePath || '', - crossOrigin: this.crossOrigin, - requestHeader: this.requestHeader, - manager: this.manager, - ktx2Loader: this.ktx2Loader, - meshoptDecoder: this.meshoptDecoder + if ( json.extensionsUsed ) { - } ); + for ( let i = 0; i < json.extensionsUsed.length; ++ i ) { - parser.fileLoader.setRequestHeader( this.requestHeader ); + const extensionName = json.extensionsUsed[ i ]; + const extensionsRequired = json.extensionsRequired || []; - for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) { + switch ( extensionName ) { - var plugin = this.pluginCallbacks[ i ]( parser ); - plugins[ plugin.name ] = plugin; + case EXTENSIONS.KHR_MATERIALS_UNLIT: + extensions[ extensionName ] = new GLTFMaterialsUnlitExtension(); + break; - // Workaround to avoid determining as unknown extension - // in addUnknownExtensionsToUserData(). - // Remove this workaround if we move all the existing - // extension handlers to plugin system - extensions[ plugin.name ] = true; + case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: + extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension(); + break; - } + case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: + extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader ); + break; - if ( json.extensionsUsed ) { + case EXTENSIONS.KHR_TEXTURE_TRANSFORM: + extensions[ extensionName ] = new GLTFTextureTransformExtension(); + break; - for ( var i = 0; i < json.extensionsUsed.length; ++ i ) { + case EXTENSIONS.KHR_MESH_QUANTIZATION: + extensions[ extensionName ] = new GLTFMeshQuantizationExtension(); + break; - var extensionName = json.extensionsUsed[ i ]; - var extensionsRequired = json.extensionsRequired || []; + default: - switch ( extensionName ) { + if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) { - case EXTENSIONS.KHR_MATERIALS_UNLIT: - extensions[ extensionName ] = new GLTFMaterialsUnlitExtension(); - break; + console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' ); - case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: - extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension(); - break; + } - case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: - extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader ); - break; + } - case EXTENSIONS.KHR_TEXTURE_TRANSFORM: - extensions[ extensionName ] = new GLTFTextureTransformExtension(); - break; + } - case EXTENSIONS.KHR_MESH_QUANTIZATION: - extensions[ extensionName ] = new GLTFMeshQuantizationExtension(); - break; + } - default: + parser.setExtensions( extensions ); + parser.setPlugins( plugins ); + parser.parse( onLoad, onError ); - if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) { + } - console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' ); + parseAsync( data, path ) { - } + const scope = this; - } + return new Promise( function ( resolve, reject ) { - } + scope.parse( data, path, resolve, reject ); - } + } ); - parser.setExtensions( extensions ); - parser.setPlugins( plugins ); - parser.parse( onLoad, onError ); + } - } +} - } ); +/* GLTFREGISTRY */ - /* GLTFREGISTRY */ +function GLTFRegistry() { - function GLTFRegistry() { + let objects = {}; - var objects = {}; + return { - return { + get: function ( key ) { - get: function ( key ) { + return objects[ key ]; - return objects[ key ]; + }, - }, + add: function ( key, object ) { - add: function ( key, object ) { + objects[ key ] = object; - objects[ key ] = object; + }, - }, + remove: function ( key ) { - remove: function ( key ) { + delete objects[ key ]; - delete objects[ key ]; + }, - }, + removeAll: function () { - removeAll: function () { + objects = {}; - objects = {}; + } - } + }; - }; +} - } +/*********************************/ +/********** EXTENSIONS ***********/ +/*********************************/ + +const EXTENSIONS = { + KHR_BINARY_GLTF: 'KHR_binary_glTF', + KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', + KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', + KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat', + KHR_MATERIALS_IOR: 'KHR_materials_ior', + KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', + KHR_MATERIALS_SHEEN: 'KHR_materials_sheen', + KHR_MATERIALS_SPECULAR: 'KHR_materials_specular', + KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', + KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence', + KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', + KHR_MATERIALS_VOLUME: 'KHR_materials_volume', + KHR_TEXTURE_BASISU: 'KHR_texture_basisu', + KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', + KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', + KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength', + EXT_TEXTURE_WEBP: 'EXT_texture_webp', + EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression' +}; - /*********************************/ - /********** EXTENSIONS ***********/ - /*********************************/ - - var EXTENSIONS = { - KHR_BINARY_GLTF: 'KHR_binary_glTF', - KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', - KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', - KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat', - KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', - KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', - KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', - KHR_TEXTURE_BASISU: 'KHR_texture_basisu', - KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', - KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', - EXT_TEXTURE_WEBP: 'EXT_texture_webp', - EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression' - }; +/** + * Punctual Lights Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual + */ +class GLTFLightsExtension { - /** - * Punctual Lights Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual - */ - function GLTFLightsExtension( parser ) { + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; @@ -50985,18 +51720,18 @@ var GLTFLoader = ( function () { } - GLTFLightsExtension.prototype._markDefs = function () { + _markDefs() { - var parser = this.parser; - var nodeDefs = this.parser.json.nodes || []; + const parser = this.parser; + const nodeDefs = this.parser.json.nodes || []; - for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { + for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { - var nodeDef = nodeDefs[ nodeIndex ]; + const nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.extensions - && nodeDef.extensions[ this.name ] - && nodeDef.extensions[ this.name ].light !== undefined ) { + && nodeDef.extensions[ this.name ] + && nodeDef.extensions[ this.name ].light !== undefined ) { parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light ); @@ -51004,27 +51739,27 @@ var GLTFLoader = ( function () { } - }; + } - GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) { + _loadLight( lightIndex ) { - var parser = this.parser; - var cacheKey = 'light:' + lightIndex; - var dependency = parser.cache.get( cacheKey ); + const parser = this.parser; + const cacheKey = 'light:' + lightIndex; + let dependency = parser.cache.get( cacheKey ); if ( dependency ) return dependency; - var json = parser.json; - var extensions = ( json.extensions && json.extensions[ this.name ] ) || {}; - var lightDefs = extensions.lights || []; - var lightDef = lightDefs[ lightIndex ]; - var lightNode; + const json = parser.json; + const extensions = ( json.extensions && json.extensions[ this.name ] ) || {}; + const lightDefs = extensions.lights || []; + const lightDef = lightDefs[ lightIndex ]; + let lightNode; - var color = new Color( 0xffffff ); + const color = new Color( 0xffffff ); if ( lightDef.color !== undefined ) color.fromArray( lightDef.color ); - var range = lightDef.range !== undefined ? lightDef.range : 0; + const range = lightDef.range !== undefined ? lightDef.range : 0; switch ( lightDef.type ) { @@ -51073,16 +51808,16 @@ var GLTFLoader = ( function () { return dependency; - }; + } - GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) { + createNodeAttachment( nodeIndex ) { - var self = this; - var parser = this.parser; - var json = parser.json; - var nodeDef = json.nodes[ nodeIndex ]; - var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {}; - var lightIndex = lightDef.light; + const self = this; + const parser = this.parser; + const json = parser.json; + const nodeDef = json.nodes[ nodeIndex ]; + const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {}; + const lightIndex = lightDef.light; if ( lightIndex === undefined ) return null; @@ -51092,39 +51827,43 @@ var GLTFLoader = ( function () { } ); - }; + } - /** - * Unlit Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit - */ - function GLTFMaterialsUnlitExtension() { +} + +/** + * Unlit Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit + */ +class GLTFMaterialsUnlitExtension { + + constructor() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } - GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () { + getMaterialType() { return MeshBasicMaterial; - }; + } - GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) { + extendParams( materialParams, materialDef, parser ) { - var pending = []; + const pending = []; materialParams.color = new Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; - var metallicRoughness = materialDef.pbrMetallicRoughness; + const metallicRoughness = materialDef.pbrMetallicRoughness; if ( metallicRoughness ) { if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { - var array = metallicRoughness.baseColorFactor; + const array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; @@ -51133,7 +51872,7 @@ var GLTFLoader = ( function () { if ( metallicRoughness.baseColorTexture !== undefined ) { - pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); + pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding ) ); } @@ -51141,35 +51880,78 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } - /** - * Clearcoat Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat - */ - function GLTFMaterialsClearcoatExtension( parser ) { +} + +/** + * Materials Emissive Strength Extension + * + * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md + */ +class GLTFMaterialsEmissiveStrengthExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength; + + if ( emissiveStrength !== undefined ) { + + materialParams.emissiveIntensity = emissiveStrength; + + } + + return Promise.resolve(); + + } + +} + +/** + * Clearcoat Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat + */ +class GLTFMaterialsClearcoatExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; } - GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) { + getMaterialType( materialIndex ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; return MeshPhysicalMaterial; - }; + } - GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) { + extendMaterialParams( materialIndex, materialParams ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { @@ -51177,9 +51959,9 @@ var GLTFLoader = ( function () { } - var pending = []; + const pending = []; - var extension = materialDef.extensions[ this.name ]; + const extension = materialDef.extensions[ this.name ]; if ( extension.clearcoatFactor !== undefined ) { @@ -51211,10 +51993,9 @@ var GLTFLoader = ( function () { if ( extension.clearcoatNormalTexture.scale !== undefined ) { - var scale = extension.clearcoatNormalTexture.scale; + const scale = extension.clearcoatNormalTexture.scale; - // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 - materialParams.clearcoatNormalScale = new Vector2( scale, - scale ); + materialParams.clearcoatNormalScale = new Vector2( scale, scale ); } @@ -51222,36 +52003,202 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } - /** - * Transmission Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission - * Draft: https://github.com/KhronosGroup/glTF/pull/1698 - */ - function GLTFMaterialsTransmissionExtension( parser ) { +} + +/** + * Iridescence Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence + */ +class GLTFMaterialsIridescenceExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.iridescenceFactor !== undefined ) { + + materialParams.iridescence = extension.iridescenceFactor; + + } + + if ( extension.iridescenceTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) ); + + } + + if ( extension.iridescenceIor !== undefined ) { + + materialParams.iridescenceIOR = extension.iridescenceIor; + + } + + if ( materialParams.iridescenceThicknessRange === undefined ) { + + materialParams.iridescenceThicknessRange = [ 100, 400 ]; + + } + + if ( extension.iridescenceThicknessMinimum !== undefined ) { + + materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum; + + } + + if ( extension.iridescenceThicknessMaximum !== undefined ) { + + materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum; + + } + + if ( extension.iridescenceThicknessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Sheen Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen + */ +class GLTFMaterialsSheenExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + materialParams.sheenColor = new Color( 0, 0, 0 ); + materialParams.sheenRoughness = 0; + materialParams.sheen = 1; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.sheenColorFactor !== undefined ) { + + materialParams.sheenColor.fromArray( extension.sheenColorFactor ); + + } + + if ( extension.sheenRoughnessFactor !== undefined ) { + + materialParams.sheenRoughness = extension.sheenRoughnessFactor; + + } + + if ( extension.sheenColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, sRGBEncoding ) ); + + } + + if ( extension.sheenRoughnessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Transmission Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission + * Draft: https://github.com/KhronosGroup/glTF/pull/1698 + */ +class GLTFMaterialsTransmissionExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; } - GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) { + getMaterialType( materialIndex ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; return MeshPhysicalMaterial; - }; + } - GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) { + extendMaterialParams( materialIndex, materialParams ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { @@ -51259,9 +52206,9 @@ var GLTFLoader = ( function () { } - var pending = []; + const pending = []; - var extension = materialDef.extensions[ this.name ]; + const extension = materialDef.extensions[ this.name ]; if ( extension.transmissionFactor !== undefined ) { @@ -51277,26 +52224,198 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } - /** - * BasisU Texture Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu - */ - function GLTFTextureBasisUExtension( parser ) { +} + +/** + * Materials Volume Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume + */ +class GLTFMaterialsVolumeExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; + + if ( extension.thicknessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) ); + + } + + materialParams.attenuationDistance = extension.attenuationDistance || 0; + + const colorArray = extension.attenuationColor || [ 1, 1, 1 ]; + materialParams.attenuationColor = new Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] ); + + return Promise.all( pending ); + + } + +} + +/** + * Materials ior Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior + */ +class GLTFMaterialsIorExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IOR; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const extension = materialDef.extensions[ this.name ]; + + materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; + + return Promise.resolve(); + + } + +} + +/** + * Materials specular Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular + */ +class GLTFMaterialsSpecularExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0; + + if ( extension.specularTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) ); + + } + + const colorArray = extension.specularColorFactor || [ 1, 1, 1 ]; + materialParams.specularColor = new Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] ); + + if ( extension.specularColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, sRGBEncoding ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * BasisU Texture Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu + */ +class GLTFTextureBasisUExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_TEXTURE_BASISU; } - GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) { + loadTexture( textureIndex ) { - var parser = this.parser; - var json = parser.json; + const parser = this.parser; + const json = parser.json; - var textureDef = json.textures[ textureIndex ]; + const textureDef = json.textures[ textureIndex ]; if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) { @@ -51304,9 +52423,8 @@ var GLTFLoader = ( function () { } - var extension = textureDef.extensions[ this.name ]; - var source = json.images[ extension.source ]; - var loader = parser.options.ktx2Loader; + const extension = textureDef.extensions[ this.name ]; + const loader = parser.options.ktx2Loader; if ( ! loader ) { @@ -51323,16 +52441,20 @@ var GLTFLoader = ( function () { } - return parser.loadTextureImage( textureIndex, source, loader ); + return parser.loadTextureImage( textureIndex, extension.source, loader ); - }; + } - /** - * WebP Texture Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp - */ - function GLTFTextureWebPExtension( parser ) { +} + +/** + * WebP Texture Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp + */ +class GLTFTextureWebPExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_WEBP; @@ -51340,13 +52462,13 @@ var GLTFLoader = ( function () { } - GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) { + loadTexture( textureIndex ) { - var name = this.name; - var parser = this.parser; - var json = parser.json; + const name = this.name; + const parser = this.parser; + const json = parser.json; - var textureDef = json.textures[ textureIndex ]; + const textureDef = json.textures[ textureIndex ]; if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) { @@ -51354,20 +52476,20 @@ var GLTFLoader = ( function () { } - var extension = textureDef.extensions[ name ]; - var source = json.images[ extension.source ]; + const extension = textureDef.extensions[ name ]; + const source = json.images[ extension.source ]; - var loader = parser.textureLoader; + let loader = parser.textureLoader; if ( source.uri ) { - var handler = parser.options.manager.getHandler( source.uri ); + const handler = parser.options.manager.getHandler( source.uri ); if ( handler !== null ) loader = handler; } return this.detectSupport().then( function ( isSupported ) { - if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader ); + if ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader ); if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) { @@ -51380,15 +52502,15 @@ var GLTFLoader = ( function () { } ); - }; + } - GLTFTextureWebPExtension.prototype.detectSupport = function () { + detectSupport() { if ( ! this.isSupported ) { this.isSupported = new Promise( function ( resolve ) { - var image = new Image(); + const image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all // WebP images, unfortunately. @@ -51406,31 +52528,35 @@ var GLTFLoader = ( function () { return this.isSupported; - }; + } - /** - * meshopt BufferView Compression Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression - */ - function GLTFMeshoptCompression( parser ) { +} + +/** + * meshopt BufferView Compression Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression + */ +class GLTFMeshoptCompression { + + constructor( parser ) { this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; this.parser = parser; } - GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) { + loadBufferView( index ) { - var json = this.parser.json; - var bufferView = json.bufferViews[ index ]; + const json = this.parser.json; + const bufferView = json.bufferViews[ index ]; if ( bufferView.extensions && bufferView.extensions[ this.name ] ) { - var extensionDef = bufferView.extensions[ this.name ]; + const extensionDef = bufferView.extensions[ this.name ]; - var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer ); - var decoder = this.parser.options.meshoptDecoder; + const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer ); + const decoder = this.parser.options.meshoptDecoder; if ( ! decoder || ! decoder.supported ) { @@ -51447,19 +52573,36 @@ var GLTFLoader = ( function () { } - return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) { + return buffer.then( function ( res ) { + + const byteOffset = extensionDef.byteOffset || 0; + const byteLength = extensionDef.byteLength || 0; + + const count = extensionDef.count; + const stride = extensionDef.byteStride; + + const source = new Uint8Array( res, byteOffset, byteLength ); + + if ( decoder.decodeGltfBufferAsync ) { + + return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) { + + return res.buffer; + + } ); + + } else { - var byteOffset = extensionDef.byteOffset || 0; - var byteLength = extensionDef.byteLength || 0; + // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync + return decoder.ready.then( function () { - var count = extensionDef.count; - var stride = extensionDef.byteStride; + const result = new ArrayBuffer( count * stride ); + decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter ); + return result; - var result = new ArrayBuffer( count * stride ); - var source = new Uint8Array( res[ 0 ], byteOffset, byteLength ); + } ); - decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter ); - return result; + } } ); @@ -51469,20 +52612,24 @@ var GLTFLoader = ( function () { } - }; + } + +} + +/* BINARY EXTENSION */ +const BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; +const BINARY_EXTENSION_HEADER_LENGTH = 12; +const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; - /* BINARY EXTENSION */ - var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; - var BINARY_EXTENSION_HEADER_LENGTH = 12; - var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; +class GLTFBinaryExtension { - function GLTFBinaryExtension( data ) { + constructor( data ) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; - var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); + const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); this.header = { magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ), @@ -51500,26 +52647,26 @@ var GLTFLoader = ( function () { } - var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; - var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); - var chunkIndex = 0; + const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; + const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); + let chunkIndex = 0; while ( chunkIndex < chunkContentsLength ) { - var chunkLength = chunkView.getUint32( chunkIndex, true ); + const chunkLength = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; - var chunkType = chunkView.getUint32( chunkIndex, true ); + const chunkType = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) { - var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); + const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); this.content = LoaderUtils.decodeText( contentArray ); } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) { - var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; + const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice( byteOffset, byteOffset + chunkLength ); } @@ -51538,12 +52685,16 @@ var GLTFLoader = ( function () { } - /** - * DRACO Mesh Compression Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression - */ - function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { +} + +/** + * DRACO Mesh Compression Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression + */ +class GLTFDracoMeshCompressionExtension { + + constructor( json, dracoLoader ) { if ( ! dracoLoader ) { @@ -51558,34 +52709,34 @@ var GLTFLoader = ( function () { } - GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) { + decodePrimitive( primitive, parser ) { - var json = this.json; - var dracoLoader = this.dracoLoader; - var bufferViewIndex = primitive.extensions[ this.name ].bufferView; - var gltfAttributeMap = primitive.extensions[ this.name ].attributes; - var threeAttributeMap = {}; - var attributeNormalizedMap = {}; - var attributeTypeMap = {}; + const json = this.json; + const dracoLoader = this.dracoLoader; + const bufferViewIndex = primitive.extensions[ this.name ].bufferView; + const gltfAttributeMap = primitive.extensions[ this.name ].attributes; + const threeAttributeMap = {}; + const attributeNormalizedMap = {}; + const attributeTypeMap = {}; - for ( var attributeName in gltfAttributeMap ) { + for ( const attributeName in gltfAttributeMap ) { - var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); + const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ]; } - for ( attributeName in primitive.attributes ) { + for ( const attributeName in primitive.attributes ) { - var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); + const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); if ( gltfAttributeMap[ attributeName ] !== undefined ) { - var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ]; - var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; + const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ]; + const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; - attributeTypeMap[ threeAttributeName ] = componentType; + attributeTypeMap[ threeAttributeName ] = componentType.name; attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true; } @@ -51598,10 +52749,10 @@ var GLTFLoader = ( function () { dracoLoader.decodeDracoFile( bufferView, function ( geometry ) { - for ( var attributeName in geometry.attributes ) { + for ( const attributeName in geometry.attributes ) { - var attribute = geometry.attributes[ attributeName ]; - var normalized = attributeNormalizedMap[ attributeName ]; + const attribute = geometry.attributes[ attributeName ]; + const normalized = attributeNormalizedMap[ attributeName ]; if ( normalized !== undefined ) attribute.normalized = normalized; @@ -51615,20 +52766,37 @@ var GLTFLoader = ( function () { } ); - }; + } - /** - * Texture Transform Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform - */ - function GLTFTextureTransformExtension() { +} + +/** + * Texture Transform Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform + */ +class GLTFTextureTransformExtension { + + constructor() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } - GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) { + extendTexture( texture, transform ) { + + if ( transform.texCoord !== undefined ) { + + console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' ); + + } + + if ( transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined ) { + + // See https://github.com/mrdoob/three.js/issues/21819. + return texture; + + } texture = texture.clone(); @@ -51650,60 +52818,56 @@ var GLTFLoader = ( function () { } - if ( transform.texCoord !== undefined ) { - - console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' ); - - } - texture.needsUpdate = true; return texture; - }; + } - /** - * Specular-Glossiness Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness - */ +} - /** - * A sub class of StandardMaterial with some of the functionality - * changed via the `onBeforeCompile` callback - * @pailhead - */ +/** + * Specular-Glossiness Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness + */ - function GLTFMeshStandardSGMaterial( params ) { +/** + * A sub class of StandardMaterial with some of the functionality + * changed via the `onBeforeCompile` callback + * @pailhead + */ +class GLTFMeshStandardSGMaterial extends MeshStandardMaterial { - MeshStandardMaterial.call( this ); + constructor( params ) { + + super(); this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing - var specularMapParsFragmentChunk = [ + const specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' ); - var glossinessMapParsFragmentChunk = [ + const glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' ); - var specularMapFragmentChunk = [ + const specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', - ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' ); - var glossinessMapFragmentChunk = [ + const glossinessMapFragmentChunk = [ 'float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', @@ -51712,18 +52876,18 @@ var GLTFLoader = ( function () { '#endif' ].join( '\n' ); - var lightPhysicalFragmentChunk = [ + const lightPhysicalFragmentChunk = [ 'PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', - 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', - 'material.specularRoughness += geometryRoughness;', - 'material.specularRoughness = min( material.specularRoughness, 1.0 );', + 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', + 'material.roughness += geometryRoughness;', + 'material.roughness = min( material.roughness, 1.0 );', 'material.specularColor = specularFactor;', ].join( '\n' ); - var uniforms = { + const uniforms = { specular: { value: new Color().setHex( 0xffffff ) }, glossiness: { value: 1 }, specularMap: { value: null }, @@ -51734,7 +52898,7 @@ var GLTFLoader = ( function () { this.onBeforeCompile = function ( shader ) { - for ( var uniformName in uniforms ) { + for ( const uniformName in uniforms ) { shader.uniforms[ uniformName ] = uniforms[ uniformName ]; @@ -51838,12 +53002,10 @@ var GLTFLoader = ( function () { } - GLTFMeshStandardSGMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); - GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial; + copy( source ) { - GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) { + super.copy( source ); - MeshStandardMaterial.prototype.copy.call( this, source ); this.specularMap = source.specularMap; this.specular.copy( source.specular ); this.glossinessMap = source.glossinessMap; @@ -51854,182 +53016,185 @@ var GLTFLoader = ( function () { delete this.roughnessMap; return this; - }; + } - function GLTFMaterialsPbrSpecularGlossinessExtension() { +} - return { - name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS, - - specularGlossinessParams: [ - 'color', - 'map', - 'lightMap', - 'lightMapIntensity', - 'aoMap', - 'aoMapIntensity', - 'emissive', - 'emissiveIntensity', - 'emissiveMap', - 'bumpMap', - 'bumpScale', - 'normalMap', - 'normalMapType', - 'displacementMap', - 'displacementScale', - 'displacementBias', - 'specularMap', - 'specular', - 'glossinessMap', - 'glossiness', - 'alphaMap', - 'envMap', - 'envMapIntensity', - 'refractionRatio', - ], - - getMaterialType: function () { - - return GLTFMeshStandardSGMaterial; +class GLTFMaterialsPbrSpecularGlossinessExtension { - }, + constructor() { - extendParams: function ( materialParams, materialDef, parser ) { + this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS; + + this.specularGlossinessParams = [ + 'color', + 'map', + 'lightMap', + 'lightMapIntensity', + 'aoMap', + 'aoMapIntensity', + 'emissive', + 'emissiveIntensity', + 'emissiveMap', + 'bumpMap', + 'bumpScale', + 'normalMap', + 'normalMapType', + 'displacementMap', + 'displacementScale', + 'displacementBias', + 'specularMap', + 'specular', + 'glossinessMap', + 'glossiness', + 'alphaMap', + 'envMap', + 'envMapIntensity' + ]; - var pbrSpecularGlossiness = materialDef.extensions[ this.name ]; + } - materialParams.color = new Color( 1.0, 1.0, 1.0 ); - materialParams.opacity = 1.0; + getMaterialType() { - var pending = []; + return GLTFMeshStandardSGMaterial; - if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) { + } - var array = pbrSpecularGlossiness.diffuseFactor; + extendParams( materialParams, materialDef, parser ) { - materialParams.color.fromArray( array ); - materialParams.opacity = array[ 3 ]; + const pbrSpecularGlossiness = materialDef.extensions[ this.name ]; - } + materialParams.color = new Color( 1.0, 1.0, 1.0 ); + materialParams.opacity = 1.0; - if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) { + const pending = []; - pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) ); + if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) { - } + const array = pbrSpecularGlossiness.diffuseFactor; - materialParams.emissive = new Color( 0.0, 0.0, 0.0 ); - materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; - materialParams.specular = new Color( 1.0, 1.0, 1.0 ); + materialParams.color.fromArray( array ); + materialParams.opacity = array[ 3 ]; - if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { + } - materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor ); + if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) { - } + pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture, sRGBEncoding ) ); - if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) { + } - var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; - pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) ); - pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) ); + materialParams.emissive = new Color( 0.0, 0.0, 0.0 ); + materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; + materialParams.specular = new Color( 1.0, 1.0, 1.0 ); - } + if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { - return Promise.all( pending ); + materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor ); - }, + } - createMaterial: function ( materialParams ) { + if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) { - var material = new GLTFMeshStandardSGMaterial( materialParams ); - material.fog = true; + const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; + pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) ); + pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef, sRGBEncoding ) ); - material.color = materialParams.color; + } - material.map = materialParams.map === undefined ? null : materialParams.map; + return Promise.all( pending ); - material.lightMap = null; - material.lightMapIntensity = 1.0; + } - material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap; - material.aoMapIntensity = 1.0; + createMaterial( materialParams ) { - material.emissive = materialParams.emissive; - material.emissiveIntensity = 1.0; - material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap; + const material = new GLTFMeshStandardSGMaterial( materialParams ); + material.fog = true; - material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap; - material.bumpScale = 1; + material.color = materialParams.color; - material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap; - material.normalMapType = TangentSpaceNormalMap; + material.map = materialParams.map === undefined ? null : materialParams.map; - if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale; + material.lightMap = null; + material.lightMapIntensity = 1.0; - material.displacementMap = null; - material.displacementScale = 1; - material.displacementBias = 0; + material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap; + material.aoMapIntensity = 1.0; - material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap; - material.specular = materialParams.specular; + material.emissive = materialParams.emissive; + material.emissiveIntensity = materialParams.emissiveIntensity === undefined ? 1.0 : materialParams.emissiveIntensity; + material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap; - material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap; - material.glossiness = materialParams.glossiness; + material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap; + material.bumpScale = 1; - material.alphaMap = null; + material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap; + material.normalMapType = TangentSpaceNormalMap; - material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap; - material.envMapIntensity = 1.0; + if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale; - material.refractionRatio = 0.98; + material.displacementMap = null; + material.displacementScale = 1; + material.displacementBias = 0; - return material; + material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap; + material.specular = materialParams.specular; - }, + material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap; + material.glossiness = materialParams.glossiness; - }; + material.alphaMap = null; + + material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap; + material.envMapIntensity = 1.0; + + return material; } - /** - * Mesh Quantization Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization - */ - function GLTFMeshQuantizationExtension() { +} + +/** + * Mesh Quantization Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization + */ +class GLTFMeshQuantizationExtension { + + constructor() { this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; } - /*********************************/ - /********** INTERPOLATION ********/ - /*********************************/ +} - // Spline Interpolation - // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation - function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { +/*********************************/ +/********** INTERPOLATION ********/ +/*********************************/ - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); +// Spline Interpolation +// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation +class GLTFCubicSplineInterpolant extends Interpolant { - } + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - GLTFCubicSplineInterpolant.prototype = Object.create( Interpolant.prototype ); - GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant; + } - GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) { + copySampleValue_( index ) { // Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. - var result = this.resultBuffer, + const result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; - for ( var i = 0; i !== valueSize; i ++ ) { + for ( let i = 0; i !== valueSize; i ++ ) { result[ i ] = values[ offset + i ]; @@ -52037,43 +53202,39 @@ var GLTFLoader = ( function () { return result; - }; - - GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; - - GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; + } - GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) { + interpolate_( i1, t0, t, t1 ) { - var result = this.resultBuffer; - var values = this.sampleValues; - var stride = this.valueSize; + const result = this.resultBuffer; + const values = this.sampleValues; + const stride = this.valueSize; - var stride2 = stride * 2; - var stride3 = stride * 3; + const stride2 = stride * 2; + const stride3 = stride * 3; - var td = t1 - t0; + const td = t1 - t0; - var p = ( t - t0 ) / td; - var pp = p * p; - var ppp = pp * p; + const p = ( t - t0 ) / td; + const pp = p * p; + const ppp = pp * p; - var offset1 = i1 * stride3; - var offset0 = offset1 - stride3; + const offset1 = i1 * stride3; + const offset0 = offset1 - stride3; - var s2 = - 2 * ppp + 3 * pp; - var s3 = ppp - pp; - var s0 = 1 - s2; - var s1 = s3 - pp + p; + const s2 = - 2 * ppp + 3 * pp; + const s3 = ppp - pp; + const s0 = 1 - s2; + const s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] - for ( var i = 0; i !== stride; i ++ ) { + for ( let i = 0; i !== stride; i ++ ) { - var p0 = values[ offset0 + i + stride ]; // splineVertex_k - var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k) - var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1 - var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k) + const p0 = values[ offset0 + i + stride ]; // splineVertex_k + const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k) + const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1 + const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k) result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; @@ -52081,352 +53242,396 @@ var GLTFLoader = ( function () { return result; - }; + } - /*********************************/ - /********** INTERNALS ************/ - /*********************************/ - - /* CONSTANTS */ - - var WEBGL_CONSTANTS = { - FLOAT: 5126, - //FLOAT_MAT2: 35674, - FLOAT_MAT3: 35675, - FLOAT_MAT4: 35676, - FLOAT_VEC2: 35664, - FLOAT_VEC3: 35665, - FLOAT_VEC4: 35666, - LINEAR: 9729, - REPEAT: 10497, - SAMPLER_2D: 35678, - POINTS: 0, - LINES: 1, - LINE_LOOP: 2, - LINE_STRIP: 3, - TRIANGLES: 4, - TRIANGLE_STRIP: 5, - TRIANGLE_FAN: 6, - UNSIGNED_BYTE: 5121, - UNSIGNED_SHORT: 5123 - }; +} - var WEBGL_COMPONENT_TYPES = { - 5120: Int8Array, - 5121: Uint8Array, - 5122: Int16Array, - 5123: Uint16Array, - 5125: Uint32Array, - 5126: Float32Array - }; +const _q = new Quaternion(); - var WEBGL_FILTERS = { - 9728: NearestFilter, - 9729: LinearFilter, - 9984: NearestMipmapNearestFilter, - 9985: LinearMipmapNearestFilter, - 9986: NearestMipmapLinearFilter, - 9987: LinearMipmapLinearFilter - }; +class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { - var WEBGL_WRAPPINGS = { - 33071: ClampToEdgeWrapping, - 33648: MirroredRepeatWrapping, - 10497: RepeatWrapping - }; + interpolate_( i1, t0, t, t1 ) { - var WEBGL_TYPE_SIZES = { - 'SCALAR': 1, - 'VEC2': 2, - 'VEC3': 3, - 'VEC4': 4, - 'MAT2': 4, - 'MAT3': 9, - 'MAT4': 16 - }; + const result = super.interpolate_( i1, t0, t, t1 ); - var ATTRIBUTES = { - POSITION: 'position', - NORMAL: 'normal', - TANGENT: 'tangent', - TEXCOORD_0: 'uv', - TEXCOORD_1: 'uv2', - COLOR_0: 'color', - WEIGHTS_0: 'skinWeight', - JOINTS_0: 'skinIndex', - }; - - var PATH_PROPERTIES = { - scale: 'scale', - translation: 'position', - rotation: 'quaternion', - weights: 'morphTargetInfluences' - }; + _q.fromArray( result ).normalize().toArray( result ); - var INTERPOLATION = { - CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each - // keyframe track will be initialized with a default interpolation type, then modified. - LINEAR: InterpolateLinear, - STEP: InterpolateDiscrete - }; + return result; - var ALPHA_MODES = { - OPAQUE: 'OPAQUE', - MASK: 'MASK', - BLEND: 'BLEND' - }; + } - /* UTILITY FUNCTIONS */ +} - function resolveURL( url, path ) { - // Invalid URL - if ( typeof url !== 'string' || url === '' ) return ''; +/*********************************/ +/********** INTERNALS ************/ +/*********************************/ - // Host Relative URL - if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { +/* CONSTANTS */ - path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); +const WEBGL_CONSTANTS = { + FLOAT: 5126, + //FLOAT_MAT2: 35674, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + LINEAR: 9729, + REPEAT: 10497, + SAMPLER_2D: 35678, + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + UNSIGNED_BYTE: 5121, + UNSIGNED_SHORT: 5123 +}; - } +const WEBGL_COMPONENT_TYPES = { + 5120: Int8Array, + 5121: Uint8Array, + 5122: Int16Array, + 5123: Uint16Array, + 5125: Uint32Array, + 5126: Float32Array +}; - // Absolute URL http://,https://,// - if ( /^(https?:)?\/\//i.test( url ) ) return url; +const WEBGL_FILTERS = { + 9728: NearestFilter, + 9729: LinearFilter, + 9984: NearestMipmapNearestFilter, + 9985: LinearMipmapNearestFilter, + 9986: NearestMipmapLinearFilter, + 9987: LinearMipmapLinearFilter +}; - // Data URI - if ( /^data:.*,.*$/i.test( url ) ) return url; +const WEBGL_WRAPPINGS = { + 33071: ClampToEdgeWrapping, + 33648: MirroredRepeatWrapping, + 10497: RepeatWrapping +}; - // Blob URL - if ( /^blob:.*$/i.test( url ) ) return url; +const WEBGL_TYPE_SIZES = { + 'SCALAR': 1, + 'VEC2': 2, + 'VEC3': 3, + 'VEC4': 4, + 'MAT2': 4, + 'MAT3': 9, + 'MAT4': 16 +}; - // Relative URL - return path + url; +const ATTRIBUTES = { + POSITION: 'position', + NORMAL: 'normal', + TANGENT: 'tangent', + TEXCOORD_0: 'uv', + TEXCOORD_1: 'uv2', + COLOR_0: 'color', + WEIGHTS_0: 'skinWeight', + JOINTS_0: 'skinIndex', +}; - } +const PATH_PROPERTIES = { + scale: 'scale', + translation: 'position', + rotation: 'quaternion', + weights: 'morphTargetInfluences' +}; - /** - * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material - */ - function createDefaultMaterial( cache ) { - - if ( cache[ 'DefaultMaterial' ] === undefined ) { - - cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( { - color: 0xFFFFFF, - emissive: 0x000000, - metalness: 1, - roughness: 1, - transparent: false, - depthTest: true, - side: FrontSide - } ); +const INTERPOLATION = { + CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each + // keyframe track will be initialized with a default interpolation type, then modified. + LINEAR: InterpolateLinear, + STEP: InterpolateDiscrete +}; - } +const ALPHA_MODES = { + OPAQUE: 'OPAQUE', + MASK: 'MASK', + BLEND: 'BLEND' +}; - return cache[ 'DefaultMaterial' ]; +/** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material + */ +function createDefaultMaterial( cache ) { + + if ( cache[ 'DefaultMaterial' ] === undefined ) { + + cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( { + color: 0xFFFFFF, + emissive: 0x000000, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: FrontSide + } ); } - function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) { + return cache[ 'DefaultMaterial' ]; - // Add unknown glTF extensions to an object's userData. +} - for ( var name in objectDef.extensions ) { +function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) { - if ( knownExtensions[ name ] === undefined ) { + // Add unknown glTF extensions to an object's userData. - object.userData.gltfExtensions = object.userData.gltfExtensions || {}; - object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ]; + for ( const name in objectDef.extensions ) { - } + if ( knownExtensions[ name ] === undefined ) { + + object.userData.gltfExtensions = object.userData.gltfExtensions || {}; + object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ]; } } - /** - * @param {Object3D|Material|BufferGeometry} object - * @param {GLTF.definition} gltfDef - */ - function assignExtrasToUserData( object, gltfDef ) { +} - if ( gltfDef.extras !== undefined ) { +/** + * @param {Object3D|Material|BufferGeometry} object + * @param {GLTF.definition} gltfDef + */ +function assignExtrasToUserData( object, gltfDef ) { - if ( typeof gltfDef.extras === 'object' ) { + if ( gltfDef.extras !== undefined ) { - Object.assign( object.userData, gltfDef.extras ); + if ( typeof gltfDef.extras === 'object' ) { - } else { + Object.assign( object.userData, gltfDef.extras ); - console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras ); + } else { - } + console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras ); } } - /** - * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets - * - * @param {BufferGeometry} geometry - * @param {Array} targets - * @param {GLTFParser} parser - * @return {Promise} - */ - function addMorphTargets( geometry, targets, parser ) { +} - var hasMorphPosition = false; - var hasMorphNormal = false; +/** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets + * + * @param {BufferGeometry} geometry + * @param {Array} targets + * @param {GLTFParser} parser + * @return {Promise} + */ +function addMorphTargets( geometry, targets, parser ) { - for ( var i = 0, il = targets.length; i < il; i ++ ) { + let hasMorphPosition = false; + let hasMorphNormal = false; + let hasMorphColor = false; - var target = targets[ i ]; + for ( let i = 0, il = targets.length; i < il; i ++ ) { - if ( target.POSITION !== undefined ) hasMorphPosition = true; - if ( target.NORMAL !== undefined ) hasMorphNormal = true; + const target = targets[ i ]; - if ( hasMorphPosition && hasMorphNormal ) break; + if ( target.POSITION !== undefined ) hasMorphPosition = true; + if ( target.NORMAL !== undefined ) hasMorphNormal = true; + if ( target.COLOR_0 !== undefined ) hasMorphColor = true; - } + if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break; - if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry ); + } - var pendingPositionAccessors = []; - var pendingNormalAccessors = []; + if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry ); - for ( var i = 0, il = targets.length; i < il; i ++ ) { + const pendingPositionAccessors = []; + const pendingNormalAccessors = []; + const pendingColorAccessors = []; - var target = targets[ i ]; + for ( let i = 0, il = targets.length; i < il; i ++ ) { - if ( hasMorphPosition ) { + const target = targets[ i ]; - var pendingAccessor = target.POSITION !== undefined - ? parser.getDependency( 'accessor', target.POSITION ) - : geometry.attributes.position; + if ( hasMorphPosition ) { - pendingPositionAccessors.push( pendingAccessor ); + const pendingAccessor = target.POSITION !== undefined + ? parser.getDependency( 'accessor', target.POSITION ) + : geometry.attributes.position; - } + pendingPositionAccessors.push( pendingAccessor ); - if ( hasMorphNormal ) { + } - var pendingAccessor = target.NORMAL !== undefined - ? parser.getDependency( 'accessor', target.NORMAL ) - : geometry.attributes.normal; + if ( hasMorphNormal ) { - pendingNormalAccessors.push( pendingAccessor ); + const pendingAccessor = target.NORMAL !== undefined + ? parser.getDependency( 'accessor', target.NORMAL ) + : geometry.attributes.normal; - } + pendingNormalAccessors.push( pendingAccessor ); } - return Promise.all( [ - Promise.all( pendingPositionAccessors ), - Promise.all( pendingNormalAccessors ) - ] ).then( function ( accessors ) { + if ( hasMorphColor ) { - var morphPositions = accessors[ 0 ]; - var morphNormals = accessors[ 1 ]; + const pendingAccessor = target.COLOR_0 !== undefined + ? parser.getDependency( 'accessor', target.COLOR_0 ) + : geometry.attributes.color; - if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; - if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; - geometry.morphTargetsRelative = true; + pendingColorAccessors.push( pendingAccessor ); - return geometry; - - } ); + } } - /** - * @param {Mesh} mesh - * @param {GLTF.Mesh} meshDef - */ - function updateMorphTargets( mesh, meshDef ) { + return Promise.all( [ + Promise.all( pendingPositionAccessors ), + Promise.all( pendingNormalAccessors ), + Promise.all( pendingColorAccessors ) + ] ).then( function ( accessors ) { - mesh.updateMorphTargets(); + const morphPositions = accessors[ 0 ]; + const morphNormals = accessors[ 1 ]; + const morphColors = accessors[ 2 ]; - if ( meshDef.weights !== undefined ) { + if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; + if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; + if ( hasMorphColor ) geometry.morphAttributes.color = morphColors; + geometry.morphTargetsRelative = true; - for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) { + return geometry; - mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ]; + } ); - } +} - } +/** + * @param {Mesh} mesh + * @param {GLTF.Mesh} meshDef + */ +function updateMorphTargets( mesh, meshDef ) { - // .extras has user-defined data, so check that .extras.targetNames is an array. - if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) { + mesh.updateMorphTargets(); - var targetNames = meshDef.extras.targetNames; + if ( meshDef.weights !== undefined ) { - if ( mesh.morphTargetInfluences.length === targetNames.length ) { + for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) { - mesh.morphTargetDictionary = {}; + mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ]; - for ( var i = 0, il = targetNames.length; i < il; i ++ ) { + } - mesh.morphTargetDictionary[ targetNames[ i ] ] = i; + } - } + // .extras has user-defined data, so check that .extras.targetNames is an array. + if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) { - } else { + const targetNames = meshDef.extras.targetNames; - console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' ); + if ( mesh.morphTargetInfluences.length === targetNames.length ) { + + mesh.morphTargetDictionary = {}; + + for ( let i = 0, il = targetNames.length; i < il; i ++ ) { + + mesh.morphTargetDictionary[ targetNames[ i ] ] = i; } + } else { + + console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' ); + } } - function createPrimitiveKey( primitiveDef ) { +} + +function createPrimitiveKey( primitiveDef ) { - var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]; - var geometryKey; + const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]; + let geometryKey; - if ( dracoExtension ) { + if ( dracoExtension ) { - geometryKey = 'draco:' + dracoExtension.bufferView + geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey( dracoExtension.attributes ); - } else { + } else { - geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode; + geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode; - } + } + + return geometryKey; - return geometryKey; +} + +function createAttributesKey( attributes ) { + + let attributesKey = ''; + + const keys = Object.keys( attributes ).sort(); + + for ( let i = 0, il = keys.length; i < il; i ++ ) { + + attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';'; } - function createAttributesKey( attributes ) { + return attributesKey; - var attributesKey = ''; +} - var keys = Object.keys( attributes ).sort(); +function getNormalizedComponentScale( constructor ) { - for ( var i = 0, il = keys.length; i < il; i ++ ) { + // Reference: + // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data - attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';'; + switch ( constructor ) { - } + case Int8Array: + return 1 / 127; - return attributesKey; + case Uint8Array: + return 1 / 255; + + case Int16Array: + return 1 / 32767; + + case Uint16Array: + return 1 / 65535; + + default: + throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' ); } - /* GLTF PARSER */ +} + +function getImageURIMimeType( uri ) { - function GLTFParser( json, options ) { + if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg'; + if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp'; - this.json = json || {}; + return 'image/png'; + +} + +/* GLTF PARSER */ + +class GLTFParser { + + constructor( json = {}, options = {} ) { + + this.json = json; this.extensions = {}; this.plugins = {}; - this.options = options || {}; + this.options = options; // loader object cache this.cache = new GLTFRegistry(); @@ -52442,19 +53647,27 @@ var GLTFLoader = ( function () { this.cameraCache = { refs: {}, uses: {} }; this.lightCache = { refs: {}, uses: {} }; + this.sourceCache = {}; + this.textureCache = {}; + // Track node names, to ensure no duplicates this.nodeNamesUsed = {}; // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the // expensive work of uploading a texture to the GPU off the main thread. - if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) { - this.textureLoader = new ImageBitmapLoader( this.options.manager ); + const isSafari = /^((?!chrome|android).)*safari/i.test( navigator.userAgent ) === true; + const isFirefox = navigator.userAgent.indexOf( 'Firefox' ) > - 1; + const firefoxVersion = isFirefox ? navigator.userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1; - } else { + if ( typeof createImageBitmap === 'undefined' || isSafari || ( isFirefox && firefoxVersion < 98 ) ) { this.textureLoader = new TextureLoader( this.options.manager ); + } else { + + this.textureLoader = new ImageBitmapLoader( this.options.manager ); + } this.textureLoader.setCrossOrigin( this.options.crossOrigin ); @@ -52471,23 +53684,23 @@ var GLTFLoader = ( function () { } - GLTFParser.prototype.setExtensions = function ( extensions ) { + setExtensions( extensions ) { this.extensions = extensions; - }; + } - GLTFParser.prototype.setPlugins = function ( plugins ) { + setPlugins( plugins ) { this.plugins = plugins; - }; + } - GLTFParser.prototype.parse = function ( onLoad, onError ) { + parse( onLoad, onError ) { - var parser = this; - var json = this.json; - var extensions = this.extensions; + const parser = this; + const json = this.json; + const extensions = this.extensions; // Clear the loader cache this.cache.removeAll(); @@ -52515,7 +53728,7 @@ var GLTFLoader = ( function () { } ).then( function ( dependencies ) { - var result = { + const result = { scene: dependencies[ 0 ][ json.scene || 0 ], scenes: dependencies[ 0 ], animations: dependencies[ 1 ], @@ -52541,24 +53754,24 @@ var GLTFLoader = ( function () { } ).catch( onError ); - }; + } /** * Marks the special nodes/meshes in json for efficient parse. */ - GLTFParser.prototype._markDefs = function () { + _markDefs() { - var nodeDefs = this.json.nodes || []; - var skinDefs = this.json.skins || []; - var meshDefs = this.json.meshes || []; + const nodeDefs = this.json.nodes || []; + const skinDefs = this.json.skins || []; + const meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a Bone or an // Object3D. Use the skins' joint references to mark bones. - for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { + for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { - var joints = skinDefs[ skinIndex ].joints; + const joints = skinDefs[ skinIndex ].joints; - for ( var i = 0, il = joints.length; i < il; i ++ ) { + for ( let i = 0, il = joints.length; i < il; i ++ ) { nodeDefs[ joints[ i ] ].isBone = true; @@ -52568,9 +53781,9 @@ var GLTFLoader = ( function () { // Iterate over all nodes, marking references to shared resources, // as well as skeleton joints. - for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { + for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { - var nodeDef = nodeDefs[ nodeIndex ]; + const nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.mesh !== undefined ) { @@ -52595,7 +53808,7 @@ var GLTFLoader = ( function () { } - }; + } /** * Counts references to shared node / Object3D resources. These resources @@ -52606,7 +53819,7 @@ var GLTFLoader = ( function () { * * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. */ - GLTFParser.prototype._addNodeRef = function ( cache, index ) { + _addNodeRef( cache, index ) { if ( index === undefined ) return; @@ -52618,46 +53831,69 @@ var GLTFLoader = ( function () { cache.refs[ index ] ++; - }; + } /** Returns a reference to a shared resource, cloning it if necessary. */ - GLTFParser.prototype._getNodeRef = function ( cache, index, object ) { + _getNodeRef( cache, index, object ) { if ( cache.refs[ index ] <= 1 ) return object; - var ref = object.clone(); + const ref = object.clone(); + + // Propagates mappings to the cloned object, prevents mappings on the + // original object from being lost. + const updateMappings = ( original, clone ) => { + + const mappings = this.associations.get( original ); + if ( mappings != null ) { + + this.associations.set( clone, mappings ); + + } + + for ( const [ i, child ] of original.children.entries() ) { + + updateMappings( child, clone.children[ i ] ); + + } + + }; + + updateMappings( object, ref ); ref.name += '_instance_' + ( cache.uses[ index ] ++ ); return ref; - }; + } - GLTFParser.prototype._invokeOne = function ( func ) { + _invokeOne( func ) { - var extensions = Object.values( this.plugins ); + const extensions = Object.values( this.plugins ); extensions.push( this ); - for ( var i = 0; i < extensions.length; i ++ ) { + for ( let i = 0; i < extensions.length; i ++ ) { - var result = func( extensions[ i ] ); + const result = func( extensions[ i ] ); if ( result ) return result; } - }; + return null; - GLTFParser.prototype._invokeAll = function ( func ) { + } - var extensions = Object.values( this.plugins ); + _invokeAll( func ) { + + const extensions = Object.values( this.plugins ); extensions.unshift( this ); - var pending = []; + const pending = []; - for ( var i = 0; i < extensions.length; i ++ ) { + for ( let i = 0; i < extensions.length; i ++ ) { - var result = func( extensions[ i ] ); + const result = func( extensions[ i ] ); if ( result ) pending.push( result ); @@ -52665,7 +53901,7 @@ var GLTFLoader = ( function () { return pending; - }; + } /** * Requests the specified dependency asynchronously, with caching. @@ -52673,10 +53909,10 @@ var GLTFLoader = ( function () { * @param {number} index * @return {Promise} */ - GLTFParser.prototype.getDependency = function ( type, index ) { + getDependency( type, index ) { - var cacheKey = type + ':' + index; - var dependency = this.cache.get( cacheKey ); + const cacheKey = type + ':' + index; + let dependency = this.cache.get( cacheKey ); if ( ! dependency ) { @@ -52735,7 +53971,11 @@ var GLTFLoader = ( function () { break; case 'animation': - dependency = this.loadAnimation( index ); + dependency = this._invokeOne( function ( ext ) { + + return ext.loadAnimation && ext.loadAnimation( index ); + + } ); break; case 'camera': @@ -52753,21 +53993,21 @@ var GLTFLoader = ( function () { return dependency; - }; + } /** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise>} */ - GLTFParser.prototype.getDependencies = function ( type ) { + getDependencies( type ) { - var dependencies = this.cache.get( type ); + let dependencies = this.cache.get( type ); if ( ! dependencies ) { - var parser = this; - var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || []; + const parser = this; + const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || []; dependencies = Promise.all( defs.map( function ( def, index ) { @@ -52781,17 +54021,17 @@ var GLTFLoader = ( function () { return dependencies; - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise} */ - GLTFParser.prototype.loadBuffer = function ( bufferIndex ) { + loadBuffer( bufferIndex ) { - var bufferDef = this.json.buffers[ bufferIndex ]; - var loader = this.fileLoader; + const bufferDef = this.json.buffers[ bufferIndex ]; + const loader = this.fileLoader; if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) { @@ -52806,11 +54046,11 @@ var GLTFLoader = ( function () { } - var options = this.options; + const options = this.options; return new Promise( function ( resolve, reject ) { - loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () { + loader.load( LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () { reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) ); @@ -52818,38 +54058,38 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise} */ - GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) { + loadBufferView( bufferViewIndex ) { - var bufferViewDef = this.json.bufferViews[ bufferViewIndex ]; + const bufferViewDef = this.json.bufferViews[ bufferViewIndex ]; return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) { - var byteLength = bufferViewDef.byteLength || 0; - var byteOffset = bufferViewDef.byteOffset || 0; + const byteLength = bufferViewDef.byteLength || 0; + const byteOffset = bufferViewDef.byteOffset || 0; return buffer.slice( byteOffset, byteOffset + byteLength ); } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise} */ - GLTFParser.prototype.loadAccessor = function ( accessorIndex ) { + loadAccessor( accessorIndex ) { - var parser = this; - var json = this.json; + const parser = this; + const json = this.json; - var accessorDef = this.json.accessors[ accessorIndex ]; + const accessorDef = this.json.accessors[ accessorIndex ]; if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) { @@ -52860,7 +54100,7 @@ var GLTFLoader = ( function () { } - var pendingBufferViews = []; + const pendingBufferViews = []; if ( accessorDef.bufferView !== undefined ) { @@ -52881,27 +54121,27 @@ var GLTFLoader = ( function () { return Promise.all( pendingBufferViews ).then( function ( bufferViews ) { - var bufferView = bufferViews[ 0 ]; + const bufferView = bufferViews[ 0 ]; - var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; - var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; + const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; + const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. - var elementBytes = TypedArray.BYTES_PER_ELEMENT; - var itemBytes = elementBytes * itemSize; - var byteOffset = accessorDef.byteOffset || 0; - var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined; - var normalized = accessorDef.normalized === true; - var array, bufferAttribute; + const elementBytes = TypedArray.BYTES_PER_ELEMENT; + const itemBytes = elementBytes * itemSize; + const byteOffset = accessorDef.byteOffset || 0; + const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined; + const normalized = accessorDef.normalized === true; + let array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes. if ( byteStride && byteStride !== itemBytes ) { // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer // This makes sure that IBA.count reflects accessor.count properly - var ibSlice = Math.floor( byteOffset / byteStride ); - var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; - var ib = parser.cache.get( ibCacheKey ); + const ibSlice = Math.floor( byteOffset / byteStride ); + const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; + let ib = parser.cache.get( ibCacheKey ); if ( ! ib ) { @@ -52935,14 +54175,14 @@ var GLTFLoader = ( function () { // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors if ( accessorDef.sparse !== undefined ) { - var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; - var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ]; + const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; + const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ]; - var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; - var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; + const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; + const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; - var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices ); - var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize ); + const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices ); + const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize ); if ( bufferView !== null ) { @@ -52951,9 +54191,9 @@ var GLTFLoader = ( function () { } - for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) { + for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) { - var index = sparseIndices[ i ]; + const index = sparseIndices[ i ]; bufferAttribute.setX( index, sparseValues[ i * itemSize ] ); if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] ); @@ -52969,98 +54209,139 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise} */ - GLTFParser.prototype.loadTexture = function ( textureIndex ) { + loadTexture( textureIndex ) { - var json = this.json; - var options = this.options; - var textureDef = json.textures[ textureIndex ]; - var source = json.images[ textureDef.source ]; + const json = this.json; + const options = this.options; + const textureDef = json.textures[ textureIndex ]; + const sourceIndex = textureDef.source; + const sourceDef = json.images[ sourceIndex ]; - var loader = this.textureLoader; + let loader = this.textureLoader; - if ( source.uri ) { + if ( sourceDef.uri ) { - var handler = options.manager.getHandler( source.uri ); + const handler = options.manager.getHandler( sourceDef.uri ); if ( handler !== null ) loader = handler; } - return this.loadTextureImage( textureIndex, source, loader ); + return this.loadTextureImage( textureIndex, sourceIndex, loader ); - }; + } - GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) { + loadTextureImage( textureIndex, sourceIndex, loader ) { - var parser = this; - var json = this.json; - var options = this.options; + const parser = this; + const json = this.json; - var textureDef = json.textures[ textureIndex ]; + const textureDef = json.textures[ textureIndex ]; + const sourceDef = json.images[ sourceIndex ]; - var URL = self.URL || self.webkitURL; + const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler; - var sourceURI = source.uri; - var isObjectURL = false; - var hasAlpha = true; + if ( this.textureCache[ cacheKey ] ) { - if ( source.mimeType === 'image/jpeg' ) hasAlpha = false; + // See https://github.com/mrdoob/three.js/issues/21559. + return this.textureCache[ cacheKey ]; - if ( source.bufferView !== undefined ) { + } - // Load binary image data from bufferView, if provided. + const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) { - sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) { + texture.flipY = false; - if ( source.mimeType === 'image/png' ) { + if ( textureDef.name ) texture.name = textureDef.name; - // Inspect the PNG 'IHDR' chunk to determine whether the image could have an - // alpha channel. This check is conservative — the image could have an alpha - // channel with all values == 1, and the indexed type (colorType == 3) only - // sometimes contains alpha. - // - // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header - var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false ); - hasAlpha = colorType === 6 || colorType === 4 || colorType === 3; + const samplers = json.samplers || {}; + const sampler = samplers[ textureDef.sampler ] || {}; - } + texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter; + texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping; + + parser.associations.set( texture, { textures: textureIndex } ); + + return texture; + + } ).catch( function () { + + return null; + + } ); + + this.textureCache[ cacheKey ] = promise; + + return promise; + + } + + loadImageSource( sourceIndex, loader ) { + + const parser = this; + const json = this.json; + const options = this.options; + + if ( this.sourceCache[ sourceIndex ] !== undefined ) { + + return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() ); + + } + + const sourceDef = json.images[ sourceIndex ]; + + const URL = self.URL || self.webkitURL; + + let sourceURI = sourceDef.uri || ''; + let isObjectURL = false; + + if ( sourceDef.bufferView !== undefined ) { + + // Load binary image data from bufferView, if provided. + + sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) { isObjectURL = true; - var blob = new Blob( [ bufferView ], { type: source.mimeType } ); + const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } ); sourceURI = URL.createObjectURL( blob ); return sourceURI; } ); - } else if ( source.uri === undefined ) { + } else if ( sourceDef.uri === undefined ) { - throw new Error( 'THREE.GLTFLoader: Image ' + textureIndex + ' is missing URI and bufferView' ); + throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' ); } - return Promise.resolve( sourceURI ).then( function ( sourceURI ) { + const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) { return new Promise( function ( resolve, reject ) { - var onLoad = resolve; + let onLoad = resolve; if ( loader.isImageBitmapLoader === true ) { onLoad = function ( imageBitmap ) { - resolve( new CanvasTexture( imageBitmap ) ); + const texture = new Texture( imageBitmap ); + texture.needsUpdate = true; + + resolve( texture ); }; } - loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject ); + loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject ); } ); @@ -53074,42 +54355,32 @@ var GLTFLoader = ( function () { } - texture.flipY = false; - - if ( textureDef.name ) texture.name = textureDef.name; - - // When there is definitely no alpha channel in the texture, set RGBFormat to save space. - if ( ! hasAlpha ) texture.format = RGBFormat; + texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri ); - var samplers = json.samplers || {}; - var sampler = samplers[ textureDef.sampler ] || {}; - - texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter; - texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter; - texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping; - texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping; + return texture; - parser.associations.set( texture, { - type: 'textures', - index: textureIndex - } ); + } ).catch( function ( error ) { - return texture; + console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI ); + throw error; } ); - }; + this.sourceCache[ sourceIndex ] = promise; + return promise; + + } /** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef - * @return {Promise} + * @return {Promise} */ - GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) { + assignTexture( materialParams, mapName, mapDef, encoding ) { - var parser = this; + const parser = this; return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) { @@ -53123,11 +54394,11 @@ var GLTFLoader = ( function () { if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) { - var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; + const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; if ( transform ) { - var gltfReference = parser.associations.get( texture ); + const gltfReference = parser.associations.get( texture ); texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform ); parser.associations.set( texture, gltfReference ); @@ -53135,11 +54406,19 @@ var GLTFLoader = ( function () { } + if ( encoding !== undefined ) { + + texture.encoding = encoding; + + } + materialParams[ mapName ] = texture; + return texture; + } ); - }; + } /** * Assigns final material to a Mesh, Line, or Points instance. The instance @@ -53149,23 +54428,20 @@ var GLTFLoader = ( function () { * be created if necessary, and reused from a cache. * @param {Object3D} mesh Mesh, Line, or Points instance. */ - GLTFParser.prototype.assignFinalMaterial = function ( mesh ) { + assignFinalMaterial( mesh ) { - var geometry = mesh.geometry; - var material = mesh.material; + const geometry = mesh.geometry; + let material = mesh.material; - var useVertexTangents = geometry.attributes.tangent !== undefined; - var useVertexColors = geometry.attributes.color !== undefined; - var useFlatShading = geometry.attributes.normal === undefined; - var useSkinning = mesh.isSkinnedMesh === true; - var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0; - var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined; + const useDerivativeTangents = geometry.attributes.tangent === undefined; + const useVertexColors = geometry.attributes.color !== undefined; + const useFlatShading = geometry.attributes.normal === undefined; if ( mesh.isPoints ) { - var cacheKey = 'PointsMaterial:' + material.uuid; + const cacheKey = 'PointsMaterial:' + material.uuid; - var pointsMaterial = this.cache.get( cacheKey ); + let pointsMaterial = this.cache.get( cacheKey ); if ( ! pointsMaterial ) { @@ -53183,9 +54459,9 @@ var GLTFLoader = ( function () { } else if ( mesh.isLine ) { - var cacheKey = 'LineBasicMaterial:' + material.uuid; + const cacheKey = 'LineBasicMaterial:' + material.uuid; - var lineMaterial = this.cache.get( cacheKey ); + let lineMaterial = this.cache.get( cacheKey ); if ( ! lineMaterial ) { @@ -53202,33 +54478,25 @@ var GLTFLoader = ( function () { } // Clone the material if it will be modified - if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) { + if ( useDerivativeTangents || useVertexColors || useFlatShading ) { - var cacheKey = 'ClonedMaterial:' + material.uuid + ':'; + let cacheKey = 'ClonedMaterial:' + material.uuid + ':'; if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:'; - if ( useSkinning ) cacheKey += 'skinning:'; - if ( useVertexTangents ) cacheKey += 'vertex-tangents:'; + if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:'; if ( useVertexColors ) cacheKey += 'vertex-colors:'; if ( useFlatShading ) cacheKey += 'flat-shading:'; - if ( useMorphTargets ) cacheKey += 'morph-targets:'; - if ( useMorphNormals ) cacheKey += 'morph-normals:'; - var cachedMaterial = this.cache.get( cacheKey ); + let cachedMaterial = this.cache.get( cacheKey ); if ( ! cachedMaterial ) { cachedMaterial = material.clone(); - if ( useSkinning ) cachedMaterial.skinning = true; if ( useVertexColors ) cachedMaterial.vertexColors = true; if ( useFlatShading ) cachedMaterial.flatShading = true; - if ( useMorphTargets ) cachedMaterial.morphTargets = true; - if ( useMorphNormals ) cachedMaterial.morphNormals = true; - - if ( useVertexTangents ) { - cachedMaterial.vertexTangents = true; + if ( useDerivativeTangents ) { // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1; @@ -53256,41 +54524,41 @@ var GLTFLoader = ( function () { mesh.material = material; - }; + } - GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) { + getMaterialType( /* materialIndex */ ) { return MeshStandardMaterial; - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise} */ - GLTFParser.prototype.loadMaterial = function ( materialIndex ) { + loadMaterial( materialIndex ) { - var parser = this; - var json = this.json; - var extensions = this.extensions; - var materialDef = json.materials[ materialIndex ]; + const parser = this; + const json = this.json; + const extensions = this.extensions; + const materialDef = json.materials[ materialIndex ]; - var materialType; - var materialParams = {}; - var materialExtensions = materialDef.extensions || {}; + let materialType; + const materialParams = {}; + const materialExtensions = materialDef.extensions || {}; - var pending = []; + const pending = []; if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) { - var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ]; + const sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ]; materialType = sgExtension.getMaterialType(); pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) ); } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) { - var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ]; + const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ]; materialType = kmuExtension.getMaterialType(); pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) ); @@ -53299,14 +54567,14 @@ var GLTFLoader = ( function () { // Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material - var metallicRoughness = materialDef.pbrMetallicRoughness || {}; + const metallicRoughness = materialDef.pbrMetallicRoughness || {}; materialParams.color = new Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { - var array = metallicRoughness.baseColorFactor; + const array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; @@ -53315,7 +54583,7 @@ var GLTFLoader = ( function () { if ( metallicRoughness.baseColorTexture !== undefined ) { - pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); + pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding ) ); } @@ -53349,7 +54617,7 @@ var GLTFLoader = ( function () { } - var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; + const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; if ( alphaMode === ALPHA_MODES.BLEND ) { @@ -53374,12 +54642,13 @@ var GLTFLoader = ( function () { pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) ); - // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 - materialParams.normalScale = new Vector2( 1, - 1 ); + materialParams.normalScale = new Vector2( 1, 1 ); if ( materialDef.normalTexture.scale !== undefined ) { - materialParams.normalScale.set( materialDef.normalTexture.scale, - materialDef.normalTexture.scale ); + const scale = materialDef.normalTexture.scale; + + materialParams.normalScale.set( scale, scale ); } @@ -53405,13 +54674,13 @@ var GLTFLoader = ( function () { if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) { - pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) ); + pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, sRGBEncoding ) ); } return Promise.all( pending ).then( function () { - var material; + let material; if ( materialType === GLTFMeshStandardSGMaterial ) { @@ -53425,13 +54694,9 @@ var GLTFLoader = ( function () { if ( materialDef.name ) material.name = materialDef.name; - // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. - if ( material.map ) material.map.encoding = sRGBEncoding; - if ( material.emissiveMap ) material.emissiveMap.encoding = sRGBEncoding; - assignExtrasToUserData( material, materialDef ); - parser.associations.set( material, { type: 'materials', index: materialIndex } ); + parser.associations.set( material, { materials: materialIndex } ); if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef ); @@ -53439,16 +54704,16 @@ var GLTFLoader = ( function () { } ); - }; + } /** When Object3D instances are targeted by animation, they need unique names. */ - GLTFParser.prototype.createUniqueName = function ( originalName ) { + createUniqueName( originalName ) { - var sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' ); + const sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' ); - var name = sanitizedName; + let name = sanitizedName; - for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) { + for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) { name = sanitizedName + '_' + i; @@ -53458,258 +54723,6 @@ var GLTFLoader = ( function () { return name; - }; - - /** - * @param {BufferGeometry} geometry - * @param {GLTF.Primitive} primitiveDef - * @param {GLTFParser} parser - */ - function computeBounds( geometry, primitiveDef, parser ) { - - var attributes = primitiveDef.attributes; - - var box = new Box3(); - - if ( attributes.POSITION !== undefined ) { - - var accessor = parser.json.accessors[ attributes.POSITION ]; - - var min = accessor.min; - var max = accessor.max; - - // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. - - if ( min !== undefined && max !== undefined ) { - - box.set( - new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ), - new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) ); - - } else { - - console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); - - return; - - } - - } else { - - return; - - } - - var targets = primitiveDef.targets; - - if ( targets !== undefined ) { - - var maxDisplacement = new Vector3(); - var vector = new Vector3(); - - for ( var i = 0, il = targets.length; i < il; i ++ ) { - - var target = targets[ i ]; - - if ( target.POSITION !== undefined ) { - - var accessor = parser.json.accessors[ target.POSITION ]; - var min = accessor.min; - var max = accessor.max; - - // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. - - if ( min !== undefined && max !== undefined ) { - - // we need to get max of absolute components because target weight is [-1,1] - vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) ); - vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) ); - vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) ); - - // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative - // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets - // are used to implement key-frame animations and as such only two are active at a time - this results in very large - // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size. - maxDisplacement.max( vector ); - - } else { - - console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); - - } - - } - - } - - // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets. - box.expandByVector( maxDisplacement ); - - } - - geometry.boundingBox = box; - - var sphere = new Sphere(); - - box.getCenter( sphere.center ); - sphere.radius = box.min.distanceTo( box.max ) / 2; - - geometry.boundingSphere = sphere; - - } - - /** - * @param {BufferGeometry} geometry - * @param {GLTF.Primitive} primitiveDef - * @param {GLTFParser} parser - * @return {Promise} - */ - function addPrimitiveAttributes( geometry, primitiveDef, parser ) { - - var attributes = primitiveDef.attributes; - - var pending = []; - - function assignAttributeAccessor( accessorIndex, attributeName ) { - - return parser.getDependency( 'accessor', accessorIndex ) - .then( function ( accessor ) { - - geometry.setAttribute( attributeName, accessor ); - - } ); - - } - - for ( var gltfAttributeName in attributes ) { - - var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); - - // Skip attributes already provided by e.g. Draco extension. - if ( threeAttributeName in geometry.attributes ) continue; - - pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) ); - - } - - if ( primitiveDef.indices !== undefined && ! geometry.index ) { - - var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) { - - geometry.setIndex( accessor ); - - } ); - - pending.push( accessor ); - - } - - assignExtrasToUserData( geometry, primitiveDef ); - - computeBounds( geometry, primitiveDef, parser ); - - return Promise.all( pending ).then( function () { - - return primitiveDef.targets !== undefined - ? addMorphTargets( geometry, primitiveDef.targets, parser ) - : geometry; - - } ); - - } - - /** - * @param {BufferGeometry} geometry - * @param {Number} drawMode - * @return {BufferGeometry} - */ - function toTrianglesDrawMode( geometry, drawMode ) { - - var index = geometry.getIndex(); - - // generate index if not present - - if ( index === null ) { - - var indices = []; - - var position = geometry.getAttribute( 'position' ); - - if ( position !== undefined ) { - - for ( var i = 0; i < position.count; i ++ ) { - - indices.push( i ); - - } - - geometry.setIndex( indices ); - index = geometry.getIndex(); - - } else { - - console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); - return geometry; - - } - - } - - // - - var numberOfTriangles = index.count - 2; - var newIndices = []; - - if ( drawMode === TriangleFanDrawMode ) { - - // gl.TRIANGLE_FAN - - for ( var i = 1; i <= numberOfTriangles; i ++ ) { - - newIndices.push( index.getX( 0 ) ); - newIndices.push( index.getX( i ) ); - newIndices.push( index.getX( i + 1 ) ); - - } - - } else { - - // gl.TRIANGLE_STRIP - - for ( var i = 0; i < numberOfTriangles; i ++ ) { - - if ( i % 2 === 0 ) { - - newIndices.push( index.getX( i ) ); - newIndices.push( index.getX( i + 1 ) ); - newIndices.push( index.getX( i + 2 ) ); - - - } else { - - newIndices.push( index.getX( i + 2 ) ); - newIndices.push( index.getX( i + 1 ) ); - newIndices.push( index.getX( i ) ); - - } - - } - - } - - if ( ( newIndices.length / 3 ) !== numberOfTriangles ) { - - console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' ); - - } - - // build final geometry - - var newGeometry = geometry.clone(); - newGeometry.setIndex( newIndices ); - - return newGeometry; - } /** @@ -53720,11 +54733,11 @@ var GLTFLoader = ( function () { * @param {Array} primitives * @return {Promise>} */ - GLTFParser.prototype.loadGeometries = function ( primitives ) { + loadGeometries( primitives ) { - var parser = this; - var extensions = this.extensions; - var cache = this.primitiveCache; + const parser = this; + const extensions = this.extensions; + const cache = this.primitiveCache; function createDracoPrimitive( primitive ) { @@ -53738,15 +54751,15 @@ var GLTFLoader = ( function () { } - var pending = []; + const pending = []; - for ( var i = 0, il = primitives.length; i < il; i ++ ) { + for ( let i = 0, il = primitives.length; i < il; i ++ ) { - var primitive = primitives[ i ]; - var cacheKey = createPrimitiveKey( primitive ); + const primitive = primitives[ i ]; + const cacheKey = createPrimitiveKey( primitive ); // See if we've already created this geometry - var cached = cache[ cacheKey ]; + const cached = cache[ cacheKey ]; if ( cached ) { @@ -53755,7 +54768,7 @@ var GLTFLoader = ( function () { } else { - var geometryPromise; + let geometryPromise; if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) { @@ -53780,27 +54793,27 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex * @return {Promise} */ - GLTFParser.prototype.loadMesh = function ( meshIndex ) { + loadMesh( meshIndex ) { - var parser = this; - var json = this.json; - var extensions = this.extensions; + const parser = this; + const json = this.json; + const extensions = this.extensions; - var meshDef = json.meshes[ meshIndex ]; - var primitives = meshDef.primitives; + const meshDef = json.meshes[ meshIndex ]; + const primitives = meshDef.primitives; - var pending = []; + const pending = []; - for ( var i = 0, il = primitives.length; i < il; i ++ ) { + for ( let i = 0, il = primitives.length; i < il; i ++ ) { - var material = primitives[ i ].material === undefined + const material = primitives[ i ].material === undefined ? createDefaultMaterial( this.cache ) : this.getDependency( 'material', primitives[ i ].material ); @@ -53812,26 +54825,26 @@ var GLTFLoader = ( function () { return Promise.all( pending ).then( function ( results ) { - var materials = results.slice( 0, results.length - 1 ); - var geometries = results[ results.length - 1 ]; + const materials = results.slice( 0, results.length - 1 ); + const geometries = results[ results.length - 1 ]; - var meshes = []; + const meshes = []; - for ( var i = 0, il = geometries.length; i < il; i ++ ) { + for ( let i = 0, il = geometries.length; i < il; i ++ ) { - var geometry = geometries[ i ]; - var primitive = primitives[ i ]; + const geometry = geometries[ i ]; + const primitive = primitives[ i ]; // 1. create Mesh - var mesh; + let mesh; - var material = materials[ i ]; + const material = materials[ i ]; if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || - primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || - primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || - primitive.mode === undefined ) { + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || + primitive.mode === undefined ) { // .isSkinnedMesh isn't in glTF spec. See ._markDefs() mesh = meshDef.isSkinnedMesh === true @@ -53896,15 +54909,26 @@ var GLTFLoader = ( function () { } + for ( let i = 0, il = meshes.length; i < il; i ++ ) { + + parser.associations.set( meshes[ i ], { + meshes: meshIndex, + primitives: i + } ); + + } + if ( meshes.length === 1 ) { return meshes[ 0 ]; } - var group = new Group(); + const group = new Group(); - for ( var i = 0, il = meshes.length; i < il; i ++ ) { + parser.associations.set( group, { meshes: meshIndex } ); + + for ( let i = 0, il = meshes.length; i < il; i ++ ) { group.add( meshes[ i ] ); @@ -53914,18 +54938,18 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @param {number} cameraIndex * @return {Promise} */ - GLTFParser.prototype.loadCamera = function ( cameraIndex ) { + loadCamera( cameraIndex ) { - var camera; - var cameraDef = this.json.cameras[ cameraIndex ]; - var params = cameraDef[ cameraDef.type ]; + let camera; + const cameraDef = this.json.cameras[ cameraIndex ]; + const params = cameraDef[ cameraDef.type ]; if ( ! params ) { @@ -53950,18 +54974,18 @@ var GLTFLoader = ( function () { return Promise.resolve( camera ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise} */ - GLTFParser.prototype.loadSkin = function ( skinIndex ) { + loadSkin( skinIndex ) { - var skinDef = this.json.skins[ skinIndex ]; + const skinDef = this.json.skins[ skinIndex ]; - var skinEntry = { joints: skinDef.joints }; + const skinEntry = { joints: skinDef.joints }; if ( skinDef.inverseBindMatrices === undefined ) { @@ -53977,33 +55001,33 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise} */ - GLTFParser.prototype.loadAnimation = function ( animationIndex ) { + loadAnimation( animationIndex ) { - var json = this.json; + const json = this.json; - var animationDef = json.animations[ animationIndex ]; + const animationDef = json.animations[ animationIndex ]; - var pendingNodes = []; - var pendingInputAccessors = []; - var pendingOutputAccessors = []; - var pendingSamplers = []; - var pendingTargets = []; + const pendingNodes = []; + const pendingInputAccessors = []; + const pendingOutputAccessors = []; + const pendingSamplers = []; + const pendingTargets = []; - for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) { + for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) { - var channel = animationDef.channels[ i ]; - var sampler = animationDef.samplers[ channel.sampler ]; - var target = channel.target; - var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated. - var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input; - var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output; + const channel = animationDef.channels[ i ]; + const sampler = animationDef.samplers[ channel.sampler ]; + const target = channel.target; + const name = target.node; + const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input; + const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output; pendingNodes.push( this.getDependency( 'node', name ) ); pendingInputAccessors.push( this.getDependency( 'accessor', input ) ); @@ -54023,28 +55047,27 @@ var GLTFLoader = ( function () { ] ).then( function ( dependencies ) { - var nodes = dependencies[ 0 ]; - var inputAccessors = dependencies[ 1 ]; - var outputAccessors = dependencies[ 2 ]; - var samplers = dependencies[ 3 ]; - var targets = dependencies[ 4 ]; + const nodes = dependencies[ 0 ]; + const inputAccessors = dependencies[ 1 ]; + const outputAccessors = dependencies[ 2 ]; + const samplers = dependencies[ 3 ]; + const targets = dependencies[ 4 ]; - var tracks = []; + const tracks = []; - for ( var i = 0, il = nodes.length; i < il; i ++ ) { + for ( let i = 0, il = nodes.length; i < il; i ++ ) { - var node = nodes[ i ]; - var inputAccessor = inputAccessors[ i ]; - var outputAccessor = outputAccessors[ i ]; - var sampler = samplers[ i ]; - var target = targets[ i ]; + const node = nodes[ i ]; + const inputAccessor = inputAccessors[ i ]; + const outputAccessor = outputAccessors[ i ]; + const sampler = samplers[ i ]; + const target = targets[ i ]; if ( node === undefined ) continue; node.updateMatrix(); - node.matrixAutoUpdate = true; - var TypedKeyframeTrack; + let TypedKeyframeTrack; switch ( PATH_PROPERTIES[ target.path ] ) { @@ -54067,18 +55090,17 @@ var GLTFLoader = ( function () { } - var targetName = node.name ? node.name : node.uuid; + const targetName = node.name ? node.name : node.uuid; - var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear; + const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear; - var targetNames = []; + const targetNames = []; if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) { - // Node may be a Group (glTF mesh with several primitives) or a Mesh. node.traverse( function ( object ) { - if ( object.isMesh === true && object.morphTargetInfluences ) { + if ( object.morphTargetInfluences ) { targetNames.push( object.name ? object.name : object.uuid ); @@ -54092,37 +55114,14 @@ var GLTFLoader = ( function () { } - var outputArray = outputAccessor.array; + let outputArray = outputAccessor.array; if ( outputAccessor.normalized ) { - var scale; - - if ( outputArray.constructor === Int8Array ) { - - scale = 1 / 127; - - } else if ( outputArray.constructor === Uint8Array ) { + const scale = getNormalizedComponentScale( outputArray.constructor ); + const scaled = new Float32Array( outputArray.length ); - scale = 1 / 255; - - } else if ( outputArray.constructor == Int16Array ) { - - scale = 1 / 32767; - - } else if ( outputArray.constructor === Uint16Array ) { - - scale = 1 / 65535; - - } else { - - throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' ); - - } - - var scaled = new Float32Array( outputArray.length ); - - for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) { + for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) { scaled[ j ] = outputArray[ j ] * scale; @@ -54132,9 +55131,9 @@ var GLTFLoader = ( function () { } - for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) { + for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) { - var track = new TypedKeyframeTrack( + const track = new TypedKeyframeTrack( targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ], inputAccessor.array, outputArray, @@ -54150,7 +55149,9 @@ var GLTFLoader = ( function () { // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize() // must be divided by three to get the interpolant's sampleSize argument. - return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result ); + const interpolantType = ( this instanceof QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; + + return new interpolantType( this.times, this.values, this.getValueSize() / 3, result ); }; @@ -54165,60 +55166,78 @@ var GLTFLoader = ( function () { } - var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex; + const name = animationDef.name ? animationDef.name : 'animation_' + animationIndex; return new AnimationClip( name, undefined, tracks ); } ); - }; + } - /** - * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy - * @param {number} nodeIndex - * @return {Promise} - */ - GLTFParser.prototype.loadNode = function ( nodeIndex ) { + createNodeMesh( nodeIndex ) { - var json = this.json; - var extensions = this.extensions; - var parser = this; + const json = this.json; + const parser = this; + const nodeDef = json.nodes[ nodeIndex ]; - var nodeDef = json.nodes[ nodeIndex ]; + if ( nodeDef.mesh === undefined ) return null; - // reserve node's name before its dependencies, so the root has the intended name. - var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : ''; + return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) { - return ( function () { + const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh ); - var pending = []; + // if weights are provided on the node, override weights on the mesh. + if ( nodeDef.weights !== undefined ) { - if ( nodeDef.mesh !== undefined ) { + node.traverse( function ( o ) { - pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) { + if ( ! o.isMesh ) return; - var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh ); + for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) { - // if weights are provided on the node, override weights on the mesh. - if ( nodeDef.weights !== undefined ) { + o.morphTargetInfluences[ i ] = nodeDef.weights[ i ]; - node.traverse( function ( o ) { + } - if ( ! o.isMesh ) return; + } ); - for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) { + } - o.morphTargetInfluences[ i ] = nodeDef.weights[ i ]; + return node; - } + } ); - } ); + } - } + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy + * @param {number} nodeIndex + * @return {Promise} + */ + loadNode( nodeIndex ) { - return node; + const json = this.json; + const extensions = this.extensions; + const parser = this; - } ) ); + const nodeDef = json.nodes[ nodeIndex ]; + + // reserve node's name before its dependencies, so the root has the intended name. + const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : ''; + + return ( function () { + + const pending = []; + + const meshPromise = parser._invokeOne( function ( ext ) { + + return ext.createNodeMesh && ext.createNodeMesh( nodeIndex ); + + } ); + + if ( meshPromise ) { + + pending.push( meshPromise ); } @@ -54246,7 +55265,7 @@ var GLTFLoader = ( function () { }() ).then( function ( objects ) { - var node; + let node; // .isBone isn't in glTF spec. See ._markDefs if ( nodeDef.isBone === true ) { @@ -54269,7 +55288,7 @@ var GLTFLoader = ( function () { if ( node !== objects[ 0 ] ) { - for ( var i = 0, il = objects.length; i < il; i ++ ) { + for ( let i = 0, il = objects.length; i < il; i ++ ) { node.add( objects[ i ] ); @@ -54290,7 +55309,7 @@ var GLTFLoader = ( function () { if ( nodeDef.matrix !== undefined ) { - var matrix = new Matrix4(); + const matrix = new Matrix4(); matrix.fromArray( nodeDef.matrix ); node.applyMatrix4( matrix ); @@ -54316,158 +55335,459 @@ var GLTFLoader = ( function () { } - parser.associations.set( node, { type: 'nodes', index: nodeIndex } ); + if ( ! parser.associations.has( node ) ) { + + parser.associations.set( node, {} ); + + } + + parser.associations.get( node ).nodes = nodeIndex; return node; } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex * @return {Promise} */ - GLTFParser.prototype.loadScene = function () { + loadScene( sceneIndex ) { + + const json = this.json; + const extensions = this.extensions; + const sceneDef = this.json.scenes[ sceneIndex ]; + const parser = this; - // scene node hierachy builder + // Loader returns Group, not Scene. + // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172 + const scene = new Group(); + if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name ); - function buildNodeHierachy( nodeId, parentObject, json, parser ) { + assignExtrasToUserData( scene, sceneDef ); - var nodeDef = json.nodes[ nodeId ]; + if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef ); - return parser.getDependency( 'node', nodeId ).then( function ( node ) { + const nodeIds = sceneDef.nodes || []; - if ( nodeDef.skin === undefined ) return node; + const pending = []; - // build skeleton here as well + for ( let i = 0, il = nodeIds.length; i < il; i ++ ) { - var skinEntry; + pending.push( buildNodeHierarchy( nodeIds[ i ], scene, json, parser ) ); + + } + + return Promise.all( pending ).then( function () { - return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) { + // Removes dangling associations, associations that reference a node that + // didn't make it into the scene. + const reduceAssociations = ( node ) => { - skinEntry = skin; + const reducedAssociations = new Map(); - var pendingJoints = []; + for ( const [ key, value ] of parser.associations ) { - for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) { + if ( key instanceof Material || key instanceof Texture ) { - pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) ); + reducedAssociations.set( key, value ); } - return Promise.all( pendingJoints ); + } - } ).then( function ( jointNodes ) { + node.traverse( ( node ) => { - node.traverse( function ( mesh ) { + const mappings = parser.associations.get( node ); - if ( ! mesh.isMesh ) return; + if ( mappings != null ) { - var bones = []; - var boneInverses = []; + reducedAssociations.set( node, mappings ); - for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) { + } - var jointNode = jointNodes[ j ]; + } ); - if ( jointNode ) { + return reducedAssociations; - bones.push( jointNode ); + }; - var mat = new Matrix4(); + parser.associations = reduceAssociations( scene ); - if ( skinEntry.inverseBindMatrices !== undefined ) { + return scene; - mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 ); + } ); - } + } - boneInverses.push( mat ); +} - } else { +function buildNodeHierarchy( nodeId, parentObject, json, parser ) { - console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] ); + const nodeDef = json.nodes[ nodeId ]; - } + return parser.getDependency( 'node', nodeId ).then( function ( node ) { - } + if ( nodeDef.skin === undefined ) return node; - mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld ); + // build skeleton here as well - } ); + let skinEntry; - return node; + return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) { - } ); + skinEntry = skin; + + const pendingJoints = []; + + for ( let i = 0, il = skinEntry.joints.length; i < il; i ++ ) { + + pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) ); + + } + + return Promise.all( pendingJoints ); + + } ).then( function ( jointNodes ) { + + node.traverse( function ( mesh ) { + + if ( ! mesh.isMesh ) return; + + const bones = []; + const boneInverses = []; + + for ( let j = 0, jl = jointNodes.length; j < jl; j ++ ) { - } ).then( function ( node ) { + const jointNode = jointNodes[ j ]; - // build node hierachy + if ( jointNode ) { - parentObject.add( node ); + bones.push( jointNode ); - var pending = []; + const mat = new Matrix4(); - if ( nodeDef.children ) { + if ( skinEntry.inverseBindMatrices !== undefined ) { - var children = nodeDef.children; + mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 ); - for ( var i = 0, il = children.length; i < il; i ++ ) { + } + + boneInverses.push( mat ); - var child = children[ i ]; - pending.push( buildNodeHierachy( child, node, json, parser ) ); + } else { + + console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] ); } } - return Promise.all( pending ); + mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld ); } ); + return node; + + } ); + + } ).then( function ( node ) { + + // build node hierachy + + parentObject.add( node ); + + const pending = []; + + if ( nodeDef.children ) { + + const children = nodeDef.children; + + for ( let i = 0, il = children.length; i < il; i ++ ) { + + const child = children[ i ]; + pending.push( buildNodeHierarchy( child, node, json, parser ) ); + + } + + } + + return Promise.all( pending ); + + } ); + +} + +/** + * @param {BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + */ +function computeBounds( geometry, primitiveDef, parser ) { + + const attributes = primitiveDef.attributes; + + const box = new Box3(); + + if ( attributes.POSITION !== undefined ) { + + const accessor = parser.json.accessors[ attributes.POSITION ]; + + const min = accessor.min; + const max = accessor.max; + + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. + + if ( min !== undefined && max !== undefined ) { + + box.set( + new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ), + new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) + ); + + if ( accessor.normalized ) { + + const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] ); + box.min.multiplyScalar( boxScale ); + box.max.multiplyScalar( boxScale ); + + } + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + return; + } - return function loadScene( sceneIndex ) { + } else { + + return; + + } + + const targets = primitiveDef.targets; + + if ( targets !== undefined ) { + + const maxDisplacement = new Vector3(); + const vector = new Vector3(); - var json = this.json; - var extensions = this.extensions; - var sceneDef = this.json.scenes[ sceneIndex ]; - var parser = this; + for ( let i = 0, il = targets.length; i < il; i ++ ) { - // Loader returns Group, not Scene. - // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172 - var scene = new Group(); - if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name ); + const target = targets[ i ]; - assignExtrasToUserData( scene, sceneDef ); + if ( target.POSITION !== undefined ) { - if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef ); + const accessor = parser.json.accessors[ target.POSITION ]; + const min = accessor.min; + const max = accessor.max; - var nodeIds = sceneDef.nodes || []; + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. - var pending = []; + if ( min !== undefined && max !== undefined ) { - for ( var i = 0, il = nodeIds.length; i < il; i ++ ) { + // we need to get max of absolute components because target weight is [-1,1] + vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) ); + vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) ); + vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) ); - pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) ); + + if ( accessor.normalized ) { + + const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] ); + vector.multiplyScalar( boxScale ); + + } + + // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative + // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets + // are used to implement key-frame animations and as such only two are active at a time - this results in very large + // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size. + maxDisplacement.max( vector ); + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + } } - return Promise.all( pending ).then( function () { + } - return scene; + // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets. + box.expandByVector( maxDisplacement ); + + } + + geometry.boundingBox = box; + + const sphere = new Sphere(); + + box.getCenter( sphere.center ); + sphere.radius = box.min.distanceTo( box.max ) / 2; + + geometry.boundingSphere = sphere; + +} + +/** + * @param {BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + * @return {Promise} + */ +function addPrimitiveAttributes( geometry, primitiveDef, parser ) { + + const attributes = primitiveDef.attributes; + + const pending = []; + + function assignAttributeAccessor( accessorIndex, attributeName ) { + + return parser.getDependency( 'accessor', accessorIndex ) + .then( function ( accessor ) { + + geometry.setAttribute( attributeName, accessor ); } ); - }; + } + + for ( const gltfAttributeName in attributes ) { + + const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); + + // Skip attributes already provided by e.g. Draco extension. + if ( threeAttributeName in geometry.attributes ) continue; + + pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) ); + + } + + if ( primitiveDef.indices !== undefined && ! geometry.index ) { + + const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) { + + geometry.setIndex( accessor ); + + } ); + + pending.push( accessor ); + + } + + assignExtrasToUserData( geometry, primitiveDef ); + + computeBounds( geometry, primitiveDef, parser ); - }(); + return Promise.all( pending ).then( function () { - return GLTFLoader; + return primitiveDef.targets !== undefined + ? addMorphTargets( geometry, primitiveDef.targets, parser ) + : geometry; -} )(); + } ); + +} + +/** + * @param {BufferGeometry} geometry + * @param {Number} drawMode + * @return {BufferGeometry} + */ +function toTrianglesDrawMode( geometry, drawMode ) { + + let index = geometry.getIndex(); + + // generate index if not present + + if ( index === null ) { + + const indices = []; + + const position = geometry.getAttribute( 'position' ); + + if ( position !== undefined ) { + + for ( let i = 0; i < position.count; i ++ ) { + + indices.push( i ); + + } + + geometry.setIndex( indices ); + index = geometry.getIndex(); + + } else { + + console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); + return geometry; + + } + + } + + // + + const numberOfTriangles = index.count - 2; + const newIndices = []; + + if ( drawMode === TriangleFanDrawMode ) { + + // gl.TRIANGLE_FAN + + for ( let i = 1; i <= numberOfTriangles; i ++ ) { + + newIndices.push( index.getX( 0 ) ); + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + + } + + } else { + + // gl.TRIANGLE_STRIP + + for ( let i = 0; i < numberOfTriangles; i ++ ) { + + if ( i % 2 === 0 ) { + + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i + 2 ) ); + + + } else { + + newIndices.push( index.getX( i + 2 ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i ) ); + + } + + } + + } + + if ( ( newIndices.length / 3 ) !== numberOfTriangles ) { + + console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' ); + + } + + // build final geometry + + const newGeometry = geometry.clone(); + newGeometry.setIndex( newIndices ); + + return newGeometry; + +} class ThreeJSWrapper { constructor(canvas) { diff --git a/build/three-js-wrapper.min.js b/build/three-js-wrapper.min.js index b0060a4..79fcdc1 100644 --- a/build/three-js-wrapper.min.js +++ b/build/three-js-wrapper.min.js @@ -1,3 +1,8 @@ -'use strict';Object.defineProperty(exports,'__esModule',{value:true});const REVISION="126",MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},CullFaceNone=0,CullFaceBack=1,CullFaceFront=2,CullFaceFrontBack=3,BasicShadowMap=0,PCFShadowMap=1,PCFSoftShadowMap=2,VSMShadowMap=3,FrontSide=0,BackSide=1,DoubleSide=2,FlatShading=1,SmoothShading=2,NoBlending=0,NormalBlending=1,AdditiveBlending=2,SubtractiveBlending=3,MultiplyBlending=4,CustomBlending=5,AddEquation=100,SubtractEquation=101,ReverseSubtractEquation=102,MinEquation=103,MaxEquation=104,ZeroFactor=200,OneFactor=201,SrcColorFactor=202,OneMinusSrcColorFactor=203,SrcAlphaFactor=204,OneMinusSrcAlphaFactor=205,DstAlphaFactor=206,OneMinusDstAlphaFactor=207,DstColorFactor=208,OneMinusDstColorFactor=209,SrcAlphaSaturateFactor=210,NeverDepth=0,AlwaysDepth=1,LessDepth=2,LessEqualDepth=3,EqualDepth=4,GreaterEqualDepth=5,GreaterDepth=6,NotEqualDepth=7,MultiplyOperation=0,MixOperation=1,AddOperation=2,NoToneMapping=0,LinearToneMapping=1,ReinhardToneMapping=2,CineonToneMapping=3,ACESFilmicToneMapping=4,CustomToneMapping=5,UVMapping=300,CubeReflectionMapping=301,CubeRefractionMapping=302,EquirectangularReflectionMapping=303,EquirectangularRefractionMapping=304,CubeUVReflectionMapping=306,CubeUVRefractionMapping=307,RepeatWrapping=1e3,ClampToEdgeWrapping=1001,MirroredRepeatWrapping=1002,NearestFilter=1003,NearestMipmapNearestFilter=1004,NearestMipMapNearestFilter=1004,NearestMipmapLinearFilter=1005,NearestMipMapLinearFilter=1005,LinearFilter=1006,LinearMipmapNearestFilter=1007,LinearMipMapNearestFilter=1007,LinearMipmapLinearFilter=1008,LinearMipMapLinearFilter=1008,UnsignedByteType=1009,ByteType=1010,ShortType=1011,UnsignedShortType=1012,IntType=1013,UnsignedIntType=1014,FloatType=1015,HalfFloatType=1016,UnsignedShort4444Type=1017,UnsignedShort5551Type=1018,UnsignedShort565Type=1019,UnsignedInt248Type=1020,AlphaFormat=1021,RGBFormat=1022,RGBAFormat=1023,LuminanceFormat=1024,LuminanceAlphaFormat=1025,RGBEFormat=1023,DepthFormat=1026,DepthStencilFormat=1027,RedFormat=1028,RedIntegerFormat=1029,RGFormat=1030,RGIntegerFormat=1031,RGBIntegerFormat=1032,RGBAIntegerFormat=1033,RGB_S3TC_DXT1_Format=33776,RGBA_S3TC_DXT1_Format=33777,RGBA_S3TC_DXT3_Format=33778,RGBA_S3TC_DXT5_Format=33779,RGB_PVRTC_4BPPV1_Format=35840,RGB_PVRTC_2BPPV1_Format=35841,RGBA_PVRTC_4BPPV1_Format=35842,RGBA_PVRTC_2BPPV1_Format=35843,RGB_ETC1_Format=36196,RGB_ETC2_Format=37492,RGBA_ETC2_EAC_Format=37496,RGBA_ASTC_4x4_Format=37808,RGBA_ASTC_5x4_Format=37809,RGBA_ASTC_5x5_Format=37810,RGBA_ASTC_6x5_Format=37811,RGBA_ASTC_6x6_Format=37812,RGBA_ASTC_8x5_Format=37813,RGBA_ASTC_8x6_Format=37814,RGBA_ASTC_8x8_Format=37815,RGBA_ASTC_10x5_Format=37816,RGBA_ASTC_10x6_Format=37817,RGBA_ASTC_10x8_Format=37818,RGBA_ASTC_10x10_Format=37819,RGBA_ASTC_12x10_Format=37820,RGBA_ASTC_12x12_Format=37821,RGBA_BPTC_Format=36492,SRGB8_ALPHA8_ASTC_4x4_Format=37840,SRGB8_ALPHA8_ASTC_5x4_Format=37841,SRGB8_ALPHA8_ASTC_5x5_Format=37842,SRGB8_ALPHA8_ASTC_6x5_Format=37843,SRGB8_ALPHA8_ASTC_6x6_Format=37844,SRGB8_ALPHA8_ASTC_8x5_Format=37845,SRGB8_ALPHA8_ASTC_8x6_Format=37846,SRGB8_ALPHA8_ASTC_8x8_Format=37847,SRGB8_ALPHA8_ASTC_10x5_Format=37848,SRGB8_ALPHA8_ASTC_10x6_Format=37849,SRGB8_ALPHA8_ASTC_10x8_Format=37850,SRGB8_ALPHA8_ASTC_10x10_Format=37851,SRGB8_ALPHA8_ASTC_12x10_Format=37852,SRGB8_ALPHA8_ASTC_12x12_Format=37853,LoopOnce=2200,LoopRepeat=2201,LoopPingPong=2202,InterpolateDiscrete=2300,InterpolateLinear=2301,InterpolateSmooth=2302,ZeroCurvatureEnding=2400,ZeroSlopeEnding=2401,WrapAroundEnding=2402,NormalAnimationBlendMode=2500,AdditiveAnimationBlendMode=2501,TrianglesDrawMode=0,TriangleStripDrawMode=1,TriangleFanDrawMode=2,LinearEncoding=3e3,sRGBEncoding=3001,GammaEncoding=3007,RGBEEncoding=3002,LogLuvEncoding=3003,RGBM7Encoding=3004,RGBM16Encoding=3005,RGBDEncoding=3006,BasicDepthPacking=3200,RGBADepthPacking=3201,TangentSpaceNormalMap=0,ObjectSpaceNormalMap=1,ZeroStencilOp=0,KeepStencilOp=7680,ReplaceStencilOp=7681,IncrementStencilOp=7682,DecrementStencilOp=7683,IncrementWrapStencilOp=34055,DecrementWrapStencilOp=34056,InvertStencilOp=5386,NeverStencilFunc=512,LessStencilFunc=513,EqualStencilFunc=514,LessEqualStencilFunc=515,GreaterStencilFunc=516,NotEqualStencilFunc=517,GreaterEqualStencilFunc=518,AlwaysStencilFunc=519,StaticDrawUsage=35044,DynamicDrawUsage=35048,StreamDrawUsage=35040,StaticReadUsage=35045,DynamicReadUsage=35049,StreamReadUsage=35041,StaticCopyUsage=35046,DynamicCopyUsage=35050,StreamCopyUsage=35042,GLSL1="100",GLSL3="300 es";function EventDispatcher(){}Object.assign(EventDispatcher.prototype,{addEventListener:function(e,t){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t);},hasEventListener:function(e,t){if(void 0===this._listeners)return !1;const n=this._listeners;return void 0!==n[e]&&-1!==n[e].indexOf(t)},removeEventListener:function(e,t){if(void 0===this._listeners)return;const n=this._listeners[e];if(void 0!==n){const e=n.indexOf(t);-1!==e&&n.splice(e,1);}},dispatchEvent:function(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const n=t.slice(0);for(let t=0,r=n.length;t>8&255]+_lut[e>>16&255]+_lut[e>>24&255]+"-"+_lut[255&t]+_lut[t>>8&255]+"-"+_lut[t>>16&15|64]+_lut[t>>24&255]+"-"+_lut[63&n|128]+_lut[n>>8&255]+"-"+_lut[n>>16&255]+_lut[n>>24&255]+_lut[255&r]+_lut[r>>8&255]+_lut[r>>16&255]+_lut[r>>24&255]).toUpperCase()},clamp:function(e,t,n){return Math.max(t,Math.min(n,e))},euclideanModulo:function(e,t){return (e%t+t)%t},mapLinear:function(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)},lerp:function(e,t,n){return (1-n)*e+n*t},damp:function(e,t,n,r){return MathUtils.lerp(e,t,1-Math.exp(-n*r))},pingpong:function(e,t=1){return t-Math.abs(MathUtils.euclideanModulo(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){return void 0!==e&&(_seed=e%2147483647),_seed=16807*_seed%2147483647,(_seed-1)/2147483646},degToRad:function(e){return e*MathUtils.DEG2RAD},radToDeg:function(e){return e*MathUtils.RAD2DEG},isPowerOfTwo:function(e){return 0==(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,n,r,i){const a=Math.cos,o=Math.sin,s=a(n/2),l=o(n/2),c=a((t+r)/2),h=o((t+r)/2),u=a((t-r)/2),d=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case"XYX":e.set(s*h,l*u,l*d,s*c);break;case"YZY":e.set(l*d,s*h,l*u,s*c);break;case"ZXZ":e.set(l*u,l*d,s*h,s*c);break;case"XZX":e.set(s*h,l*m,l*p,s*c);break;case"YXY":e.set(l*p,s*h,l*m,s*c);break;case"ZYZ":e.set(l*m,l*p,s*h,s*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i);}}};class Vector2{constructor(e=0,t=0){this.x=e,this.y=t;}get width(){return this.x}set width(e){this.x=e;}get height(){return this.y}set height(e){this.y=e;}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e,t){return void 0!==t?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this)}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e,t){return void 0!==t?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this)}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){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(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t,n){return void 0!==n&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}}Vector2.prototype.isVector2=!0;class Matrix3{constructor(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.");}set(e,t,n,r,i,a,o,s,l){const c=this.elements;return c[0]=e,c[1]=r,c[2]=o,c[3]=t,c[4]=i,c[5]=s,c[6]=n,c[7]=a,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=r[0],f=r[3],g=r[6],v=r[1],_=r[4],y=r[7],x=r[2],b=r[5],M=r[8];return i[0]=a*m+o*v+s*x,i[3]=a*f+o*_+s*b,i[6]=a*g+o*y+s*M,i[1]=l*m+c*v+h*x,i[4]=l*f+c*_+h*b,i[7]=l*g+c*y+h*M,i[2]=u*m+d*v+p*x,i[5]=u*f+d*_+p*b,i[8]=u*g+d*y+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],l=e[7],c=e[8];return t*a*c-t*o*l-n*i*c+n*o*s+r*i*l-r*a*s}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],l=e[7],c=e[8],h=c*a-o*l,u=o*s-c*i,d=l*i-a*s,p=t*h+n*u+r*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=h*m,e[1]=(r*l-c*n)*m,e[2]=(o*n-r*a)*m,e[3]=u*m,e[4]=(c*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=d*m,e[7]=(n*s-l*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){const s=Math.cos(i),l=Math.sin(i);return this.set(n*s,n*l,-n*(s*a+l*o)+a+e,-r*l,r*s,-r*(-l*a+s*o)+o+t,0,0,1),this}scale(e,t){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=t,n[4]*=t,n[7]*=t,this}rotate(e){const t=Math.cos(e),n=Math.sin(e),r=this.elements,i=r[0],a=r[3],o=r[6],s=r[1],l=r[4],c=r[7];return r[0]=t*i+n*s,r[3]=t*a+n*l,r[6]=t*o+n*c,r[1]=-n*i+t*s,r[4]=-n*a+t*l,r[7]=-n*o+t*c,this}translate(e,t){const n=this.elements;return n[0]+=e*n[2],n[3]+=e*n[5],n[6]+=e*n[8],n[1]+=t*n[2],n[4]+=t*n[5],n[7]+=t*n[8],this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return !1;return !0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return (new this.constructor).fromArray(this.elements)}}let _canvas;Matrix3.prototype.isMatrix3=!0;const ImageUtils={getDataURL:function(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else {void 0===_canvas&&(_canvas=document.createElementNS("http://www.w3.org/1999/xhtml","canvas")),_canvas.width=e.width,_canvas.height=e.height;const n=_canvas.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=_canvas;}return t.width>2048||t.height>2048?t.toDataURL("image/jpeg",.6):t.toDataURL("image/png")}};let textureId=0;class Texture extends EventDispatcher{constructor(e=Texture.DEFAULT_IMAGE,t=Texture.DEFAULT_MAPPING,n=1001,r=1001,i=1006,a=1008,o=1023,s=1009,l=1,c=3e3){super(),Object.defineProperty(this,"id",{value:textureId++}),this.uuid=MathUtils.generateUUID(),this.name="",this.image=e,this.mipmaps=[],this.mapping=t,this.wrapS=n,this.wrapT=r,this.magFilter=i,this.minFilter=a,this.anisotropy=l,this.format=o,this.internalFormat=null,this.type=s,this.offset=new Vector2(0,0),this.repeat=new Vector2(1,1),this.center=new Vector2(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Matrix3,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=c,this.version=0,this.onUpdate=null;}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y);}clone(){return (new this.constructor).copy(this)}copy(e){return this.name=e.name,this.image=e.image,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.encoding=e.encoding,this}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const n={metadata:{version:4.5,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],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(void 0!==this.image){const r=this.image;if(void 0===r.uuid&&(r.uuid=MathUtils.generateUUID()),!t&&void 0===e.images[r.uuid]){let t;if(Array.isArray(r)){t=[];for(let e=0,n=r.length;e1)switch(this.wrapS){case 1e3:e.x=e.x-Math.floor(e.x);break;case 1001:e.x=e.x<0?0:1;break;case 1002:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);}if(e.y<0||e.y>1)switch(this.wrapT){case 1e3:e.y=e.y-Math.floor(e.y);break;case 1001:e.y=e.y<0?0:1;break;case 1002:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&this.version++;}}function serializeImage(e){return "undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?ImageUtils.getDataURL(e):e.data?{data:Array.prototype.slice.call(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}Texture.DEFAULT_IMAGE=void 0,Texture.DEFAULT_MAPPING=300,Texture.prototype.isTexture=!0;class Vector4{constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r;}get width(){return this.z}set width(e){this.z=e;}get height(){return this.w}set height(e){this.w=e;}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){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: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e,t){return void 0!==t?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e,t){return void 0!==t?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i;const a=e.elements,o=a[0],s=a[4],l=a[8],c=a[1],h=a[5],u=a[9],d=a[2],p=a[6],m=a[10];if(Math.abs(s-c)<.01&&Math.abs(l-d)<.01&&Math.abs(u-p)<.01){if(Math.abs(s+c)<.1&&Math.abs(l+d)<.1&&Math.abs(u+p)<.1&&Math.abs(o+h+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const e=(o+1)/2,a=(h+1)/2,f=(m+1)/2,g=(s+c)/4,v=(l+d)/4,_=(u+p)/4;return e>a&&e>f?e<.01?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=g/n,i=v/n):a>f?a<.01?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(a),n=g/r,i=_/r):f<.01?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(f),n=v/i,r=_/i),this.set(n,r,i,t),this}let f=Math.sqrt((p-u)*(p-u)+(l-d)*(l-d)+(c-s)*(c-s));return Math.abs(f)<.001&&(f=1),this.x=(p-u)/f,this.y=(l-d)/f,this.z=(c-s)/f,this.w=Math.acos((o+h+m-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){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.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t,n){return void 0!==n&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute()."),this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}}Vector4.prototype.isVector4=!0;class WebGLRenderTarget extends EventDispatcher{constructor(e,t,n){super(),this.width=e,this.height=t,this.depth=1,this.scissor=new Vector4(0,0,e,t),this.scissorTest=!1,this.viewport=new Vector4(0,0,e,t),n=n||{},this.texture=new Texture(void 0,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.encoding),this.texture.image={},this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=1,this.texture.generateMipmaps=void 0!==n.generateMipmaps&&n.generateMipmaps,this.texture.minFilter=void 0!==n.minFilter?n.minFilter:1006,this.depthBuffer=void 0===n.depthBuffer||n.depthBuffer,this.stencilBuffer=void 0!==n.stencilBuffer&&n.stencilBuffer,this.depthTexture=void 0!==n.depthTexture?n.depthTexture:null;}setTexture(e){e.image={width:this.width,height:this.height,depth:this.depth},this.texture=e;}setSize(e,t,n=1){this.width===e&&this.height===t&&this.depth===n||(this.width=e,this.height=t,this.depth=n,this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=n,this.dispose()),this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t);}clone(){return (new this.constructor).copy(this)}copy(e){return this.width=e.width,this.height=e.height,this.depth=e.depth,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.depthTexture=e.depthTexture,this}dispose(){this.dispatchEvent({type:"dispose"});}}WebGLRenderTarget.prototype.isWebGLRenderTarget=!0;class WebGLMultisampleRenderTarget extends WebGLRenderTarget{constructor(e,t,n){super(e,t,n),this.samples=4;}copy(e){return super.copy.call(this,e),this.samples=e.samples,this}}WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget=!0;class Quaternion{constructor(e=0,t=0,n=0,r=1){this._x=e,this._y=t,this._z=n,this._w=r;}static slerp(e,t,n,r){return n.copy(e).slerp(t,r)}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],l=n[r+1],c=n[r+2],h=n[r+3];const u=i[a+0],d=i[a+1],p=i[a+2],m=i[a+3];if(0===o)return e[t+0]=s,e[t+1]=l,e[t+2]=c,void(e[t+3]=h);if(1===o)return e[t+0]=u,e[t+1]=d,e[t+2]=p,void(e[t+3]=m);if(h!==m||s!==u||l!==d||c!==p){let e=1-o;const t=s*u+l*d+c*p+h*m,n=t>=0?1:-1,r=1-t*t;if(r>Number.EPSILON){const i=Math.sqrt(r),a=Math.atan2(i,t*n);e=Math.sin(e*a)/i,o=Math.sin(o*a)/i;}const i=o*n;if(s=s*e+u*i,l=l*e+d*i,c=c*e+p*i,h=h*e+m*i,e===1-o){const e=1/Math.sqrt(s*s+l*l+c*c+h*h);s*=e,l*=e,c*=e,h*=e;}}e[t]=s,e[t+1]=l,e[t+2]=c,e[t+3]=h;}static multiplyQuaternionsFlat(e,t,n,r,i,a){const o=n[r],s=n[r+1],l=n[r+2],c=n[r+3],h=i[a],u=i[a+1],d=i[a+2],p=i[a+3];return e[t]=o*p+c*h+s*d-l*u,e[t+1]=s*p+c*u+l*h-o*d,e[t+2]=l*p+c*d+o*u-s*h,e[t+3]=c*p-o*h-s*u-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback();}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback();}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback();}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback();}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t){if(!e||!e.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");const n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,l=o(n/2),c=o(r/2),h=o(i/2),u=s(n/2),d=s(r/2),p=s(i/2);switch(a){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a);}return !1!==t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],l=t[2],c=t[6],h=t[10],u=n+o+h;if(u>0){const e=.5/Math.sqrt(u+1);this._w=.25/e,this._x=(c-s)*e,this._y=(i-l)*e,this._z=(a-r)*e;}else if(n>o&&n>h){const e=2*Math.sqrt(1+n-o-h);this._w=(c-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+l)/e;}else if(o>h){const e=2*Math.sqrt(1+o-n-h);this._w=(i-l)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+c)/e;}else {const e=2*Math.sqrt(1+h-n-o);this._w=(a-r)/e,this._x=(i+l)/e,this._y=(s+c)/e,this._z=.25*e;}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-6?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(MathUtils.clamp(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e,t){return void 0!==t?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(e,t)):this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,l=t._z,c=t._w;return this._x=n*c+a*o+r*l-i*s,this._y=r*c+a*s+i*o-n*l,this._z=i*c+a*l+n*s-r*o,this._w=a*c-n*o-r*s-i*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,r=this._y,i=this._z,a=this._w;let o=a*e._w+n*e._x+r*e._y+i*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=r,this._z=i,this;const s=1-o*o;if(s<=Number.EPSILON){const e=1-t;return this._w=e*a+t*this._w,this._x=e*n+t*this._x,this._y=e*r+t*this._y,this._z=e*i+t*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(s),c=Math.atan2(l,o),h=Math.sin((1-t)*c)/l,u=Math.sin(t*c)/l;return this._w=a*h+this._w*u,this._x=n*h+this._x*u,this._y=r*h+this._y*u,this._z=i*h+this._z*u,this._onChangeCallback(),this}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}}Quaternion.prototype.isQuaternion=!0;class Vector3{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n;}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e,t){return void 0!==t?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this.z+=e.z,this)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e,t){return void 0!==t?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this.z-=e.z,this)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e,t){return void 0!==t?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(e,t)):(this.x*=e.x,this.y*=e.y,this.z*=e.z,this)}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return e&&e.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(_quaternion.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(_quaternion.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,l=s*t+a*r-o*n,c=s*n+o*t-i*r,h=s*r+i*n-a*t,u=-i*t-a*n-o*r;return this.x=l*s+u*-i+c*-o-h*-a,this.y=c*s+u*-a+h*-i-l*-o,this.z=h*s+u*-o+l*-a-c*-i,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){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(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e,t){return void 0!==t?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(e,t)):this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return _vector.copy(this).projectOnVector(e),this.sub(_vector)}reflect(e){return this.sub(_vector.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(MathUtils.clamp(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t,n){return void 0!==n&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}}Vector3.prototype.isVector3=!0;const _vector=new Vector3,_quaternion=new Quaternion;class Box3{constructor(e=new Vector3(1/0,1/0,1/0),t=new Vector3(-1/0,-1/0,-1/0)){this.min=e,this.max=t;}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){let t=1/0,n=1/0,r=1/0,i=-1/0,a=-1/0,o=-1/0;for(let s=0,l=e.length;si&&(i=l),c>a&&(a=c),h>o&&(o=h);}return this.min.set(t,n,r),this.max.set(i,a,o),this}setFromBufferAttribute(e){let t=1/0,n=1/0,r=1/0,i=-1/0,a=-1/0,o=-1/0;for(let s=0,l=e.count;si&&(i=l),c>a&&(a=c),h>o&&(o=h);}return this.min.set(t,n,r),this.max.set(i,a,o),this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return void 0===t&&(console.warn("THREE.Box3: .getParameter() target is now required"),t=new Vector3),t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return !(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,_vector$1),_vector$1.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return !1;this.getCenter(_center),_extents.subVectors(this.max,_center),_v0.subVectors(e.a,_center),_v1.subVectors(e.b,_center),_v2.subVectors(e.c,_center),_f0.subVectors(_v1,_v0),_f1.subVectors(_v2,_v1),_f2.subVectors(_v0,_v2);let t=[0,-_f0.z,_f0.y,0,-_f1.z,_f1.y,0,-_f2.z,_f2.y,_f0.z,0,-_f0.x,_f1.z,0,-_f1.x,_f2.z,0,-_f2.x,-_f0.y,_f0.x,0,-_f1.y,_f1.x,0,-_f2.y,_f2.x,0];return !!satForAxes(t,_v0,_v1,_v2,_extents)&&(t=[1,0,0,0,1,0,0,0,1],!!satForAxes(t,_v0,_v1,_v2,_extents)&&(_triangleNormal.crossVectors(_f0,_f1),t=[_triangleNormal.x,_triangleNormal.y,_triangleNormal.z],satForAxes(t,_v0,_v1,_v2,_extents)))}clampPoint(e,t){return void 0===t&&(console.warn("THREE.Box3: .clampPoint() target is now required"),t=new Vector3),t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return _vector$1.copy(e).clamp(this.min,this.max).sub(e).length()}getBoundingSphere(e){return void 0===e&&console.error("THREE.Box3: .getBoundingSphere() target is now required"),this.getCenter(e.center),e.radius=.5*this.getSize(_vector$1).length(),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(_points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),_points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),_points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),_points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),_points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),_points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),_points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),_points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(_points)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}Box3.prototype.isBox3=!0;const _points=[new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3],_vector$1=new Vector3,_box=new Box3,_v0=new Vector3,_v1=new Vector3,_v2=new Vector3,_f0=new Vector3,_f1=new Vector3,_f2=new Vector3,_center=new Vector3,_extents=new Vector3,_triangleNormal=new Vector3,_testAxis=new Vector3;function satForAxes(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){_testAxis.fromArray(e,a);const o=i.x*Math.abs(_testAxis.x)+i.y*Math.abs(_testAxis.y)+i.z*Math.abs(_testAxis.z),s=t.dot(_testAxis),l=n.dot(_testAxis),c=r.dot(_testAxis);if(Math.max(-Math.max(s,l,c),Math.min(s,l,c))>o)return !1}return !0}const _box$1=new Box3;class Sphere{constructor(e=new Vector3,t=-1){this.center=e,this.radius=t;}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):_box$1.setFromPoints(e).getCenter(n);let r=0;for(let t=0,i=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return void 0===e&&(console.warn("THREE.Sphere: .getBoundingBox() target is now required"),e=new Box3),this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return (new this.constructor).copy(this)}}const _vector$2=new Vector3,_segCenter=new Vector3,_segDir=new Vector3,_diff=new Vector3,_edge1=new Vector3,_edge2=new Vector3,_normal=new Vector3;class Ray{constructor(e=new Vector3,t=new Vector3(0,0,-1)){this.origin=e,this.direction=t;}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return void 0===t&&(console.warn("THREE.Ray: .at() target is now required"),t=new Vector3),t.copy(this.direction).multiplyScalar(e).add(this.origin)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,_vector$2)),this}closestPointToPoint(e,t){void 0===t&&(console.warn("THREE.Ray: .closestPointToPoint() target is now required"),t=new Vector3),t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.direction).multiplyScalar(n).add(this.origin)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=_vector$2.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(_vector$2.copy(this.direction).multiplyScalar(t).add(this.origin),_vector$2.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){_segCenter.copy(e).add(t).multiplyScalar(.5),_segDir.copy(t).sub(e).normalize(),_diff.copy(this.origin).sub(_segCenter);const i=.5*e.distanceTo(t),a=-this.direction.dot(_segDir),o=_diff.dot(this.direction),s=-_diff.dot(_segDir),l=_diff.lengthSq(),c=Math.abs(1-a*a);let h,u,d,p;if(c>0)if(h=a*s-o,u=a*o-s,p=i*c,h>=0)if(u>=-p)if(u<=p){const e=1/c;h*=e,u*=e,d=h*(h+a*u+2*o)+u*(a*h+u+2*s)+l;}else u=i,h=Math.max(0,-(a*u+o)),d=-h*h+u*(u+2*s)+l;else u=-i,h=Math.max(0,-(a*u+o)),d=-h*h+u*(u+2*s)+l;else u<=-p?(h=Math.max(0,-(-a*i+o)),u=h>0?-i:Math.min(Math.max(-i,-s),i),d=-h*h+u*(u+2*s)+l):u<=p?(h=0,u=Math.min(Math.max(-i,-s),i),d=u*(u+2*s)+l):(h=Math.max(0,-(a*i+o)),u=h>0?i:Math.min(Math.max(-i,-s),i),d=-h*h+u*(u+2*s)+l);else u=a>0?-i:i,h=Math.max(0,-(a*u+o)),d=-h*h+u*(u+2*s)+l;return n&&n.copy(this.direction).multiplyScalar(h).add(this.origin),r&&r.copy(_segDir).multiplyScalar(u).add(_segCenter),d}intersectSphere(e,t){_vector$2.subVectors(e.center,this.origin);const n=_vector$2.dot(this.direction),r=_vector$2.dot(_vector$2)-n*n,i=e.radius*e.radius;if(r>i)return null;const a=Math.sqrt(i-r),o=n-a,s=n+a;return o<0&&s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return !0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(e.min.x-u.x)*l,r=(e.max.x-u.x)*l):(n=(e.max.x-u.x)*l,r=(e.min.x-u.x)*l),c>=0?(i=(e.min.y-u.y)*c,a=(e.max.y-u.y)*c):(i=(e.max.y-u.y)*c,a=(e.min.y-u.y)*c),n>a||i>r?null:((i>n||n!=n)&&(n=i),(a=0?(o=(e.min.z-u.z)*h,s=(e.max.z-u.z)*h):(o=(e.max.z-u.z)*h,s=(e.min.z-u.z)*h),n>s||o>r?null:((o>n||n!=n)&&(n=o),(s=0?n:r,t)))}intersectsBox(e){return null!==this.intersectBox(e,_vector$2)}intersectTriangle(e,t,n,r,i){_edge1.subVectors(t,e),_edge2.subVectors(n,e),_normal.crossVectors(_edge1,_edge2);let a,o=this.direction.dot(_normal);if(o>0){if(r)return null;a=1;}else {if(!(o<0))return null;a=-1,o=-o;}_diff.subVectors(this.origin,e);const s=a*this.direction.dot(_edge2.crossVectors(_diff,_edge2));if(s<0)return null;const l=a*this.direction.dot(_edge1.cross(_diff));if(l<0)return null;if(s+l>o)return null;const c=-a*_diff.dot(_normal);return c<0?null:this.at(c/o,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return (new this.constructor).copy(this)}}class Matrix4{constructor(){this.elements=[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.");}set(e,t,n,r,i,a,o,s,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return (new Matrix4).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,r=1/_v1$1.setFromMatrixColumn(e,0).length(),i=1/_v1$1.setFromMatrixColumn(e,1).length(),a=1/_v1$1.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){e&&e.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");const t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),l=Math.sin(r),c=Math.cos(i),h=Math.sin(i);if("XYZ"===e.order){const e=a*c,n=a*h,r=o*c,i=o*h;t[0]=s*c,t[4]=-s*h,t[8]=l,t[1]=n+r*l,t[5]=e-i*l,t[9]=-o*s,t[2]=i-e*l,t[6]=r+n*l,t[10]=a*s;}else if("YXZ"===e.order){const e=s*c,n=s*h,r=l*c,i=l*h;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*l,t[1]=a*h,t[5]=a*c,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s;}else if("ZXY"===e.order){const e=s*c,n=s*h,r=l*c,i=l*h;t[0]=e-i*o,t[4]=-a*h,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*c,t[9]=i-e*o,t[2]=-a*l,t[6]=o,t[10]=a*s;}else if("ZYX"===e.order){const e=a*c,n=a*h,r=o*c,i=o*h;t[0]=s*c,t[4]=r*l-n,t[8]=e*l+i,t[1]=s*h,t[5]=i*l+e,t[9]=n*l-r,t[2]=-l,t[6]=o*s,t[10]=a*s;}else if("YZX"===e.order){const e=a*s,n=a*l,r=o*s,i=o*l;t[0]=s*c,t[4]=i-e*h,t[8]=r*h+n,t[1]=h,t[5]=a*c,t[9]=-o*c,t[2]=-l*c,t[6]=n*h+r,t[10]=e-i*h;}else if("XZY"===e.order){const e=a*s,n=a*l,r=o*s,i=o*l;t[0]=s*c,t[4]=-h,t[8]=l*c,t[1]=e*h+i,t[5]=a*c,t[9]=n*h-r,t[2]=r*h-n,t[6]=o*c,t[10]=i*h+e;}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(_zero,e,_one)}lookAt(e,t,n){const r=this.elements;return _z.subVectors(e,t),0===_z.lengthSq()&&(_z.z=1),_z.normalize(),_x.crossVectors(n,_z),0===_x.lengthSq()&&(1===Math.abs(n.z)?_z.x+=1e-4:_z.z+=1e-4,_z.normalize(),_x.crossVectors(n,_z)),_x.normalize(),_y.crossVectors(_z,_x),r[0]=_x.x,r[4]=_y.x,r[8]=_z.x,r[1]=_x.y,r[5]=_y.y,r[9]=_z.y,r[2]=_x.z,r[6]=_y.z,r[10]=_z.z,this}multiply(e,t){return void 0!==t?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(e,t)):this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],_=n[7],y=n[11],x=n[15],b=r[0],M=r[4],w=r[8],S=r[12],T=r[1],E=r[5],A=r[9],L=r[13],C=r[2],R=r[6],P=r[10],B=r[14],D=r[3],I=r[7],G=r[11],F=r[15];return i[0]=a*b+o*T+s*C+l*D,i[4]=a*M+o*E+s*R+l*I,i[8]=a*w+o*A+s*P+l*G,i[12]=a*S+o*L+s*B+l*F,i[1]=c*b+h*T+u*C+d*D,i[5]=c*M+h*E+u*R+d*I,i[9]=c*w+h*A+u*P+d*G,i[13]=c*S+h*L+u*B+d*F,i[2]=p*b+m*T+f*C+g*D,i[6]=p*M+m*E+f*R+g*I,i[10]=p*w+m*A+f*P+g*G,i[14]=p*S+m*L+f*B+g*F,i[3]=v*b+_*T+y*C+x*D,i[7]=v*M+_*E+y*R+x*I,i[11]=v*w+_*A+y*P+x*G,i[15]=v*S+_*L+y*B+x*F,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],l=e[13],c=e[2],h=e[6],u=e[10],d=e[14];return e[3]*(+i*s*h-r*l*h-i*o*u+n*l*u+r*o*d-n*s*d)+e[7]*(+t*s*d-t*l*u+i*a*u-r*a*d+r*l*c-i*s*c)+e[11]*(+t*l*h-t*o*d-i*a*h+n*a*d+i*o*c-n*l*c)+e[15]*(-r*o*c-t*s*h+t*o*u+r*a*h-n*a*u+n*s*c)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],l=e[7],c=e[8],h=e[9],u=e[10],d=e[11],p=e[12],m=e[13],f=e[14],g=e[15],v=h*f*l-m*u*l+m*s*d-o*f*d-h*s*g+o*u*g,_=p*u*l-c*f*l-p*s*d+a*f*d+c*s*g-a*u*g,y=c*m*l-p*h*l+p*o*d-a*m*d-c*o*g+a*h*g,x=p*h*s-c*m*s-p*o*u+a*m*u+c*o*f-a*h*f,b=t*v+n*_+r*y+i*x;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/b;return e[0]=v*M,e[1]=(m*u*i-h*f*i-m*r*d+n*f*d+h*r*g-n*u*g)*M,e[2]=(o*f*i-m*s*i+m*r*l-n*f*l-o*r*g+n*s*g)*M,e[3]=(h*s*i-o*u*i-h*r*l+n*u*l+o*r*d-n*s*d)*M,e[4]=_*M,e[5]=(c*f*i-p*u*i+p*r*d-t*f*d-c*r*g+t*u*g)*M,e[6]=(p*s*i-a*f*i-p*r*l+t*f*l+a*r*g-t*s*g)*M,e[7]=(a*u*i-c*s*i+c*r*l-t*u*l-a*r*d+t*s*d)*M,e[8]=y*M,e[9]=(p*h*i-c*m*i-p*n*d+t*m*d+c*n*g-t*h*g)*M,e[10]=(a*m*i-p*o*i+p*n*l-t*m*l-a*n*g+t*o*g)*M,e[11]=(c*o*i-a*h*i-c*n*l+t*h*l+a*n*d-t*o*d)*M,e[12]=x*M,e[13]=(c*m*r-p*h*r+p*n*u-t*m*u-c*n*f+t*h*f)*M,e[14]=(p*o*r-a*m*r-p*n*s+t*m*s+a*n*f-t*o*f)*M,e[15]=(a*h*r-c*o*r+c*n*s-t*h*s-a*n*u+t*o*u)*M,this}scale(e){const t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,l=i*a,c=i*o;return this.set(l*a+n,l*o-r*s,l*s+r*o,0,l*o+r*s,c*o+n,c*s-r*a,0,l*s-r*o,c*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n){return this.set(1,t,n,0,e,1,n,0,e,t,1,0,0,0,0,1),this}compose(e,t,n){const r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,l=i+i,c=a+a,h=o+o,u=i*l,d=i*c,p=i*h,m=a*c,f=a*h,g=o*h,v=s*l,_=s*c,y=s*h,x=n.x,b=n.y,M=n.z;return r[0]=(1-(m+g))*x,r[1]=(d+y)*x,r[2]=(p-_)*x,r[3]=0,r[4]=(d-y)*b,r[5]=(1-(u+g))*b,r[6]=(f+v)*b,r[7]=0,r[8]=(p+_)*M,r[9]=(f-v)*M,r[10]=(1-(u+m))*M,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){const r=this.elements;let i=_v1$1.set(r[0],r[1],r[2]).length();const a=_v1$1.set(r[4],r[5],r[6]).length(),o=_v1$1.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],_m1.copy(this);const s=1/i,l=1/a,c=1/o;return _m1.elements[0]*=s,_m1.elements[1]*=s,_m1.elements[2]*=s,_m1.elements[4]*=l,_m1.elements[5]*=l,_m1.elements[6]*=l,_m1.elements[8]*=c,_m1.elements[9]*=c,_m1.elements[10]*=c,t.setFromRotationMatrix(_m1),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a){void 0===a&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");const o=this.elements,s=2*i/(t-e),l=2*i/(n-r),c=(t+e)/(t-e),h=(n+r)/(n-r),u=-(a+i)/(a-i),d=-2*a*i/(a-i);return o[0]=s,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=l,o[9]=h,o[13]=0,o[2]=0,o[6]=0,o[10]=u,o[14]=d,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,n,r,i,a){const o=this.elements,s=1/(t-e),l=1/(n-r),c=1/(a-i),h=(t+e)*s,u=(n+r)*l,d=(a+i)*c;return o[0]=2*s,o[4]=0,o[8]=0,o[12]=-h,o[1]=0,o[5]=2*l,o[9]=0,o[13]=-u,o[2]=0,o[6]=0,o[10]=-2*c,o[14]=-d,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return !1;return !0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}Matrix4.prototype.isMatrix4=!0;const _v1$1=new Vector3,_m1=new Matrix4,_zero=new Vector3(0,0,0),_one=new Vector3(1,1,1),_x=new Vector3,_y=new Vector3,_z=new Vector3,_matrix=new Matrix4,_quaternion$1=new Quaternion;class Euler{constructor(e=0,t=0,n=0,r=Euler.DefaultOrder){this._x=e,this._y=t,this._z=n,this._order=r;}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback();}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback();}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback();}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback();}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._order=r||this._order,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t,n){const r=MathUtils.clamp,i=e.elements,a=i[0],o=i[4],s=i[8],l=i[1],c=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(t=t||this._order){case"XYZ":this._y=Math.asin(r(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-o,a)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-r(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(s,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,a),this._z=0);break;case"ZXY":this._x=Math.asin(r(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-r(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(r(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,a)):(this._x=0,this._y=Math.atan2(s,p));break;case"XZY":this._z=Math.asin(-r(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(s,a)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t);}return this._order=t,!1!==n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return _matrix.makeRotationFromQuaternion(e),this.setFromRotationMatrix(_matrix,t,n)}setFromVector3(e,t){return this.set(e.x,e.y,e.z,t||this._order)}reorder(e){return _quaternion$1.setFromEuler(this),this.setFromQuaternion(_quaternion$1,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}toVector3(e){return e?e.set(this._x,this._y,this._z):new Vector3(this._x,this._y,this._z)}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}}Euler.prototype.isEuler=!0,Euler.DefaultOrder="XYZ",Euler.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];class Layers{constructor(){this.mask=1;}set(e){this.mask=1<1){for(let e=0;e1){for(let e=0;e0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c);}return n.object=r,n;function a(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r);}return t}},clone:function(e){return (new this.constructor).copy(this,e)},copy:function(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t1?void 0:t.copy(n).multiplyScalar(i).add(e.start)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return void 0===e&&(console.warn("THREE.Plane: .coplanarPoint() target is now required"),e=new Vector3),e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||_normalMatrix.getNormalMatrix(e),r=this.coplanarPoint(_vector1).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return (new this.constructor).copy(this)}}Plane.prototype.isPlane=!0;const _v0$1=new Vector3,_v1$3=new Vector3,_v2$1=new Vector3,_v3=new Vector3,_vab=new Vector3,_vac=new Vector3,_vbc=new Vector3,_vap=new Vector3,_vbp=new Vector3,_vcp=new Vector3;class Triangle{constructor(e=new Vector3,t=new Vector3,n=new Vector3){this.a=e,this.b=t,this.c=n;}static getNormal(e,t,n,r){void 0===r&&(console.warn("THREE.Triangle: .getNormal() target is now required"),r=new Vector3),r.subVectors(n,t),_v0$1.subVectors(e,t),r.cross(_v0$1);const i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){_v0$1.subVectors(r,t),_v1$3.subVectors(n,t),_v2$1.subVectors(e,t);const a=_v0$1.dot(_v0$1),o=_v0$1.dot(_v1$3),s=_v0$1.dot(_v2$1),l=_v1$3.dot(_v1$3),c=_v1$3.dot(_v2$1),h=a*l-o*o;if(void 0===i&&(console.warn("THREE.Triangle: .getBarycoord() target is now required"),i=new Vector3),0===h)return i.set(-2,-1,-1);const u=1/h,d=(l*s-o*c)*u,p=(a*c-o*s)*u;return i.set(1-d-p,p,d)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,_v3),_v3.x>=0&&_v3.y>=0&&_v3.x+_v3.y<=1}static getUV(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,_v3),s.set(0,0),s.addScaledVector(i,_v3.x),s.addScaledVector(a,_v3.y),s.addScaledVector(o,_v3.z),s}static isFrontFacing(e,t,n,r){return _v0$1.subVectors(n,t),_v1$3.subVectors(e,t),_v0$1.cross(_v1$3).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}clone(){return (new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return _v0$1.subVectors(this.c,this.b),_v1$3.subVectors(this.a,this.b),.5*_v0$1.cross(_v1$3).length()}getMidpoint(e){return void 0===e&&(console.warn("THREE.Triangle: .getMidpoint() target is now required"),e=new Vector3),e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Triangle.getNormal(this.a,this.b,this.c,e)}getPlane(e){return void 0===e&&(console.warn("THREE.Triangle: .getPlane() target is now required"),e=new Plane),e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Triangle.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,n,r,i){return Triangle.getUV(e,this.a,this.b,this.c,t,n,r,i)}containsPoint(e){return Triangle.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Triangle.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){void 0===t&&(console.warn("THREE.Triangle: .closestPointToPoint() target is now required"),t=new Vector3);const n=this.a,r=this.b,i=this.c;let a,o;_vab.subVectors(r,n),_vac.subVectors(i,n),_vap.subVectors(e,n);const s=_vab.dot(_vap),l=_vac.dot(_vap);if(s<=0&&l<=0)return t.copy(n);_vbp.subVectors(e,r);const c=_vab.dot(_vbp),h=_vac.dot(_vbp);if(c>=0&&h<=c)return t.copy(r);const u=s*h-c*l;if(u<=0&&s>=0&&c<=0)return a=s/(s-c),t.copy(n).addScaledVector(_vab,a);_vcp.subVectors(e,i);const d=_vab.dot(_vcp),p=_vac.dot(_vcp);if(p>=0&&d<=p)return t.copy(i);const m=d*l-s*p;if(m<=0&&l>=0&&p<=0)return o=l/(l-p),t.copy(n).addScaledVector(_vac,o);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return _vbc.subVectors(i,r),o=(h-c)/(h-c+(d-p)),t.copy(r).addScaledVector(_vbc,o);const g=1/(f+m+u);return a=m*g,o=u*g,t.copy(n).addScaledVector(_vab,a).addScaledVector(_vac,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}let materialId=0;function Material(){Object.defineProperty(this,"id",{value:materialId++}),this.uuid=MathUtils.generateUUID(),this.name="",this.type="Material",this.fog=!0,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaTest=0,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0;}Material.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Material,isMaterial:!0,onBeforeCompile:function(){},customProgramCacheKey:function(){return this.onBeforeCompile.toString()},setValues:function(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){console.warn("THREE.Material: '"+t+"' parameter is undefined.");continue}if("shading"===t){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===n;continue}const r=this[t];void 0!==r?r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n:console.warn("THREE."+this.type+": '"+t+"' is not a property of this material.");}},toJSON:function(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function r(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r);}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),this.sheen&&this.sheen.isColor&&(n.sheen=this.sheen.getHex()),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,n.reflectivity=this.reflectivity,n.refractionRatio=this.refractionRatio,void 0!==this.combine&&(n.combine=this.combine),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity)),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.size&&(n.size=this.size),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=this.transparent),n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.stencilWrite=this.stencilWrite,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.morphTargets&&(n.morphTargets=!0),!0===this.morphNormals&&(n.morphNormals=!0),!0===this.skinning&&(n.skinning=!0),!0===this.flatShading&&(n.flatShading=this.flatShading),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),"{}"!==JSON.stringify(this.userData)&&(n.userData=this.userData),t){const t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i);}return n},clone:function(){return (new this.constructor).copy(this)},copy:function(e){this.name=e.name,this.fog=e.fog,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone();}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.premultipliedAlpha=e.premultipliedAlpha,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this},dispose:function(){this.dispatchEvent({type:"dispose"});}}),Object.defineProperty(Material.prototype,"needsUpdate",{set:function(e){!0===e&&this.version++;}});const _colorKeywords={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},_hslA={h:0,s:0,l:0},_hslB={h:0,s:0,l:0};function hue2rgb(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}function SRGBToLinear(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function LinearToSRGB(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class Color{constructor(e,t,n){return void 0===t&&void 0===n?this.set(e):this.setRGB(e,t,n)}set(e){return e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e),this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,this}setRGB(e,t,n){return this.r=e,this.g=t,this.b=n,this}setHSL(e,t,n){if(e=MathUtils.euclideanModulo(e,1),t=MathUtils.clamp(t,0,1),n=MathUtils.clamp(n,0,1),0===t)this.r=this.g=this.b=n;else {const r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=hue2rgb(i,r,e+1/3),this.g=hue2rgb(i,r,e),this.b=hue2rgb(i,r,e-1/3);}return this}setStyle(e){function t(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.");}let n;if(n=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(e)){let e;const r=n[1],i=n[2];switch(r){case"rgb":case"rgba":if(e=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(i))return this.r=Math.min(255,parseInt(e[1],10))/255,this.g=Math.min(255,parseInt(e[2],10))/255,this.b=Math.min(255,parseInt(e[3],10))/255,t(e[4]),this;if(e=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(i))return this.r=Math.min(100,parseInt(e[1],10))/100,this.g=Math.min(100,parseInt(e[2],10))/100,this.b=Math.min(100,parseInt(e[3],10))/100,t(e[4]),this;break;case"hsl":case"hsla":if(e=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(i)){const n=parseFloat(e[1])/360,r=parseInt(e[2],10)/100,i=parseInt(e[3],10)/100;return t(e[4]),this.setHSL(n,r,i)}}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const e=n[1],t=e.length;if(3===t)return this.r=parseInt(e.charAt(0)+e.charAt(0),16)/255,this.g=parseInt(e.charAt(1)+e.charAt(1),16)/255,this.b=parseInt(e.charAt(2)+e.charAt(2),16)/255,this;if(6===t)return this.r=parseInt(e.charAt(0)+e.charAt(1),16)/255,this.g=parseInt(e.charAt(2)+e.charAt(3),16)/255,this.b=parseInt(e.charAt(4)+e.charAt(5),16)/255,this}return e&&e.length>0?this.setColorName(e):this}setColorName(e){const t=_colorKeywords[e];return void 0!==t?this.setHex(t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyGammaToLinear(e,t=2){return this.r=Math.pow(e.r,t),this.g=Math.pow(e.g,t),this.b=Math.pow(e.b,t),this}copyLinearToGamma(e,t=2){const n=t>0?1/t:1;return this.r=Math.pow(e.r,n),this.g=Math.pow(e.g,n),this.b=Math.pow(e.b,n),this}convertGammaToLinear(e){return this.copyGammaToLinear(this,e),this}convertLinearToGamma(e){return this.copyLinearToGamma(this,e),this}copySRGBToLinear(e){return this.r=SRGBToLinear(e.r),this.g=SRGBToLinear(e.g),this.b=SRGBToLinear(e.b),this}copyLinearToSRGB(e){return this.r=LinearToSRGB(e.r),this.g=LinearToSRGB(e.g),this.b=LinearToSRGB(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0}getHexString(){return ("000000"+this.getHex().toString(16)).slice(-6)}getHSL(e){void 0===e&&(console.warn("THREE.Color: .getHSL() target is now required"),e={h:0,s:0,l:0});const t=this.r,n=this.g,r=this.b,i=Math.max(t,n,r),a=Math.min(t,n,r);let o,s;const l=(a+i)/2;if(a===i)o=0,s=0;else {const e=i-a;switch(s=l<=.5?e/(i+a):e/(2-i-a),i){case t:o=(n-r)/e+(nt&&(t=e[n]);return t}Object.defineProperty(BufferAttribute.prototype,"needsUpdate",{set:function(e){!0===e&&this.version++;}}),Object.assign(BufferAttribute.prototype,{isBufferAttribute:!0,onUploadCallback:function(){},setUsage:function(e){return this.usage=e,this},copy:function(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this},copyAt:function(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r65535?Uint32BufferAttribute:Uint16BufferAttribute)(e,1):this.index=e,this},getAttribute:function(e){return this.attributes[e]},setAttribute:function(e,t){return this.attributes[e]=t,this},deleteAttribute:function(e){return delete this.attributes[e],this},hasAttribute:function(e){return void 0!==this.attributes[e]},addGroup:function(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n});},clearGroups:function(){this.groups=[];},setDrawRange:function(e,t){this.drawRange.start=e,this.drawRange.count=t;},applyMatrix4:function(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const t=(new Matrix3).getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0;}const r=this.attributes.tangent;return void 0!==r&&(r.transformDirection(e),r.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this},rotateX:function(e){return _m1$2.makeRotationX(e),this.applyMatrix4(_m1$2),this},rotateY:function(e){return _m1$2.makeRotationY(e),this.applyMatrix4(_m1$2),this},rotateZ:function(e){return _m1$2.makeRotationZ(e),this.applyMatrix4(_m1$2),this},translate:function(e,t,n){return _m1$2.makeTranslation(e,t,n),this.applyMatrix4(_m1$2),this},scale:function(e,t,n){return _m1$2.makeScale(e,t,n),this.applyMatrix4(_m1$2),this},lookAt:function(e){return _obj.lookAt(e),_obj.updateMatrix(),this.applyMatrix4(_obj.matrix),this},center:function(){return this.computeBoundingBox(),this.boundingBox.getCenter(_offset).negate(),this.translate(_offset.x,_offset.y,_offset.z),this},setFromPoints:function(e){const t=[];for(let n=0,r=e.length;n0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const t in n){const r=n[t],i=r.toJSON(e.data);""!==r.name&&(i.name=r.name),e.data.attributes[t]=i;}const r={};let i=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t0&&(r[t]=a,i=!0);}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e},clone:function(){return (new BufferGeometry).copy(this)},copy:function(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone(t));const r=e.attributes;for(const e in r){const n=r[e];this.setAttribute(e,n.clone(t));}const i=e.morphAttributes;for(const e in i){const n=[],r=i[e];for(let e=0,i=r.length;en.far?null:{distance:c,point:_intersectionPointWorld.clone(),object:e}}function checkBufferGeometryIntersection(e,t,n,r,i,a,o,s,l,c,h,u){_vA.fromBufferAttribute(i,c),_vB.fromBufferAttribute(i,h),_vC.fromBufferAttribute(i,u);const d=e.morphTargetInfluences;if(t.morphTargets&&a&&d){_morphA.set(0,0,0),_morphB.set(0,0,0),_morphC.set(0,0,0);for(let e=0,t=a.length;e0){const e=t[n[0]];if(void 0!==e){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,n=e.length;t0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.");}},raycast:function(e,t){const n=this.geometry,r=this.material,i=this.matrixWorld;if(void 0===r)return;if(null===n.boundingSphere&&n.computeBoundingSphere(),_sphere.copy(n.boundingSphere),_sphere.applyMatrix4(i),!1===e.ray.intersectsSphere(_sphere))return;if(_inverseMatrix.copy(i).invert(),_ray.copy(e.ray).applyMatrix4(_inverseMatrix),null!==n.boundingBox&&!1===_ray.intersectsBox(n.boundingBox))return;let a;if(n.isBufferGeometry){const i=n.index,o=n.attributes.position,s=n.morphAttributes.position,l=n.morphTargetsRelative,c=n.attributes.uv,h=n.attributes.uv2,u=n.groups,d=n.drawRange;if(null!==i)if(Array.isArray(r))for(let n=0,p=u.length;n0?1:-1,c.push(A.x,A.y,A.z),h.push(s/f),h.push(1-a/g),T+=1;}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t},Camera.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Camera,isCamera:!0,copy:function(e,t){return Object3D.prototype.copy.call(this,e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this},getWorldDirection:function(e){void 0===e&&(console.warn("THREE.Camera: .getWorldDirection() target is now required"),e=new Vector3),this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(-t[8],-t[9],-t[10]).normalize()},updateMatrixWorld:function(e){Object3D.prototype.updateMatrixWorld.call(this,e),this.matrixWorldInverse.copy(this.matrixWorld).invert();},updateWorldMatrix:function(e,t){Object3D.prototype.updateWorldMatrix.call(this,e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert();},clone:function(){return (new this.constructor).copy(this)}}),PerspectiveCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:PerspectiveCamera,isPerspectiveCamera:!0,copy:function(e,t){return Camera.prototype.copy.call(this,e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this},setFocalLength:function(e){const t=.5*this.getFilmHeight()/e;this.fov=2*MathUtils.RAD2DEG*Math.atan(t),this.updateProjectionMatrix();},getFocalLength:function(){const e=Math.tan(.5*MathUtils.DEG2RAD*this.fov);return .5*this.getFilmHeight()/e},getEffectiveFOV:function(){return 2*MathUtils.RAD2DEG*Math.atan(Math.tan(.5*MathUtils.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(e,t,n,r,i,a){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix();},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix();},updateProjectionMatrix:function(){const e=this.near;let t=e*Math.tan(.5*MathUtils.DEG2RAD*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r;const a=this.view;if(null!==this.view&&this.view.enabled){const e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o;}const o=this.filmOffset;0!==o&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert();},toJSON:function(e){const t=Object3D.prototype.toJSON.call(this,e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}});const fov=90,aspect=1;class CubeCamera extends Object3D{constructor(e,t,n){if(super(),this.type="CubeCamera",!0!==n.isWebGLCubeRenderTarget)return void console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");this.renderTarget=n;const r=new PerspectiveCamera(90,1,e,t);r.layers=this.layers,r.up.set(0,-1,0),r.lookAt(new Vector3(1,0,0)),this.add(r);const i=new PerspectiveCamera(90,1,e,t);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new Vector3(-1,0,0)),this.add(i);const a=new PerspectiveCamera(90,1,e,t);a.layers=this.layers,a.up.set(0,0,1),a.lookAt(new Vector3(0,1,0)),this.add(a);const o=new PerspectiveCamera(90,1,e,t);o.layers=this.layers,o.up.set(0,0,-1),o.lookAt(new Vector3(0,-1,0)),this.add(o);const s=new PerspectiveCamera(90,1,e,t);s.layers=this.layers,s.up.set(0,-1,0),s.lookAt(new Vector3(0,0,1)),this.add(s);const l=new PerspectiveCamera(90,1,e,t);l.layers=this.layers,l.up.set(0,-1,0),l.lookAt(new Vector3(0,0,-1)),this.add(l);}update(e,t){null===this.parent&&this.updateMatrixWorld();const n=this.renderTarget,[r,i,a,o,s,l]=this.children,c=e.xr.enabled,h=e.getRenderTarget();e.xr.enabled=!1;const u=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0),e.render(t,r),e.setRenderTarget(n,1),e.render(t,i),e.setRenderTarget(n,2),e.render(t,a),e.setRenderTarget(n,3),e.render(t,o),e.setRenderTarget(n,4),e.render(t,s),n.texture.generateMipmaps=u,e.setRenderTarget(n,5),e.render(t,l),e.setRenderTarget(h),e.xr.enabled=c;}}class CubeTexture extends Texture{constructor(e,t,n,r,i,a,o,s,l,c){super(e=void 0!==e?e:[],t=void 0!==t?t:301,n,r,i,a,o=void 0!==o?o:1022,s,l,c),this._needsFlipEnvMap=!0,this.flipY=!1;}get images(){return this.image}set images(e){this.image=e;}}CubeTexture.prototype.isCubeTexture=!0;class WebGLCubeRenderTarget extends WebGLRenderTarget{constructor(e,t,n){Number.isInteger(t)&&(console.warn("THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )"),t=n),super(e,e,t),t=t||{},this.texture=new CubeTexture(void 0,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.encoding),this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:1006,this.texture._needsFlipEnvMap=!1;}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.format=1023,this.texture.encoding=t.encoding,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},r=new BoxGeometry(5,5,5),i=new ShaderMaterial({name:"CubemapFromEquirect",uniforms:cloneUniforms(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;const a=new Mesh(r,i),o=t.minFilter;1008===t.minFilter&&(t.minFilter=1006);return new CubeCamera(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t,n,r){const i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i);}}WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget=!0;class DataTexture extends Texture{constructor(e,t,n,r,i,a,o,s,l,c,h,u){super(null,a,o,s,l,c,r,i,h,u),this.image={data:e||null,width:t||1,height:n||1},this.magFilter=void 0!==l?l:1003,this.minFilter=void 0!==c?c:1003,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.needsUpdate=!0;}}DataTexture.prototype.isDataTexture=!0;const _sphere$1=new Sphere,_vector$5=new Vector3;class Frustum{constructor(e=new Plane,t=new Plane,n=new Plane,r=new Plane,i=new Plane,a=new Plane){this.planes=[e,t,n,r,i,a];}set(e,t,n,r,i,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e){const t=this.planes,n=e.elements,r=n[0],i=n[1],a=n[2],o=n[3],s=n[4],l=n[5],c=n[6],h=n[7],u=n[8],d=n[9],p=n[10],m=n[11],f=n[12],g=n[13],v=n[14],_=n[15];return t[0].setComponents(o-r,h-s,m-u,_-f).normalize(),t[1].setComponents(o+r,h+s,m+u,_+f).normalize(),t[2].setComponents(o+i,h+l,m+d,_+g).normalize(),t[3].setComponents(o-i,h-l,m-d,_-g).normalize(),t[4].setComponents(o-a,h-c,m-p,_-v).normalize(),t[5].setComponents(o+a,h+c,m+p,_+v).normalize(),this}intersectsObject(e){const t=e.geometry;return null===t.boundingSphere&&t.computeBoundingSphere(),_sphere$1.copy(t.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(_sphere$1)}intersectsSprite(e){return _sphere$1.center.set(0,0,0),_sphere$1.radius=.7071067811865476,_sphere$1.applyMatrix4(e.matrixWorld),this.intersectsSphere(_sphere$1)}intersectsSphere(e){const t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,_vector$5.y=r.normal.y>0?e.max.y:e.min.y,_vector$5.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(_vector$5)<0)return !1}return !0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return !1;return !0}clone(){return (new this.constructor).copy(this)}}function WebGLAnimation(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i);}return {start:function(){!0!==t&&null!==n&&(r=e.requestAnimationFrame(i),t=!0);},stop:function(){e.cancelAnimationFrame(r),t=!1;},setAnimationLoop:function(e){n=e;},setContext:function(t){e=t;}}}function WebGLAttributes(e,t){const n=t.isWebGL2,r=new WeakMap;return {get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),r.get(e)},remove:function(t){t.isInterleavedBufferAttribute&&(t=t.data);const n=r.get(t);n&&(e.deleteBuffer(n.buffer),r.delete(t));},update:function(t,i){if(t.isGLBufferAttribute){const e=r.get(t);return void((!e||e.version=0){const a=l[t];if(void 0!==a){const t=a.normalized,i=a.itemSize,o=n.get(a);if(void 0===o)continue;const l=o.buffer,c=o.type,h=o.bytesPerElement;if(a.isInterleavedBufferAttribute){const n=a.data,o=n.stride,u=a.offset;n&&n.isInstancedInterleavedBuffer?(f(r,n.meshPerAttribute),void 0===s._maxInstanceCount&&(s._maxInstanceCount=n.meshPerAttribute*n.count)):m(r),e.bindBuffer(34962,l),v(r,i,c,t,o*h,u*h);}else a.isInstancedBufferAttribute?(f(r,a.meshPerAttribute),void 0===s._maxInstanceCount&&(s._maxInstanceCount=a.meshPerAttribute*a.count)):m(r),e.bindBuffer(34962,l),v(r,i,c,t,0,0);}else if("instanceMatrix"===t){const t=n.get(i.instanceMatrix);if(void 0===t)continue;const a=t.buffer,o=t.type;f(r+0,1),f(r+1,1),f(r+2,1),f(r+3,1),e.bindBuffer(34962,a),e.vertexAttribPointer(r+0,4,o,!1,64,0),e.vertexAttribPointer(r+1,4,o,!1,64,16),e.vertexAttribPointer(r+2,4,o,!1,64,32),e.vertexAttribPointer(r+3,4,o,!1,64,48);}else if("instanceColor"===t){const t=n.get(i.instanceColor);if(void 0===t)continue;const a=t.buffer,o=t.type;f(r,1),e.bindBuffer(34962,a),e.vertexAttribPointer(r,3,o,!1,12,0);}else if(void 0!==h){const n=h[t];if(void 0!==n)switch(n.length){case 2:e.vertexAttrib2fv(r,n);break;case 3:e.vertexAttrib3fv(r,n);break;case 4:e.vertexAttrib4fv(r,n);break;default:e.vertexAttrib1fv(r,n);}}}}g();}(i,l,u,_),null!==y&&e.bindBuffer(34963,n.get(y).buffer));},reset:_,resetDefaultState:y,dispose:function(){_();for(const e in s){const t=s[e];for(const e in t){const n=t[e];for(const e in n)u(n[e].object),delete n[e];delete t[e];}delete s[e];}},releaseStatesOfGeometry:function(e){if(void 0===s[e.id])return;const t=s[e.id];for(const e in t){const n=t[e];for(const e in n)u(n[e].object),delete n[e];delete t[e];}delete s[e.id];},releaseStatesOfProgram:function(e){for(const t in s){const n=s[t];if(void 0===n[e.id])continue;const r=n[e.id];for(const e in r)u(r[e].object),delete r[e];delete n[e.id];}},initAttributes:p,enableAttribute:m,disableUnusedAttributes:g}}function WebGLBufferRenderer(e,t,n,r){const i=r.isWebGL2;let a;this.setMode=function(e){a=e;},this.render=function(t,r){e.drawArrays(a,t,r),n.update(r,a,1);},this.renderInstances=function(r,o,s){if(0===s)return;let l,c;if(i)l=e,c="drawArraysInstanced";else if(l=t.get("ANGLE_instanced_arrays"),c="drawArraysInstancedANGLE",null===l)return void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");l[c](a,r,o,s),n.update(o,a,s);};}function WebGLCapabilities(e,t,n){let r;function i(t){if("highp"===t){if(e.getShaderPrecisionFormat(35633,36338).precision>0&&e.getShaderPrecisionFormat(35632,36338).precision>0)return "highp";t="mediump";}return "mediump"===t&&e.getShaderPrecisionFormat(35633,36337).precision>0&&e.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}const a="undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext||"undefined"!=typeof WebGL2ComputeRenderingContext&&e instanceof WebGL2ComputeRenderingContext;let o=void 0!==n.precision?n.precision:"highp";const s=i(o);s!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",s,"instead."),o=s);const l=!0===n.logarithmicDepthBuffer,c=e.getParameter(34930),h=e.getParameter(35660),u=e.getParameter(3379),d=e.getParameter(34076),p=e.getParameter(34921),m=e.getParameter(36347),f=e.getParameter(36348),g=e.getParameter(36349),v=h>0,_=a||t.has("OES_texture_float");return {isWebGL2:a,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT);}else r=0;return r},getMaxPrecision:i,precision:o,logarithmicDepthBuffer:l,maxTextures:c,maxVertexTextures:h,maxTextureSize:u,maxCubemapSize:d,maxAttributes:p,maxVertexUniforms:m,maxVaryings:f,maxFragmentUniforms:g,vertexTextures:v,floatFragmentTextures:_,floatVertexTextures:v&&_,maxSamples:a?e.getParameter(36183):0}}function WebGLClipping(e){const t=this;let n=null,r=0,i=!1,a=!1;const o=new Plane,s=new Matrix3,l={value:null,needsUpdate:!1};function c(){l.value!==n&&(l.value=n,l.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0;}function h(e,n,r,i){const a=null!==e?e.length:0;let c=null;if(0!==a){if(c=l.value,!0!==i||null===c){const t=r+4*a,i=n.matrixWorldInverse;s.getNormalMatrix(i),(null===c||c.length0){const o=e.getRenderTarget(),s=new WebGLCubeRenderTarget(a.height/2);return s.fromEquirectangularTexture(e,i),t.set(i,s),e.setRenderTarget(o),i.addEventListener("dispose",r),n(s.texture,i.mapping)}return null}}}return i},dispose:function(){t=new WeakMap;}}}function WebGLExtensions(e){const t={};function n(n){if(void 0!==t[n])return t[n];let r;switch(n){case"WEBGL_depth_texture":r=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":r=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":r=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":r=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:r=e.getExtension(n);}return t[n]=r,r}return {has:function(e){return null!==n(e)},init:function(e){e.isWebGL2?n("EXT_color_buffer_float"):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float");},get:function(e){const t=n(e);return null===t&&console.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function WebGLGeometries(e,t,n,r){const i={},a=new WeakMap;function o(e){const s=e.target;null!==s.index&&t.remove(s.index);for(const e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener("dispose",o),delete i[s.id];const l=a.get(s);l&&(t.remove(l),a.delete(s)),r.releaseStatesOfGeometry(s),!0===s.isInstancedBufferGeometry&&delete s._maxInstanceCount,n.memory.geometries--;}function s(e){const n=[],r=e.index,i=e.attributes.position;let o=0;if(null!==r){const e=r.array;o=r.version;for(let t=0,r=e.length;t65535?Uint32BufferAttribute:Uint16BufferAttribute)(n,1);s.version=o;const l=a.get(e);l&&t.remove(l),a.set(e,s);}return {get:function(e,t){return !0===i[t.id]||(t.addEventListener("dispose",o),i[t.id]=!0,n.memory.geometries++),t},update:function(e){const n=e.attributes;for(const e in n)t.update(n[e],34962);const r=e.morphAttributes;for(const e in r){const n=r[e];for(let e=0,r=n.length;e0)return e;const i=t*n;let a=arrayCacheF32[i];if(void 0===a&&(a=new Float32Array(i),arrayCacheF32[i]=a),0!==t){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i);}return a}function arraysEqual(e,t){if(e.length!==t.length)return !1;for(let n=0,r=e.length;n/gm;function resolveIncludes(e){return e.replace(includePattern,includeReplacer)}function includeReplacer(e,t){const n=ShaderChunk[t];if(void 0===n)throw new Error("Can not resolve #include <"+t+">");return resolveIncludes(n)}const deprecatedUnrollLoopPattern=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,unrollLoopPattern=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function unrollLoops(e){return e.replace(unrollLoopPattern,loopReplacer).replace(deprecatedUnrollLoopPattern,deprecatedLoopReplacer)}function deprecatedLoopReplacer(e,t,n,r){return console.warn("WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead."),loopReplacer(e,t,n,r)}function loopReplacer(e,t,n,r){let i="";for(let e=parseInt(t);e0?e.gammaFactor:1,p=n.isWebGL2?"":generateExtensions(n),m=generateDefines(a),f=i.createProgram();let g,v,_=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(g=[m].filter(filterEmptyLine).join("\n"),g.length>0&&(g+="\n"),v=[p,m].filter(filterEmptyLine).join("\n"),v.length>0&&(v+="\n")):(g=[generatePrecision(n),"#define SHADER_NAME "+n.shaderName,m,n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+d,"#define MAX_BONES "+n.maxBones,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+h:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMap&&n.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",n.normalMap&&n.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.displacementMap&&n.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.vertexTangents?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexUvs?"#define USE_UV":"",n.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.useVertexTexture?"#define BONE_TEXTURE":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#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(filterEmptyLine).join("\n"),v=[p,generatePrecision(n),"#define SHADER_NAME "+n.shaderName,m,n.alphaTest?"#define ALPHATEST "+n.alphaTest+(n.alphaTest%1?"":".0"):"","#define GAMMA_FACTOR "+d,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",n.envMap?"#define "+u:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMap&&n.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",n.normalMap&&n.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.sheen?"#define USE_SHEEN":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.vertexTangents?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexUvs?"#define USE_UV":"",n.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"",(n.extensionShaderTextureLOD||n.envMap)&&n.rendererExtensionShaderTextureLod?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?ShaderChunk.tonemapping_pars_fragment:"",0!==n.toneMapping?getToneMappingFunction("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",ShaderChunk.encodings_pars_fragment,n.map?getTexelDecodingFunction("mapTexelToLinear",n.mapEncoding):"",n.matcap?getTexelDecodingFunction("matcapTexelToLinear",n.matcapEncoding):"",n.envMap?getTexelDecodingFunction("envMapTexelToLinear",n.envMapEncoding):"",n.emissiveMap?getTexelDecodingFunction("emissiveMapTexelToLinear",n.emissiveMapEncoding):"",n.lightMap?getTexelDecodingFunction("lightMapTexelToLinear",n.lightMapEncoding):"",getTexelEncodingFunction("linearToOutputTexel",n.outputEncoding),n.depthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(filterEmptyLine).join("\n")),o=resolveIncludes(o),o=replaceLightNums(o,n),o=replaceClippingPlaneNums(o,n),s=resolveIncludes(s),s=replaceLightNums(s,n),s=replaceClippingPlaneNums(s,n),o=unrollLoops(o),s=unrollLoops(s),n.isWebGL2&&!0!==n.isRawShaderMaterial&&(_="#version 300 es\n",g=["#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,v=["#define varying in",n.glslVersion===GLSL3?"":"out highp vec4 pc_fragColor;",n.glslVersion===GLSL3?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+v);const y=_+v+s,x=WebGLShader(i,35633,_+g+o),b=WebGLShader(i,35632,y);if(i.attachShader(f,x),i.attachShader(f,b),void 0!==n.index0AttributeName?i.bindAttribLocation(f,0,n.index0AttributeName):!0===n.morphTargets&&i.bindAttribLocation(f,0,"position"),i.linkProgram(f),e.debug.checkShaderErrors){const e=i.getProgramInfoLog(f).trim(),t=i.getShaderInfoLog(x).trim(),n=i.getShaderInfoLog(b).trim();let r=!0,a=!0;if(!1===i.getProgramParameter(f,35714)){r=!1;const t=getShaderErrors(i,x,"vertex"),n=getShaderErrors(i,b,"fragment");console.error("THREE.WebGLProgram: shader error: ",i.getError(),"35715",i.getProgramParameter(f,35715),"gl.getProgramInfoLog",e,t,n);}else ""!==e?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",e):""!==t&&""!==n||(a=!1);a&&(this.diagnostics={runnable:r,programLog:e,vertexShader:{log:t,prefix:g},fragmentShader:{log:n,prefix:v}});}let M,w;return i.deleteShader(x),i.deleteShader(b),this.getUniforms=function(){return void 0===M&&(M=new WebGLUniforms(i,f)),M},this.getAttributes=function(){return void 0===w&&(w=fetchAttributeLocations(i,f)),w},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(f),this.program=void 0;},this.name=n.shaderName,this.id=programIdCount++,this.cacheKey=t,this.usedTimes=1,this.program=f,this.vertexShader=x,this.fragmentShader=b,this}function WebGLPrograms(e,t,n,r,i,a){const o=[],s=r.isWebGL2,l=r.logarithmicDepthBuffer,c=r.floatVertexTextures,h=r.maxVertexUniforms,u=r.vertexTextures;let d=r.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"},m=["precision","isWebGL2","supportsVertexTextures","outputEncoding","instancing","instancingColor","map","mapEncoding","matcap","matcapEncoding","envMap","envMapMode","envMapEncoding","envMapCubeUV","lightMap","lightMapEncoding","aoMap","emissiveMap","emissiveMapEncoding","bumpMap","normalMap","objectSpaceNormalMap","tangentSpaceNormalMap","clearcoatMap","clearcoatRoughnessMap","clearcoatNormalMap","displacementMap","specularMap","roughnessMap","metalnessMap","gradientMap","alphaMap","combine","vertexColors","vertexTangents","vertexUvs","uvsVertexOnly","fog","useFog","fogExp2","flatShading","sizeAttenuation","logarithmicDepthBuffer","skinning","maxBones","useVertexTexture","morphTargets","morphNormals","maxMorphTargets","maxMorphNormals","premultipliedAlpha","numDirLights","numPointLights","numSpotLights","numHemiLights","numRectAreaLights","numDirLightShadows","numPointLightShadows","numSpotLightShadows","shadowMapEnabled","shadowMapType","toneMapping","physicallyCorrectLights","alphaTest","doubleSided","flipSided","numClippingPlanes","numClipIntersection","depthPacking","dithering","sheen","transmissionMap"];function f(e){let t;return e&&e.isTexture?t=e.encoding:e&&e.isWebGLRenderTarget?(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),t=e.texture.encoding):t=3e3,t}return {getParameters:function(i,o,m,g,v){const _=g.fog,y=i.isMeshStandardMaterial?g.environment:null,x=t.get(i.envMap||y),b=p[i.type],M=v.isSkinnedMesh?function(e){const t=e.skeleton.bones;if(c)return 1024;{const e=h,n=Math.floor((e-20)/4),r=Math.min(n,t.length);return r0,maxBones:M,useVertexTexture:c,morphTargets:i.morphTargets,morphNormals:i.morphNormals,maxMorphTargets:e.maxMorphTargets,maxMorphNormals:e.maxMorphNormals,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&m.length>0,shadowMapType:e.shadowMap.type,toneMapping:i.toneMapped?e.toneMapping:0,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:i.premultipliedAlpha,alphaTest:i.alphaTest,doubleSided:2===i.side,flipSided:1===i.side,depthPacking:void 0!==i.depthPacking&&i.depthPacking,index0AttributeName:i.index0AttributeName,extensionDerivatives:i.extensions&&i.extensions.derivatives,extensionFragDepth:i.extensions&&i.extensions.fragDepth,extensionDrawBuffers:i.extensions&&i.extensions.drawBuffers,extensionShaderTextureLOD:i.extensions&&i.extensions.shaderTextureLOD,rendererExtensionFragDepth:s||n.has("EXT_frag_depth"),rendererExtensionDrawBuffers:s||n.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:s||n.has("EXT_shader_texture_lod"),customProgramCacheKey:i.customProgramCacheKey()}},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.fragmentShader),n.push(t.vertexShader)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);if(!1===t.isRawShaderMaterial){for(let e=0;e1&&r.sort(e||painterSortStable),i.length>1&&i.sort(t||reversePainterSortStable);}}}function WebGLRenderLists(e){let t=new WeakMap;return {get:function(n,r){let i;return !1===t.has(n)?(i=new WebGLRenderList(e),t.set(n,[i])):r>=t.get(n).length?(i=new WebGLRenderList(e),t.get(n).push(i)):i=t.get(n)[r],i},dispose:function(){t=new WeakMap;}}}function UniformsCache(){const e={};return {get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new Vector3,color:new Color};break;case"SpotLight":n={position:new Vector3,direction:new Vector3,color:new Color,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Vector3,color:new Color,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Vector3,skyColor:new Color,groundColor:new Color};break;case"RectAreaLight":n={color:new Color,position:new Vector3,halfWidth:new Vector3,halfHeight:new Vector3};}return e[t.id]=n,n}}}function ShadowUniformsCache(){const e={};return {get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2,shadowCameraNear:1,shadowCameraFar:1e3};}return e[t.id]=n,n}}}let nextVersion=0;function shadowCastingLightsFirst(e,t){return (t.castShadow?1:0)-(e.castShadow?1:0)}function WebGLLights(e,t){const n=new UniformsCache,r=ShadowUniformsCache(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(let e=0;e<9;e++)i.probe.push(new Vector3);const a=new Vector3,o=new Matrix4,s=new Matrix4;return {setup:function(a){let o=0,s=0,l=0;for(let e=0;e<9;e++)i.probe[e].set(0,0,0);let c=0,h=0,u=0,d=0,p=0,m=0,f=0,g=0;a.sort(shadowCastingLightsFirst);for(let e=0,t=a.length;e0&&(t.isWebGL2||!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=UniformsLib.LTC_FLOAT_1,i.rectAreaLTC2=UniformsLib.LTC_FLOAT_2):!0===e.has("OES_texture_half_float_linear")?(i.rectAreaLTC1=UniformsLib.LTC_HALF_1,i.rectAreaLTC2=UniformsLib.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),i.ambient[0]=o,i.ambient[1]=s,i.ambient[2]=l;const v=i.hash;v.directionalLength===c&&v.pointLength===h&&v.spotLength===u&&v.rectAreaLength===d&&v.hemiLength===p&&v.numDirectionalShadows===m&&v.numPointShadows===f&&v.numSpotShadows===g||(i.directional.length=c,i.spot.length=u,i.rectArea.length=d,i.point.length=h,i.hemi.length=p,i.directionalShadow.length=m,i.directionalShadowMap.length=m,i.pointShadow.length=f,i.pointShadowMap.length=f,i.spotShadow.length=g,i.spotShadowMap.length=g,i.directionalShadowMatrix.length=m,i.pointShadowMatrix.length=f,i.spotShadowMatrix.length=g,v.directionalLength=c,v.pointLength=h,v.spotLength=u,v.rectAreaLength=d,v.hemiLength=p,v.numDirectionalShadows=m,v.numPointShadows=f,v.numSpotShadows=g,i.version=nextVersion++);},setupView:function(e,t){let n=0,r=0,l=0,c=0,h=0;const u=t.matrixWorldInverse;for(let t=0,d=e.length;t=n.get(r).length?(a=new WebGLRenderState(e,t),n.get(r).push(a)):a=n.get(r)[i],a},dispose:function(){n=new WeakMap;}}}class MeshDepthMaterial extends Material{constructor(e){super(),this.type="MeshDepthMaterial",this.depthPacking=3200,this.skinning=!1,this.morphTargets=!1,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.setValues(e);}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.skinning=e.skinning,this.morphTargets=e.morphTargets,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}MeshDepthMaterial.prototype.isMeshDepthMaterial=!0;class MeshDistanceMaterial extends Material{constructor(e){super(),this.type="MeshDistanceMaterial",this.referencePosition=new Vector3,this.nearDistance=1,this.farDistance=1e3,this.skinning=!1,this.morphTargets=!1,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.fog=!1,this.setValues(e);}copy(e){return super.copy(e),this.referencePosition.copy(e.referencePosition),this.nearDistance=e.nearDistance,this.farDistance=e.farDistance,this.skinning=e.skinning,this.morphTargets=e.morphTargets,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}MeshDistanceMaterial.prototype.isMeshDistanceMaterial=!0;var vsm_frag="uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}",vsm_vert="void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";function WebGLShadowMap(e,t,n){let r=new Frustum;const i=new Vector2,a=new Vector2,o=new Vector4,s=[],l=[],c={},h={0:1,1:0,2:2},u=new ShaderMaterial({defines:{SAMPLE_RATE:2/8,HALF_SAMPLE_RATE:1/8},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2},radius:{value:4}},vertexShader:vsm_vert,fragmentShader:vsm_frag}),d=u.clone();d.defines.HORIZONTAL_PASS=1;const p=new BufferGeometry;p.setAttribute("position",new BufferAttribute(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new Mesh(p,u),f=this;function g(n,r){const i=t.update(m);u.uniforms.shadow_pass.value=n.map.texture,u.uniforms.resolution.value=n.mapSize,u.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,i,u,m,null),d.uniforms.shadow_pass.value=n.mapPass.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,i,d,m,null);}function v(e,t,n){const r=e<<0|t<<1|n<<2;let i=s[r];return void 0===i&&(i=new MeshDepthMaterial({depthPacking:3201,morphTargets:e,skinning:t}),s[r]=i),i}function _(e,t,n){const r=e<<0|t<<1|n<<2;let i=l[r];return void 0===i&&(i=new MeshDistanceMaterial({morphTargets:e,skinning:t}),l[r]=i),i}function y(t,n,r,i,a,o,s){let l=null,u=v,d=t.customDepthMaterial;if(!0===i.isPointLight&&(u=_,d=t.customDistanceMaterial),void 0===d){let e=!1;!0===r.morphTargets&&(e=n.morphAttributes&&n.morphAttributes.position&&n.morphAttributes.position.length>0);let i=!1;!0===t.isSkinnedMesh&&(!0===r.skinning?i=!0:console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",t));l=u(e,i,!0===t.isInstancedMesh);}else l=d;if(e.localClippingEnabled&&!0===r.clipShadows&&0!==r.clippingPlanes.length){const e=l.uuid,t=r.uuid;let n=c[e];void 0===n&&(n={},c[e]=n);let i=n[t];void 0===i&&(i=l.clone(),n[t]=i),l=i;}return l.visible=r.visible,l.wireframe=r.wireframe,l.side=3===s?null!==r.shadowSide?r.shadowSide:r.side:null!==r.shadowSide?r.shadowSide:h[r.side],l.clipShadows=r.clipShadows,l.clippingPlanes=r.clippingPlanes,l.clipIntersection=r.clipIntersection,l.wireframeLinewidth=r.wireframeLinewidth,l.linewidth=r.linewidth,!0===i.isPointLight&&!0===l.isMeshDistanceMaterial&&(l.referencePosition.setFromMatrixPosition(i.matrixWorld),l.nearDistance=a,l.farDistance=o),l}function x(n,i,a,o,s){if(!1===n.visible)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===s)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);const r=t.update(n),i=n.material;if(Array.isArray(i)){const t=r.groups;for(let l=0,c=t.length;ln||i.y>n)&&(i.x>n&&(a.x=Math.floor(n/p.x),i.x=a.x*p.x,u.mapSize.x=a.x),i.y>n&&(a.y=Math.floor(n/p.y),i.y=a.y*p.y,u.mapSize.y=a.y)),null===u.map&&!u.isPointLightShadow&&3===this.type){const e={minFilter:1006,magFilter:1006,format:1023};u.map=new WebGLRenderTarget(i.x,i.y,e),u.map.texture.name=h.name+".shadowMap",u.mapPass=new WebGLRenderTarget(i.x,i.y,e),u.camera.updateProjectionMatrix();}if(null===u.map){const e={minFilter:1003,magFilter:1003,format:1023};u.map=new WebGLRenderTarget(i.x,i.y,e),u.map.texture.name=h.name+".shadowMap",u.camera.updateProjectionMatrix();}e.setRenderTarget(u.map),e.clear();const m=u.getViewportCount();for(let e=0;e=1):-1!==E.indexOf("OpenGL ES")&&(T=parseFloat(/^OpenGL ES (\d)/.exec(E)[1]),S=T>=2);let A=null,L={};const C=new Vector4,R=new Vector4;function P(t,n,r){const i=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,10241,9728),e.texParameteri(t,10240,9728);for(let t=0;tr||e.height>r)&&(i=r/Math.max(e.width,e.height)),i<1||!0===t){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const r=t?MathUtils.floorPowerOfTwo:Math.floor,a=r(i*e.width),o=r(i*e.height);void 0===p&&(p=f(a,o));const s=n?f(a,o):p;s.width=a,s.height=o;return s.getContext("2d").drawImage(e,0,0,a,o),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+e.width+"x"+e.height+") to ("+a+"x"+o+")."),s}return "data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+e.width+"x"+e.height+")."),e}return e}function v(e){return MathUtils.isPowerOfTwo(e.width)&&MathUtils.isPowerOfTwo(e.height)}function _(e,t){return e.generateMipmaps&&t&&1003!==e.minFilter&&1006!==e.minFilter}function y(t,n,i,a){e.generateMipmap(t);r.get(n).__maxMipLevel=Math.log2(Math.max(i,a));}function x(n,r,i){if(!1===s)return r;if(null!==n){if(void 0!==e[n])return e[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'");}let a=r;return 6403===r&&(5126===i&&(a=33326),5131===i&&(a=33325),5121===i&&(a=33321)),6407===r&&(5126===i&&(a=34837),5131===i&&(a=34843),5121===i&&(a=32849)),6408===r&&(5126===i&&(a=34836),5131===i&&(a=34842),5121===i&&(a=32856)),33325!==a&&33326!==a&&34842!==a&&34836!==a||t.get("EXT_color_buffer_float"),a}function b(e){return 1003===e||1004===e||1005===e?9728:9729}function M(t){const n=t.target;n.removeEventListener("dispose",M),function(t){const n=r.get(t);if(void 0===n.__webglInit)return;e.deleteTexture(n.__webglTexture),r.remove(t);}(n),n.isVideoTexture&&d.delete(n),o.memory.textures--;}function w(t){const n=t.target;n.removeEventListener("dispose",w),function(t){const n=t.texture,i=r.get(t),a=r.get(n);if(!t)return;void 0!==a.__webglTexture&&e.deleteTexture(a.__webglTexture);t.depthTexture&&t.depthTexture.dispose();if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++)e.deleteFramebuffer(i.__webglFramebuffer[t]),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer[t]);else e.deleteFramebuffer(i.__webglFramebuffer),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer),i.__webglMultisampledFramebuffer&&e.deleteFramebuffer(i.__webglMultisampledFramebuffer),i.__webglColorRenderbuffer&&e.deleteRenderbuffer(i.__webglColorRenderbuffer),i.__webglDepthRenderbuffer&&e.deleteRenderbuffer(i.__webglDepthRenderbuffer);r.remove(n),r.remove(t);}(n),o.memory.textures--;}let S=0;function T(e,t){const i=r.get(e);if(e.isVideoTexture&&function(e){const t=o.render.frame;d.get(e)!==t&&(d.set(e,t),e.update());}(e),e.version>0&&i.__version!==e.version){const n=e.image;if(void 0===n)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");else {if(!1!==n.complete)return void P(i,e,t);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");}}n.activeTexture(33984+t),n.bindTexture(3553,i.__webglTexture);}function E(t,i){const o=r.get(t);t.version>0&&o.__version!==t.version?function(t,r,i){if(6!==r.image.length)return;R(t,r),n.activeTexture(33984+i),n.bindTexture(34067,t.__webglTexture),e.pixelStorei(37440,r.flipY),e.pixelStorei(37441,r.premultiplyAlpha),e.pixelStorei(3317,r.unpackAlignment),e.pixelStorei(37443,0);const o=r&&(r.isCompressedTexture||r.image[0].isCompressedTexture),l=r.image[0]&&r.image[0].isDataTexture,h=[];for(let e=0;e<6;e++)h[e]=o||l?l?r.image[e].image:r.image[e]:g(r.image[e],!1,!0,c);const u=h[0],d=v(u)||s,p=a.convert(r.format),m=a.convert(r.type),f=x(r.internalFormat,p,m);let b;if(C(34067,r,d),o){for(let e=0;e<6;e++){b=h[e].mipmaps;for(let t=0;t1||r.get(a).__currentAnisotropy)&&(e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy);}}function R(t,n){void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",M),t.__webglTexture=e.createTexture(),o.memory.textures++);}function P(t,r,i){let o=3553;r.isDataTexture2DArray&&(o=35866),r.isDataTexture3D&&(o=32879),R(t,r),n.activeTexture(33984+i),n.bindTexture(o,t.__webglTexture),e.pixelStorei(37440,r.flipY),e.pixelStorei(37441,r.premultiplyAlpha),e.pixelStorei(3317,r.unpackAlignment),e.pixelStorei(37443,0);const l=function(e){return !s&&(1001!==e.wrapS||1001!==e.wrapT||1003!==e.minFilter&&1006!==e.minFilter)}(r)&&!1===v(r.image),c=g(r.image,l,!1,h),u=v(c)||s,d=a.convert(r.format);let p,m=a.convert(r.type),f=x(r.internalFormat,d,m);C(o,r,u);const b=r.mipmaps;if(r.isDepthTexture)f=6402,s?f=1015===r.type?36012:1014===r.type?33190:1020===r.type?35056:33189:1015===r.type&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),1026===r.format&&6402===f&&1012!==r.type&&1014!==r.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),r.type=1012,m=a.convert(r.type)),1027===r.format&&6402===f&&(f=34041,1020!==r.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),r.type=1020,m=a.convert(r.type))),n.texImage2D(3553,0,f,c.width,c.height,0,d,m,null);else if(r.isDataTexture)if(b.length>0&&u){for(let e=0,t=b.length;e0&&u){for(let e=0,t=b.length;e=l&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+l),S+=1,e},this.resetTextureUnits=function(){S=0;},this.setTexture2D=T,this.setTexture2DArray=function(e,t){const i=r.get(e);e.version>0&&i.__version!==e.version?P(i,e,t):(n.activeTexture(33984+t),n.bindTexture(35866,i.__webglTexture));},this.setTexture3D=function(e,t){const i=r.get(e);e.version>0&&i.__version!==e.version?P(i,e,t):(n.activeTexture(33984+t),n.bindTexture(32879,i.__webglTexture));},this.setTextureCube=E,this.setupRenderTarget=function(t){const i=t.texture,l=r.get(t),c=r.get(i);t.addEventListener("dispose",w),c.__webglTexture=e.createTexture(),o.memory.textures++;const h=!0===t.isWebGLCubeRenderTarget,u=!0===t.isWebGLMultisampleRenderTarget,d=i.isDataTexture3D||i.isDataTexture2DArray,p=v(t)||s;if(!s||1022!==i.format||1015!==i.type&&1016!==i.type||(i.format=1023,console.warn("THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.")),h){l.__webglFramebuffer=[];for(let t=0;t<6;t++)l.__webglFramebuffer[t]=e.createFramebuffer();}else if(l.__webglFramebuffer=e.createFramebuffer(),u)if(s){l.__webglMultisampledFramebuffer=e.createFramebuffer(),l.__webglColorRenderbuffer=e.createRenderbuffer(),e.bindRenderbuffer(36161,l.__webglColorRenderbuffer);const n=a.convert(i.format),r=a.convert(i.type),o=x(i.internalFormat,n,r),s=G(t);e.renderbufferStorageMultisample(36161,s,o,t.width,t.height),e.bindFramebuffer(36160,l.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(36160,36064,36161,l.__webglColorRenderbuffer),e.bindRenderbuffer(36161,null),t.depthBuffer&&(l.__webglDepthRenderbuffer=e.createRenderbuffer(),D(l.__webglDepthRenderbuffer,t,!0)),e.bindFramebuffer(36160,null);}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.");if(h){n.bindTexture(34067,c.__webglTexture),C(34067,i,p);for(let e=0;e<6;e++)B(l.__webglFramebuffer[e],t,36064,34069+e);_(i,p)&&y(34067,i,t.width,t.height),n.bindTexture(34067,null);}else {let e=3553;if(d)if(s){e=i.isDataTexture3D?32879:35866;}else console.warn("THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.");n.bindTexture(e,c.__webglTexture),C(e,i,p),B(l.__webglFramebuffer,t,36064,e),_(i,p)&&y(3553,i,t.width,t.height),n.bindTexture(3553,null);}t.depthBuffer&&I(t);},this.updateRenderTargetMipmap=function(e){const t=e.texture;if(_(t,v(e)||s)){const i=e.isWebGLCubeRenderTarget?34067:3553,a=r.get(t).__webglTexture;n.bindTexture(i,a),y(i,t,e.width,e.height),n.bindTexture(i,null);}},this.updateMultisampleRenderTarget=function(t){if(t.isWebGLMultisampleRenderTarget)if(s){const n=r.get(t);e.bindFramebuffer(36008,n.__webglMultisampledFramebuffer),e.bindFramebuffer(36009,n.__webglFramebuffer);const i=t.width,a=t.height;let o=16384;t.depthBuffer&&(o|=256),t.stencilBuffer&&(o|=1024),e.blitFramebuffer(0,0,i,a,0,0,i,a,o,9728),e.bindFramebuffer(36160,n.__webglMultisampledFramebuffer);}else console.warn("THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.");},this.safeSetTexture2D=function(e,t){e&&e.isWebGLRenderTarget&&(!1===F&&(console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead."),F=!0),e=e.texture),T(e,t);},this.safeSetTextureCube=function(e,t){e&&e.isWebGLCubeRenderTarget&&(!1===V&&(console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead."),V=!0),e=e.texture),E(e,t);};}function WebGLUtils(e,t,n){const r=n.isWebGL2;return {convert:function(e){let n;if(1009===e)return 5121;if(1017===e)return 32819;if(1018===e)return 32820;if(1019===e)return 33635;if(1010===e)return 5120;if(1011===e)return 5122;if(1012===e)return 5123;if(1013===e)return 5124;if(1014===e)return 5125;if(1015===e)return 5126;if(1016===e)return r?5131:(n=t.get("OES_texture_half_float"),null!==n?n.HALF_FLOAT_OES:null);if(1021===e)return 6406;if(1022===e)return 6407;if(1023===e)return 6408;if(1024===e)return 6409;if(1025===e)return 6410;if(1026===e)return 6402;if(1027===e)return 34041;if(1028===e)return 6403;if(1029===e)return 36244;if(1030===e)return 33319;if(1031===e)return 33320;if(1032===e)return 36248;if(1033===e)return 36249;if(33776===e||33777===e||33778===e||33779===e){if(n=t.get("WEBGL_compressed_texture_s3tc"),null===n)return null;if(33776===e)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===e)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===e)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===e)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===e||35841===e||35842===e||35843===e){if(n=t.get("WEBGL_compressed_texture_pvrtc"),null===n)return null;if(35840===e)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===e)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===e)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===e)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===e)return n=t.get("WEBGL_compressed_texture_etc1"),null!==n?n.COMPRESSED_RGB_ETC1_WEBGL:null;if((37492===e||37496===e)&&(n=t.get("WEBGL_compressed_texture_etc"),null!==n)){if(37492===e)return n.COMPRESSED_RGB8_ETC2;if(37496===e)return n.COMPRESSED_RGBA8_ETC2_EAC}return 37808===e||37809===e||37810===e||37811===e||37812===e||37813===e||37814===e||37815===e||37816===e||37817===e||37818===e||37819===e||37820===e||37821===e||37840===e||37841===e||37842===e||37843===e||37844===e||37845===e||37846===e||37847===e||37848===e||37849===e||37850===e||37851===e||37852===e||37853===e?(n=t.get("WEBGL_compressed_texture_astc"),null!==n?e:null):36492===e?(n=t.get("EXT_texture_compression_bptc"),null!==n?e:null):1020===e?r?34042:(n=t.get("WEBGL_depth_texture"),null!==n?n.UNSIGNED_INT_24_8_WEBGL:null):void 0}}}function ArrayCamera(e=[]){PerspectiveCamera.call(this),this.cameras=e;}ArrayCamera.prototype=Object.assign(Object.create(PerspectiveCamera.prototype),{constructor:ArrayCamera,isArrayCamera:!0});class Group extends Object3D{constructor(){super(),this.type="Group";}}function WebXRController(){this._targetRay=null,this._grip=null,this._hand=null;}function WebXRManager(e,t){const n=this;let r=null,i=1,a=null,o="local-floor",s=null;const l=[],c=new Map,h=new PerspectiveCamera;h.layers.enable(1),h.viewport=new Vector4;const u=new PerspectiveCamera;u.layers.enable(2),u.viewport=new Vector4;const d=[h,u],p=new ArrayCamera;p.layers.enable(1),p.layers.enable(2);let m=null,f=null;function g(e){const t=c.get(e.inputSource);t&&t.dispatchEvent({type:e.type,data:e.inputSource});}function v(){c.forEach((function(e,t){e.disconnect(t);})),c.clear(),m=null,f=null,e.setFramebuffer(null),e.setRenderTarget(e.getRenderTarget()),w.stop(),n.isPresenting=!1,n.dispatchEvent({type:"sessionend"});}function _(e){const t=r.inputSources;for(let e=0;e0&&be(a,e,t),o.length>0&&be(o,e,t),!0===e.isScene&&e.onAfterRender(f,e,t),null!==x&&($.updateRenderTargetMipmap(x),$.updateMultisampleRenderTarget(x)),W.buffers.depth.setTest(!0),W.buffers.depth.setMask(!0),W.buffers.color.setMask(!0),W.setPolygonOffset(!1),m.pop(),d=m.length>0?m[m.length-1]:null,p.pop(),u=p.length>0?p[p.length-1]:null;},this.setFramebuffer=function(e){v!==e&&null===x&&ce.bindFramebuffer(36160,e),v=e;},this.getActiveCubeFace=function(){return _},this.getActiveMipmapLevel=function(){return y},this.getRenderTarget=function(){return x},this.setRenderTarget=function(e,t=0,n=0){x=e,_=t,y=n,e&&void 0===q.get(e).__webglFramebuffer&&$.setupRenderTarget(e);let r=v,i=!1,a=!1;if(e){const n=e.texture;(n.isDataTexture3D||n.isDataTexture2DArray)&&(a=!0);const o=q.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=o[t],i=!0):r=e.isWebGLMultisampleRenderTarget?q.get(e).__webglMultisampledFramebuffer:o,S.copy(e.viewport),T.copy(e.scissor),E=e.scissorTest;}else S.copy(B).multiplyScalar(C).floor(),T.copy(D).multiplyScalar(C).floor(),E=I;if(b!==r&&(ce.bindFramebuffer(36160,r),b=r),W.viewport(S),W.scissor(T),W.setScissorTest(E),i){const r=q.get(e.texture);ce.framebufferTexture2D(36160,36064,34069+t,r.__webglTexture,n);}else if(a){const r=q.get(e.texture),i=t||0;ce.framebufferTextureLayer(36160,36064,r.__webglTexture,n||0,i);}},this.readRenderTargetPixels=function(e,t,n,r,i,a,o){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let s=q.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==o&&(s=s[o]),s){let o=!1;s!==b&&(ce.bindFramebuffer(36160,s),o=!0);try{const s=e.texture,l=s.format,c=s.type;if(1023!==l&&se.convert(l)!==ce.getParameter(35739))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const h=1016===c&&(H.has("EXT_color_buffer_half_float")||k.isWebGL2&&H.has("EXT_color_buffer_float"));if(!(1009===c||se.convert(c)===ce.getParameter(35738)||1015===c&&(k.isWebGL2||H.has("OES_texture_float")||H.has("WEBGL_color_buffer_float"))||h))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");36053===ce.checkFramebufferStatus(36160)?t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&ce.readPixels(t,n,r,i,se.convert(l),se.convert(c),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.");}finally{o&&ce.bindFramebuffer(36160,b);}}},this.copyFramebufferToTexture=function(e,t,n=0){const r=Math.pow(2,-n),i=Math.floor(t.image.width*r),a=Math.floor(t.image.height*r),o=se.convert(t.format);$.setTexture2D(t,0),ce.copyTexImage2D(3553,n,o,e.x,e.y,i,a,0),W.unbindTexture();},this.copyTextureToTexture=function(e,t,n,r=0){const i=t.image.width,a=t.image.height,o=se.convert(n.format),s=se.convert(n.type);$.setTexture2D(n,0),ce.pixelStorei(37440,n.flipY),ce.pixelStorei(37441,n.premultiplyAlpha),ce.pixelStorei(3317,n.unpackAlignment),t.isDataTexture?ce.texSubImage2D(3553,r,e.x,e.y,i,a,o,s,t.image.data):t.isCompressedTexture?ce.compressedTexSubImage2D(3553,r,e.x,e.y,t.mipmaps[0].width,t.mipmaps[0].height,o,t.mipmaps[0].data):ce.texSubImage2D(3553,r,e.x,e.y,o,s,t.image),0===r&&n.generateMipmaps&&ce.generateMipmap(3553),W.unbindTexture();},this.copyTextureToTexture3D=function(e,t,n,r,i=0){if(f.isWebGL1Renderer)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");const{width:a,height:o,data:s}=n.image,l=se.convert(r.format),c=se.convert(r.type);let h;if(r.isDataTexture3D)$.setTexture3D(r,0),h=32879;else {if(!r.isDataTexture2DArray)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");$.setTexture2DArray(r,0),h=35866;}ce.pixelStorei(37440,r.flipY),ce.pixelStorei(37441,r.premultiplyAlpha),ce.pixelStorei(3317,r.unpackAlignment);const u=ce.getParameter(3314),d=ce.getParameter(32878),p=ce.getParameter(3316),m=ce.getParameter(3315),g=ce.getParameter(32877);ce.pixelStorei(3314,a),ce.pixelStorei(32878,o),ce.pixelStorei(3316,e.min.x),ce.pixelStorei(3315,e.min.y),ce.pixelStorei(32877,e.min.z),ce.texSubImage3D(h,i,t.x,t.y,t.z,e.max.x-e.min.x+1,e.max.y-e.min.y+1,e.max.z-e.min.z+1,l,c,s),ce.pixelStorei(3314,u),ce.pixelStorei(32878,d),ce.pixelStorei(3316,p),ce.pixelStorei(3315,m),ce.pixelStorei(32877,g),0===i&&r.generateMipmaps&&ce.generateMipmap(h),W.unbindTexture();},this.initTexture=function(e){$.setTexture2D(e,0),W.unbindTexture();},this.resetState=function(){W.reset(),le.reset();},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}));}Group.prototype.isGroup=!0,Object.assign(WebXRController.prototype,{constructor:WebXRController,getHandSpace:function(){return null===this._hand&&(this._hand=new Group,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand},getTargetRaySpace:function(){return null===this._targetRay&&(this._targetRay=new Group,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1),this._targetRay},getGripSpace:function(){return null===this._grip&&(this._grip=new Group,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1),this._grip},dispatchEvent:function(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this},disconnect:function(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this},update:function(e,t,n){let r=null,i=null,a=null;const o=this._targetRay,s=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState)if(l&&e.hand){a=!0;for(const r of e.hand.values()){const e=t.getJointPose(r,n);if(void 0===l.joints[r.jointName]){const e=new Group;e.matrixAutoUpdate=!1,e.visible=!1,l.joints[r.jointName]=e,l.add(e);}const i=l.joints[r.jointName];null!==e&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.jointRadius=e.radius),i.visible=null!==e;}const r=l.joints["index-finger-tip"],i=l.joints["thumb-tip"],o=r.position.distanceTo(i.position),s=.02,c=.005;l.inputState.pinching&&o>s+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&o<=s-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}));}else null!==o&&(r=t.getPose(e.targetRaySpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale))),null!==s&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),null!==i&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale)));return null!==o&&(o.visible=null!==r),null!==s&&(s.visible=null!==i),null!==l&&(l.visible=null!==a),this}}),Object.assign(WebXRManager.prototype,EventDispatcher.prototype);class WebGL1Renderer extends WebGLRenderer{}WebGL1Renderer.prototype.isWebGL1Renderer=!0;class FogExp2{constructor(e,t){this.name="",this.color=new Color(e),this.density=void 0!==t?t:25e-5;}clone(){return new FogExp2(this.color,this.density)}toJSON(){return {type:"FogExp2",color:this.color.getHex(),density:this.density}}}FogExp2.prototype.isFogExp2=!0;class Fog{constructor(e,t,n){this.name="",this.color=new Color(e),this.near=void 0!==t?t:1,this.far=void 0!==n?n:1e3;}clone(){return new Fog(this.color,this.near,this.far)}toJSON(){return {type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}}Fog.prototype.isFog=!0;class Scene extends Object3D{constructor(){super(),this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}));}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.autoUpdate=e.autoUpdate,this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.background&&(t.object.background=this.background.toJSON(e)),null!==this.environment&&(t.object.environment=this.environment.toJSON(e)),null!==this.fog&&(t.object.fog=this.fog.toJSON()),t}}function InterleavedBuffer(e,t){this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=35044,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=MathUtils.generateUUID();}Scene.prototype.isScene=!0,Object.defineProperty(InterleavedBuffer.prototype,"needsUpdate",{set:function(e){!0===e&&this.version++;}}),Object.assign(InterleavedBuffer.prototype,{isInterleavedBuffer:!0,onUploadCallback:function(){},setUsage:function(e){return this.usage=e,this},copy:function(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this},copyAt:function(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;re.far||t.push({distance:s,point:_intersectPoint.clone(),uv:Triangle.getUV(_intersectPoint,_vA$1,_vB$1,_vC$1,_uvA$1,_uvB$1,_uvC$1,new Vector2),face:null,object:this});}copy(e){return super.copy(e),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function transformVertex(e,t,n,r,i,a){_alignedPosition.subVectors(e,n).addScalar(.5).multiply(r),void 0!==i?(_rotatedPosition.x=a*_alignedPosition.x-i*_alignedPosition.y,_rotatedPosition.y=i*_alignedPosition.x+a*_alignedPosition.y):_rotatedPosition.copy(_alignedPosition),e.copy(t),e.x+=_rotatedPosition.x,e.y+=_rotatedPosition.y,e.applyMatrix4(_viewWorldMatrix);}Sprite.prototype.isSprite=!0;const _v1$4=new Vector3,_v2$2=new Vector3;class LOD extends Object3D{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0;}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,n=t.length;e0){let n,r;for(n=1,r=t.length;n0){_v1$4.setFromMatrixPosition(this.matrixWorld);const n=e.ray.origin.distanceTo(_v1$4);this.getObjectForDistance(n).raycast(e,t);}}update(e){const t=this.levels;if(t.length>1){_v1$4.setFromMatrixPosition(e.matrixWorld),_v2$2.setFromMatrixPosition(this.matrixWorld);const n=_v1$4.distanceTo(_v2$2)/e.zoom;let r,i;for(t[0].object.visible=!0,r=1,i=t.length;r=t[r].distance;r++)t[r-1].object.visible=!1,t[r].object.visible=!0;for(this._currentLevel=r-1;ro)continue;h.applyMatrix4(this.matrixWorld);const d=e.ray.origin.distanceTo(h);de.far||t.push({distance:d,point:c.clone().applyMatrix4(this.matrixWorld),index:r,face:null,faceIndex:null,object:this});}}else for(let n=0,r=i.count-1;no)continue;h.applyMatrix4(this.matrixWorld);const r=e.ray.origin.distanceTo(h);re.far||t.push({distance:r,point:c.clone().applyMatrix4(this.matrixWorld),index:n,face:null,faceIndex:null,object:this});}}else n.isGeometry&&console.error("THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.");},updateMorphTargets:function(){const e=this.geometry;if(e.isBufferGeometry){const t=e.morphAttributes,n=Object.keys(t);if(n.length>0){const e=t[n[0]];if(void 0!==e){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,n=e.length;t0&&console.error("THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.");}}});const _start$1=new Vector3,_end$1=new Vector3;function LineSegments(e,t){Line.call(this,e,t),this.type="LineSegments";}LineSegments.prototype=Object.assign(Object.create(Line.prototype),{constructor:LineSegments,isLineSegments:!0,computeLineDistances:function(){const e=this.geometry;if(e.isBufferGeometry)if(null===e.index){const t=e.attributes.position,n=[];for(let e=0,r=t.count;ei.far)return;a.push({distance:l,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,object:o});}}Points.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Points,isPoints:!0,copy:function(e){return Object3D.prototype.copy.call(this,e),this.material=e.material,this.geometry=e.geometry,this},raycast:function(e,t){const n=this.geometry,r=this.matrixWorld,i=e.params.Points.threshold;if(null===n.boundingSphere&&n.computeBoundingSphere(),_sphere$3.copy(n.boundingSphere),_sphere$3.applyMatrix4(r),_sphere$3.radius+=i,!1===e.ray.intersectsSphere(_sphere$3))return;_inverseMatrix$2.copy(r).invert(),_ray$2.copy(e.ray).applyMatrix4(_inverseMatrix$2);const a=i/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a;if(n.isBufferGeometry){const i=n.index,a=n.attributes.position;if(null!==i){const n=i.array;for(let i=0,s=n.length;i0){const e=t[n[0]];if(void 0!==e){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,n=e.length;t0&&console.error("THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.");}}});class VideoTexture extends Texture{constructor(e,t,n,r,i,a,o,s,l){super(e,t,n,r,i,a,o,s,l),this.format=void 0!==o?o:1022,this.minFilter=void 0!==a?a:1006,this.magFilter=void 0!==i?i:1006,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){c.needsUpdate=!0,e.requestVideoFrameCallback(t);}));}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0);}}VideoTexture.prototype.isVideoTexture=!0;class CompressedTexture extends Texture{constructor(e,t,n,r,i,a,o,s,l,c,h,u){super(null,a,o,s,l,c,r,i,h,u),this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1;}}CompressedTexture.prototype.isCompressedTexture=!0;class CanvasTexture extends Texture{constructor(e,t,n,r,i,a,o,s,l){super(e,t,n,r,i,a,o,s,l),this.needsUpdate=!0;}}CanvasTexture.prototype.isCanvasTexture=!0;class DepthTexture extends Texture{constructor(e,t,n,r,i,a,o,s,l,c){if(1026!==(c=void 0!==c?c:1026)&&1027!==c)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===n&&1026===c&&(n=1012),void 0===n&&1027===c&&(n=1020),super(null,r,i,a,o,s,c,n,l),this.image={width:e,height:t},this.magFilter=void 0!==o?o:1003,this.minFilter=void 0!==s?s:1003,this.flipY=!1,this.generateMipmaps=!1;}}DepthTexture.prototype.isDepthTexture=!0;class CircleGeometry extends BufferGeometry{constructor(e=1,t=8,n=0,r=2*Math.PI){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:n,thetaLength:r},t=Math.max(3,t);const i=[],a=[],o=[],s=[],l=new Vector3,c=new Vector2;a.push(0,0,0),o.push(0,0,1),s.push(.5,.5);for(let i=0,h=3;i<=t;i++,h+=3){const u=n+i/t*r;l.x=e*Math.cos(u),l.y=e*Math.sin(u),a.push(l.x,l.y,l.z),o.push(0,0,1),c.x=(a[h]/e+1)/2,c.y=(a[h+1]/e+1)/2,s.push(c.x,c.y);}for(let e=1;e<=t;e++)i.push(e,e+1,0);this.setIndex(i),this.setAttribute("position",new Float32BufferAttribute(a,3)),this.setAttribute("normal",new Float32BufferAttribute(o,3)),this.setAttribute("uv",new Float32BufferAttribute(s,2));}}class CylinderGeometry extends BufferGeometry{constructor(e=1,t=1,n=1,r=8,i=1,a=!1,o=0,s=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:i,openEnded:a,thetaStart:o,thetaLength:s};const l=this;r=Math.floor(r),i=Math.floor(i);const c=[],h=[],u=[],d=[];let p=0;const m=[],f=n/2;let g=0;function v(n){const i=p,a=new Vector2,m=new Vector3;let v=0;const _=!0===n?e:t,y=!0===n?1:-1;for(let e=1;e<=r;e++)h.push(0,f*y,0),u.push(0,y,0),d.push(.5,.5),p++;const x=p;for(let e=0;e<=r;e++){const t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=_*i,m.y=f*y,m.z=_*n,h.push(m.x,m.y,m.z),u.push(0,y,0),a.x=.5*n+.5,a.y=.5*i*y+.5,d.push(a.x,a.y),p++;}for(let e=0;e0&&v(!0),t>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new Float32BufferAttribute(h,3)),this.setAttribute("normal",new Float32BufferAttribute(u,3)),this.setAttribute("uv",new Float32BufferAttribute(d,2));}}class ConeGeometry extends CylinderGeometry{constructor(e=1,t=1,n=8,r=1,i=!1,a=0,o=2*Math.PI){super(0,e,t,n,r,i,a,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:r,openEnded:i,thetaStart:a,thetaLength:o};}}class PolyhedronGeometry extends BufferGeometry{constructor(e,t,n=1,r=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:r};const i=[],a=[];function o(e,t,n,r){const i=r+1,a=[];for(let r=0;r<=i;r++){a[r]=[];const o=e.clone().lerp(n,r/i),s=t.clone().lerp(n,r/i),l=i-r;for(let e=0;e<=l;e++)a[r][e]=0===e&&r===i?o:o.clone().lerp(s,e/l);}for(let e=0;e.9&&o<.1&&(t<.2&&(a[e+0]+=1),n<.2&&(a[e+2]+=1),r<.2&&(a[e+4]+=1));}}();}(),this.setAttribute("position",new Float32BufferAttribute(i,3)),this.setAttribute("normal",new Float32BufferAttribute(i.slice(),3)),this.setAttribute("uv",new Float32BufferAttribute(a,2)),0===r?this.computeVertexNormals():this.normalizeNormals();}}class DodecahedronGeometry extends PolyhedronGeometry{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,r=1/n;super([-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,-r,-n,0,-r,n,0,r,-n,0,r,n,-r,-n,0,-r,n,0,r,-n,0,r,n,0,-n,0,-r,n,0,-r,-n,0,r,n,0,r],[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],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t};}}const _v0$2=new Vector3,_v1$5=new Vector3,_normal$1=new Vector3,_triangle=new Triangle;class EdgesGeometry extends BufferGeometry{constructor(e,t){if(super(),this.type="EdgesGeometry",this.parameters={thresholdAngle:t},t=void 0!==t?t:1,!0===e.isGeometry)return void console.error("THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.");const n=Math.pow(10,4),r=Math.cos(MathUtils.DEG2RAD*t),i=e.getIndex(),a=e.getAttribute("position"),o=i?i.count:a.count,s=[0,0,0],l=["a","b","c"],c=new Array(3),h={},u=[];for(let e=0;e80*n){s=c=e[0],l=h=e[1];for(let t=n;tc&&(c=u),d>h&&(h=d);p=Math.max(c-s,h-l),p=0!==p?1/p:0;}return earcutLinked(a,o,n,s,l,p),o}};function linkedList(e,t,n,r,i){let a,o;if(i===signedArea(e,t,n,r)>0)for(a=t;a=t;a-=r)o=insertNode(a,e[a],e[a+1],o);return o&&equals(o,o.next)&&(removeNode(o),o=o.next),o}function filterPoints(e,t){if(!e)return e;t||(t=e);let n,r=e;do{if(n=!1,r.steiner||!equals(r,r.next)&&0!==area(r.prev,r,r.next))r=r.next;else {if(removeNode(r),r=t=r.prev,r===r.next)break;n=!0;}}while(n||r!==t);return t}function earcutLinked(e,t,n,r,i,a,o){if(!e)return;!o&&a&&indexCurve(e,r,i,a);let s,l,c=e;for(;e.prev!==e.next;)if(s=e.prev,l=e.next,a?isEarHashed(e,r,i,a):isEar(e))t.push(s.i/n),t.push(e.i/n),t.push(l.i/n),removeNode(e),e=l.next,c=l.next;else if((e=l)===c){o?1===o?earcutLinked(e=cureLocalIntersections(filterPoints(e),t,n),t,n,r,i,a,2):2===o&&splitEarcut(e,t,n,r,i,a):earcutLinked(filterPoints(e),t,n,r,i,a,1);break}}function isEar(e){const t=e.prev,n=e,r=e.next;if(area(t,n,r)>=0)return !1;let i=e.next.next;for(;i!==e.prev;){if(pointInTriangle(t.x,t.y,n.x,n.y,r.x,r.y,i.x,i.y)&&area(i.prev,i,i.next)>=0)return !1;i=i.next;}return !0}function isEarHashed(e,t,n,r){const i=e.prev,a=e,o=e.next;if(area(i,a,o)>=0)return !1;const s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,h=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,u=zOrder(s,l,t,n,r),d=zOrder(c,h,t,n,r);let p=e.prevZ,m=e.nextZ;for(;p&&p.z>=u&&m&&m.z<=d;){if(p!==e.prev&&p!==e.next&&pointInTriangle(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return !1;if(p=p.prevZ,m!==e.prev&&m!==e.next&&pointInTriangle(i.x,i.y,a.x,a.y,o.x,o.y,m.x,m.y)&&area(m.prev,m,m.next)>=0)return !1;m=m.nextZ;}for(;p&&p.z>=u;){if(p!==e.prev&&p!==e.next&&pointInTriangle(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return !1;p=p.prevZ;}for(;m&&m.z<=d;){if(m!==e.prev&&m!==e.next&&pointInTriangle(i.x,i.y,a.x,a.y,o.x,o.y,m.x,m.y)&&area(m.prev,m,m.next)>=0)return !1;m=m.nextZ;}return !0}function cureLocalIntersections(e,t,n){let r=e;do{const i=r.prev,a=r.next.next;!equals(i,a)&&intersects(i,r,r.next,a)&&locallyInside(i,a)&&locallyInside(a,i)&&(t.push(i.i/n),t.push(r.i/n),t.push(a.i/n),removeNode(r),removeNode(r.next),r=e=a),r=r.next;}while(r!==e);return filterPoints(r)}function splitEarcut(e,t,n,r,i,a){let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&isValidDiagonal(o,e)){let s=splitPolygon(o,e);return o=filterPoints(o,o.next),s=filterPoints(s,s.next),earcutLinked(o,t,n,r,i,a),void earcutLinked(s,t,n,r,i,a)}e=e.next;}o=o.next;}while(o!==e)}function eliminateHoles(e,t,n,r){const i=[];let a,o,s,l,c;for(a=0,o=t.length;a=n.next.y&&n.next.y!==n.y){const e=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(e<=r&&e>o){if(o=e,e===r){if(i===n.y)return n;if(i===n.next.y)return n.next}a=n.x=n.x&&n.x>=l&&r!==n.x&&pointInTriangle(ia.x||n.x===a.x&§orContainsSector(a,n)))&&(a=n,u=h)),n=n.next;}while(n!==s);return a}function sectorContainsSector(e,t){return area(e.prev,e,t.prev)<0&&area(t.next,e,e.next)<0}function indexCurve(e,t,n,r){let i=e;do{null===i.z&&(i.z=zOrder(i.x,i.y,t,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==e);i.prevZ.nextZ=null,i.prevZ=null,sortLinked(i);}function sortLinked(e){let t,n,r,i,a,o,s,l,c=1;do{for(n=e,e=null,a=null,o=0;n;){for(o++,r=n,s=0,t=0;t0||l>0&&r;)0!==s&&(0===l||!r||n.z<=r.z)?(i=n,n=n.nextZ,s--):(i=r,r=r.nextZ,l--),a?a.nextZ=i:e=i,i.prevZ=a,a=i;n=r;}a.nextZ=null,c*=2;}while(o>1);return e}function zOrder(e,t,n,r,i){return (e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function getLeftmost(e){let t=e,n=e;do{(t.x=0&&(e-o)*(r-s)-(n-o)*(t-s)>=0&&(n-o)*(a-s)-(i-o)*(r-s)>=0}function isValidDiagonal(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!intersectsPolygon(e,t)&&(locallyInside(e,t)&&locallyInside(t,e)&&middleInside(e,t)&&(area(e.prev,e,t.prev)||area(e,t.prev,t))||equals(e,t)&&area(e.prev,e,e.next)>0&&area(t.prev,t,t.next)>0)}function area(e,t,n){return (t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function equals(e,t){return e.x===t.x&&e.y===t.y}function intersects(e,t,n,r){const i=sign(area(e,t,n)),a=sign(area(e,t,r)),o=sign(area(n,r,e)),s=sign(area(n,r,t));return i!==a&&o!==s||(!(0!==i||!onSegment(e,n,t))||(!(0!==a||!onSegment(e,r,t))||(!(0!==o||!onSegment(n,e,r))||!(0!==s||!onSegment(n,t,r)))))}function onSegment(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function sign(e){return e>0?1:e<0?-1:0}function intersectsPolygon(e,t){let n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&intersects(n,n.next,e,t))return !0;n=n.next;}while(n!==e);return !1}function locallyInside(e,t){return area(e.prev,e,e.next)<0?area(e,t,e.next)>=0&&area(e,e.prev,t)>=0:area(e,t,e.prev)<0||area(e,e.next,t)<0}function middleInside(e,t){let n=e,r=!1;const i=(e.x+t.x)/2,a=(e.y+t.y)/2;do{n.y>a!=n.next.y>a&&n.next.y!==n.y&&i<(n.next.x-n.x)*(a-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next;}while(n!==e);return r}function splitPolygon(e,t){const n=new Node(e.i,e.x,e.y),r=new Node(t.i,t.x,t.y),i=e.next,a=t.prev;return e.next=t,t.prev=e,n.next=i,i.prev=n,r.next=n,n.prev=r,a.next=r,r.prev=a,r}function insertNode(e,t,n,r){const i=new Node(e,t,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function removeNode(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ);}function Node(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function signedArea(e,t,n,r){let i=0;for(let a=t,o=n-r;a2&&e[t-1].equals(e[0])&&e.pop();}function addContour(e,t){for(let n=0;nNumber.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=t.x-s/u,m=t.y+o/u,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(o*c-s*l);r=p+o*f-e.x,i=m+s*f-e.y;const g=r*r+i*i;if(g<=2)return new Vector2(r,i);a=Math.sqrt(g/2);}else {let e=!1;o>Number.EPSILON?l>Number.EPSILON&&(e=!0):o<-Number.EPSILON?l<-Number.EPSILON&&(e=!0):Math.sign(s)===Math.sign(c)&&(e=!0),e?(r=-s,i=o,a=Math.sqrt(h)):(r=o,i=s,a=Math.sqrt(h/2));}return new Vector2(r/a,i/a)}const P=[];for(let e=0,t=E.length,n=t-1,r=e+1;e=0;e--){const t=e/p,n=h*Math.cos(t*Math.PI/2),r=u*Math.sin(t*Math.PI/2)+d;for(let e=0,t=E.length;e=0;){const r=n;let i=n-1;i<0&&(i=e.length-1);for(let e=0,n=s+2*p;e=0?(e(r-s,p,h),u.subVectors(c,h)):(e(r+s,p,h),u.subVectors(h,c)),p-s>=0?(e(r,p-s,h),d.subVectors(c,h)):(e(r,p+s,h),d.subVectors(h,c)),l.crossVectors(u,d).normalize(),a.push(l.x,l.y,l.z),o.push(r,p);}}for(let e=0;e0)&&d.push(t,i,l),(e!==n-1||s=r)){l.push(t.times[e]);for(let n=0;na.tracks[e].times[0]&&(s=a.tracks[e].times[0]);for(let e=0;e=r.times[u]){const e=u*l+s,t=e+l-s;d=AnimationUtils.arraySlice(r.values,e,t);}else {const e=r.createInterpolant(),t=s,n=l-s;e.evaluate(a),d=AnimationUtils.arraySlice(e.resultBuffer,t,n);}if("quaternion"===i){(new Quaternion).fromArray(d).normalize().conjugate().toArray(d);}const p=o.times.length;for(let e=0;e=i)break e;{const o=t[1];e=i)break t}a=n,n=0;}}for(;n>>1;et;)--a;if(++a,0!==i||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);const e=this.getValueSize();this.times=AnimationUtils.arraySlice(n,i,a),this.values=AnimationUtils.arraySlice(this.values,i*e,a*e);}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,r=this.values,i=n.length;0===i&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let t=0;t!==i;t++){const r=n[t];if("number"==typeof r&&isNaN(r)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,r),e=!1;break}if(null!==a&&a>r){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,r,a),e=!1;break}a=r;}if(void 0!==r&&AnimationUtils.isTypedArray(r))for(let t=0,n=r.length;t!==n;++t){const n=r[t];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,n),e=!1;break}}return e}optimize(){const e=AnimationUtils.arraySlice(this.times),t=AnimationUtils.arraySlice(this.values),n=this.getValueSize(),r=2302===this.getInterpolation(),i=e.length-1;let a=1;for(let o=1;o0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a;}return a!==e.length?(this.times=AnimationUtils.arraySlice(e,0,a),this.values=AnimationUtils.arraySlice(t,0,a*n)):(this.times=e,this.values=t),this}clone(){const e=AnimationUtils.arraySlice(this.times,0),t=AnimationUtils.arraySlice(this.values,0),n=new(0,this.constructor)(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}}KeyframeTrack.prototype.TimeBufferType=Float32Array,KeyframeTrack.prototype.ValueBufferType=Float32Array,KeyframeTrack.prototype.DefaultInterpolation=2301;class BooleanKeyframeTrack extends KeyframeTrack{}BooleanKeyframeTrack.prototype.ValueTypeName="bool",BooleanKeyframeTrack.prototype.ValueBufferType=Array,BooleanKeyframeTrack.prototype.DefaultInterpolation=2300,BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0,BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;class ColorKeyframeTrack extends KeyframeTrack{}ColorKeyframeTrack.prototype.ValueTypeName="color";class NumberKeyframeTrack extends KeyframeTrack{}function QuaternionLinearInterpolant(e,t,n,r){Interpolant.call(this,e,t,n,r);}NumberKeyframeTrack.prototype.ValueTypeName="number",QuaternionLinearInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:QuaternionLinearInterpolant,interpolate_:function(e,t,n,r){const i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t);let l=e*o;for(let e=l+o;l!==e;l+=4)Quaternion.slerpFlat(i,0,a,l-o,a,l,s);return i}});class QuaternionKeyframeTrack extends KeyframeTrack{InterpolantFactoryMethodLinear(e){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),e)}}QuaternionKeyframeTrack.prototype.ValueTypeName="quaternion",QuaternionKeyframeTrack.prototype.DefaultInterpolation=2301,QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;class StringKeyframeTrack extends KeyframeTrack{}StringKeyframeTrack.prototype.ValueTypeName="string",StringKeyframeTrack.prototype.ValueBufferType=Array,StringKeyframeTrack.prototype.DefaultInterpolation=2300,StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0,StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;class VectorKeyframeTrack extends KeyframeTrack{}VectorKeyframeTrack.prototype.ValueTypeName="vector";class AnimationClip{constructor(e,t=-1,n,r=2500){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=MathUtils.generateUUID(),this.duration<0&&this.resetDuration();}static parse(e){const t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(parseKeyframeTrack(n[e]).scale(r));const i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i}static toJSON(e){const t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,r=n.length;e!==r;++e)t.push(KeyframeTrack.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){const i=t.length,a=[];for(let e=0;e1){const e=a[1];let t=r[e];t||(r[e]=t=[]),t.push(n);}}const a=[];for(const e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(e,t,n,r,i){if(0!==n.length){const a=[],o=[];AnimationUtils.flattenJSON(n,a,o,r),0!==a.length&&i.push(new e(t,a,o));}},r=[],i=e.name||"default",a=e.fps||30,o=e.blendMode;let s=e.length||-1;const l=e.hierarchy||[];for(let e=0;e0||0===e.search(/^data\:image\/jpeg/);i.format=r?1022:1023,i.needsUpdate=!0,void 0!==t&&t(i);}),n,r),i}}),Object.assign(Curve.prototype,{getPoint:function(){return console.warn("THREE.Curve: .getPoint() not implemented."),null},getPointAt:function(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)},getPoints:function(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t},getSpacedPoints:function(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t},getLength:function(){const e=this.getLengths();return e[e.length-1]},getLengths:function(e){if(void 0===e&&(e=this.arcLengthDivisions),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,r=this.getPoint(0),i=0;t.push(0);for(let a=1;a<=e;a++)n=this.getPoint(a/e),i+=n.distanceTo(r),t.push(i),r=n;return this.cacheArcLengths=t,t},updateArcLengths:function(){this.needsUpdate=!0,this.getLengths();},getUtoTmapping:function(e,t){const n=this.getLengths();let r=0;const i=n.length;let a;a=t||e*n[i-1];let o,s=0,l=i-1;for(;s<=l;)if(r=Math.floor(s+(l-s)/2),o=n[r]-a,o<0)s=r+1;else {if(!(o>0)){l=r;break}l=r-1;}if(r=l,n[r]===a)return r/(i-1);const c=n[r];return (r+(a-c)/(n[r+1]-c))/(i-1)},getTangent:function(e,t){let n=e-1e-4,r=e+1e-4;n<0&&(n=0),r>1&&(r=1);const i=this.getPoint(n),a=this.getPoint(r),o=t||(i.isVector2?new Vector2:new Vector3);return o.copy(a).sub(i).normalize(),o},getTangentAt:function(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)},computeFrenetFrames:function(e,t){const n=new Vector3,r=[],i=[],a=[],o=new Vector3,s=new Matrix4;for(let t=0;t<=e;t++){const n=t/e;r[t]=this.getTangentAt(n,new Vector3),r[t].normalize();}i[0]=new Vector3,a[0]=new Vector3;let l=Number.MAX_VALUE;const c=Math.abs(r[0].x),h=Math.abs(r[0].y),u=Math.abs(r[0].z);c<=l&&(l=c,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),u<=l&&n.set(0,0,1),o.crossVectors(r[0],n).normalize(),i[0].crossVectors(r[0],o),a[0].crossVectors(r[0],i[0]);for(let t=1;t<=e;t++){if(i[t]=i[t-1].clone(),a[t]=a[t-1].clone(),o.crossVectors(r[t-1],r[t]),o.length()>Number.EPSILON){o.normalize();const e=Math.acos(MathUtils.clamp(r[t-1].dot(r[t]),-1,1));i[t].applyMatrix4(s.makeRotationAxis(o,e));}a[t].crossVectors(r[t],i[t]);}if(!0===t){let t=Math.acos(MathUtils.clamp(i[0].dot(i[e]),-1,1));t/=e,r[0].dot(o.crossVectors(i[0],i[e]))>0&&(t=-t);for(let n=1;n<=e;n++)i[n].applyMatrix4(s.makeRotationAxis(r[n],t*n)),a[n].crossVectors(r[n],i[n]);}return {tangents:r,normals:i,binormals:a}},clone:function(){return (new this.constructor).copy(this)},copy:function(e){return this.arcLengthDivisions=e.arcLengthDivisions,this},toJSON:function(){const e={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e},fromJSON:function(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}});class EllipseCurve extends Curve{constructor(e=0,t=0,n=1,r=1,i=0,a=2*Math.PI,o=!1,s=0){super(),this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=r,this.aStartAngle=i,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s;}getPoint(e,t){const n=t||new Vector2,r=2*Math.PI;let i=this.aEndAngle-this.aStartAngle;const a=Math.abs(i)r;)i-=r;i0?0:(Math.floor(Math.abs(l)/i)+1)*i:0===c&&l===i-1&&(l=i-2,c=1),this.closed||l>0?o=r[(l-1)%i]:(tmp.subVectors(r[0],r[1]).add(r[0]),o=tmp);const h=r[l%i],u=r[(l+1)%i];if(this.closed||l+2r.length-2?r.length-1:a+1],h=r[a>r.length-3?r.length-1:a+2];return n.set(CatmullRom(o,s.x,l.x,c.x,h.x),CatmullRom(o,s.y,l.y,c.y,h.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=t){const e=n[r]-t,i=this.curves[r],a=i.getLength(),o=0===a?0:1-e/a;return i.getPointAt(o)}r++;}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths();}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let n=0,r=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){const e=l.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y);}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Shape extends Path{constructor(e){super(e),this.uuid=MathUtils.generateUUID(),this.type="Shape",this.holes=[];}getPointsHoles(e){const t=[];for(let n=0,r=this.holes.length;n0:r.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const i=e.uniforms[t];switch(r.uniforms[t]={},i.type){case"t":r.uniforms[t].value=n(i.value);break;case"c":r.uniforms[t].value=(new Color).setHex(i.value);break;case"v2":r.uniforms[t].value=(new Vector2).fromArray(i.value);break;case"v3":r.uniforms[t].value=(new Vector3).fromArray(i.value);break;case"v4":r.uniforms[t].value=(new Vector4).fromArray(i.value);break;case"m3":r.uniforms[t].value=(new Matrix3).fromArray(i.value);break;case"m4":r.uniforms[t].value=(new Matrix4).fromArray(i.value);break;default:r.uniforms[t].value=i.value;}}if(void 0!==e.defines&&(r.defines=e.defines),void 0!==e.vertexShader&&(r.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(r.fragmentShader=e.fragmentShader),void 0!==e.extensions)for(const t in e.extensions)r.extensions[t]=e.extensions[t];if(void 0!==e.shading&&(r.flatShading=1===e.shading),void 0!==e.size&&(r.size=e.size),void 0!==e.sizeAttenuation&&(r.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(r.map=n(e.map)),void 0!==e.matcap&&(r.matcap=n(e.matcap)),void 0!==e.alphaMap&&(r.alphaMap=n(e.alphaMap)),void 0!==e.bumpMap&&(r.bumpMap=n(e.bumpMap)),void 0!==e.bumpScale&&(r.bumpScale=e.bumpScale),void 0!==e.normalMap&&(r.normalMap=n(e.normalMap)),void 0!==e.normalMapType&&(r.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),r.normalScale=(new Vector2).fromArray(t);}return void 0!==e.displacementMap&&(r.displacementMap=n(e.displacementMap)),void 0!==e.displacementScale&&(r.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(r.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(r.roughnessMap=n(e.roughnessMap)),void 0!==e.metalnessMap&&(r.metalnessMap=n(e.metalnessMap)),void 0!==e.emissiveMap&&(r.emissiveMap=n(e.emissiveMap)),void 0!==e.emissiveIntensity&&(r.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(r.specularMap=n(e.specularMap)),void 0!==e.envMap&&(r.envMap=n(e.envMap)),void 0!==e.envMapIntensity&&(r.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(r.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(r.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(r.lightMap=n(e.lightMap)),void 0!==e.lightMapIntensity&&(r.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(r.aoMap=n(e.aoMap)),void 0!==e.aoMapIntensity&&(r.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(r.gradientMap=n(e.gradientMap)),void 0!==e.clearcoatMap&&(r.clearcoatMap=n(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(r.clearcoatRoughnessMap=n(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(r.clearcoatNormalMap=n(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(r.clearcoatNormalScale=(new Vector2).fromArray(e.clearcoatNormalScale)),void 0!==e.transmission&&(r.transmission=e.transmission),void 0!==e.transmissionMap&&(r.transmissionMap=n(e.transmissionMap)),r}setTextures(e){return this.textures=e,this}}const LoaderUtils={decodeText:function(e){if("undefined"!=typeof TextDecoder)return (new TextDecoder).decode(e);let t="";for(let n=0,r=e.length;n0){const n=new LoadingManager(t);i=new ImageLoader(n),i.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;tNumber.EPSILON){if(l<0&&(n=t[a],s=-s,o=t[i],l=-l),e.yo.y)continue;if(e.y===n.y){if(e.x===n.x)return !0}else {const t=l*(e.x-n.x)-s*(e.y-n.y);if(0===t)return !0;if(t<0)continue;r=!r;}}else {if(e.y!==n.y)continue;if(o.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=o.x)return !0}}return r}const i=ShapeUtils.isClockWise,a=this.subPaths;if(0===a.length)return [];if(!0===t)return n(a);let o,s,l;const c=[];if(1===a.length)return s=a[0],l=new Shape,l.curves=s.curves,c.push(l),c;let h=!i(a[0].getPoints());h=e?!h:h;const u=[],d=[];let p,m,f=[],g=0;d[g]=void 0,f[g]=[];for(let t=0,n=a.length;t1){let e=!1;const t=[];for(let e=0,t=d.length;e0&&(e||(f=u));}for(let e=0,t=d.length;e0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){const e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0;}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e);}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r];}_slerp(e,t,n,r){Quaternion.slerpFlat(e,t,e,t,e,n,r);}_slerpAdditive(e,t,n,r,i){const a=this._workIndex*i;Quaternion.multiplyQuaternionsFlat(e,a,e,t,e,n),Quaternion.slerpFlat(e,t,e,t,e,a,r);}_lerp(e,t,n,r,i){const a=1-r;for(let o=0;o!==i;++o){const i=t+o;e[i]=e[i]*a+e[n+o]*r;}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){const i=t+a;e[i]=e[i]+e[n+a]*r;}}}const _RESERVED_CHARS_RE="\\[\\]\\.:\\/",_reservedRe=new RegExp("[\\[\\]\\.:\\/]","g"),_wordChar="[^\\[\\]\\.:\\/]",_wordCharOrDot="[^"+"\\[\\]\\.:\\/".replace("\\.","")+"]",_directoryRe=/((?:WC+[\/:])*)/.source.replace("WC",_wordChar),_nodeRe=/(WCOD+)?/.source.replace("WCOD",_wordCharOrDot),_objectRe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",_wordChar),_propertyRe=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",_wordChar),_trackRe=new RegExp("^"+_directoryRe+_nodeRe+_objectRe+_propertyRe+"$"),_supportedObjectNames=["material","materials","bones"];function Composite(e,t,n){const r=n||PropertyBinding.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r);}function PropertyBinding(e,t,n){this.path=t,this.parsedPath=n||PropertyBinding.parseTrackName(t),this.node=PropertyBinding.findNode(e,this.parsedPath.nodeName)||e,this.rootNode=e;}Object.assign(Composite.prototype,{getValue:function(e,t){this.bind();const n=this._targetGroup.nCachedObjects_,r=this._bindings[n];void 0!==r&&r.getValue(e,t);},setValue:function(e,t){const n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t);},bind:function(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind();},unbind:function(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind();}}),Object.assign(PropertyBinding,{Composite:Composite,create:function(e,t,n){return e&&e.isAnimationObjectGroup?new PropertyBinding.Composite(e,t,n):new PropertyBinding(e,t,n)},sanitizeNodeName:function(e){return e.replace(/\s/g,"_").replace(_reservedRe,"")},parseTrackName:function(e){const t=_trackRe.exec(e);if(!t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==r&&-1!==r){const e=n.nodeName.substring(r+1);-1!==_supportedObjectNames.indexOf(e)&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e);}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n},findNode:function(e,t){if(!t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(void 0!==n)return n}if(e.children){const n=function(e){for(let r=0;r=i){const a=i++,c=e[a];t[c.uuid]=l,e[l]=c,t[s]=a,e[a]=o;for(let e=0,t=r;e!==t;++e){const t=n[e],r=t[a],i=t[l];t[l]=r,t[a]=i;}}}this.nCachedObjects_=i;}uncache(){const e=this._objects,t=this._indicesByUUID,n=this._bindings,r=n.length;let i=this.nCachedObjects_,a=e.length;for(let o=0,s=arguments.length;o!==s;++o){const s=arguments[o].uuid,l=t[s];if(void 0!==l)if(delete t[s],l0&&(t[o.uuid]=l),e[l]=o,e.pop();for(let e=0,t=r;e!==t;++e){const t=n[e];t[l]=t[i],t.pop();}}}this.nCachedObjects_=i;}subscribe_(e,t){const n=this._bindingsIndicesByPath;let r=n[e];const i=this._bindings;if(void 0!==r)return i[r];const a=this._paths,o=this._parsedPaths,s=this._objects,l=s.length,c=this.nCachedObjects_,h=new Array(l);r=i.length,n[e]=r,a.push(e),o.push(t),i.push(h);for(let n=c,r=s.length;n!==r;++n){const r=s[n];h[n]=new PropertyBinding(r,e,t);}return h}unsubscribe_(e){const t=this._bindingsIndicesByPath,n=t[e];if(void 0!==n){const r=this._paths,i=this._parsedPaths,a=this._bindings,o=a.length-1,s=a[o];t[e[o]]=n,a[n]=s,a.pop(),i[n]=i[o],i.pop(),r[n]=r[o],r.pop();}}}AnimationObjectGroup.prototype.isAnimationObjectGroup=!0;class AnimationAction{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;const i=t.tracks,a=i.length,o=new Array(a),s={endingStart:2400,endingEnd:2400};for(let e=0;e!==a;++e){const t=i[e].createInterpolant(null);o[e]=t,t.settings=s;}this._interpolantSettings=s,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0;}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n){if(e.fadeOut(t),this.fadeIn(t),n){const n=this._clip.duration,r=e._clip.duration,i=r/n,a=n/r;e.warp(1,i,t),this.warp(a,1,t);}return this}crossFadeTo(e,t,n){return e.crossFadeFrom(this,t,n)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){const r=this._mixer,i=r.time,a=this.timeScale;let o=this._timeScaleInterpolant;null===o&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);const s=o.parameterPositions,l=o.sampleValues;return s[0]=i,s[1]=i+n,l[0]=e/a,l[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled)return void this._updateWeight(e);const i=this._startTime;if(null!==i){const r=(e-i)*n;if(r<0||0===n)return;this._startTime=null,t=n*r;}t*=this._updateTimeScale(e);const a=this._updateTime(t),o=this._updateWeight(e);if(o>0){const e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case 2501:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case 2500:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o);}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const n=this._weightInterpolant;if(null!==n){const r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),0===r&&(this.enabled=!1));}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){t*=n.evaluate(e)[0],e>n.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t);}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,n=this.loop;let r=this.time+e,i=this._loopCount;const a=2202===n;if(0===e)return -1===i?r:a&&1==(1&i)?t-r:r;if(2200===n){-1===i&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(r>=t)r=t;else {if(!(r<0)){this.time=r;break e}r=0;}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1});}}else {if(-1===i&&(e>=0?(i=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),r>=t||r<0){const n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);const o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else {if(1===o){const t=e<0;this._setEndings(t,!t,a);}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n});}}else this.time=r;if(a&&1==(1&i))return t-r}return r}_setEndings(e,t,n){const r=this._interpolantSettings;n?(r.endingStart=2401,r.endingEnd=2401):(r.endingStart=e?this.zeroSlopeAtStart?2401:2400:2402,r.endingEnd=t?this.zeroSlopeAtEnd?2401:2400:2402);}_scheduleFading(e,t,n){const r=this._mixer,i=r.time;let a=this._weightInterpolant;null===a&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}}class AnimationMixer extends EventDispatcher{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1;}_bindAction(e,t){const n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,l=this._bindingsByRootAndName;let c=l[s];void 0===c&&(c={},l[s]=c);for(let e=0;e!==i;++e){const i=r[e],l=i.name;let h=c[l];if(void 0!==h)a[e]=h;else {if(h=a[e],void 0!==h){null===h._cacheIndex&&(++h.referenceCount,this._addInactiveBinding(h,s,l));continue}const r=t&&t._propertyBindings[e].binding.parsedPath;h=new PropertyMixer(PropertyBinding.create(n,l,r),i.ValueTypeName,i.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,s,l),a[e]=h;}o[e].resultBuffer=h.buffer;}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t);}const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0==n.useCount++&&(this._lendBinding(n),n.saveOriginalState());}this._lendAction(e);}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0==--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n));}this._takeBackAction(e);}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}};}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o){t[o]._update(r,e,i,a);}const o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;ethis.max.x||e.ythis.max.y)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return void 0===t&&(console.warn("THREE.Box2: .getParameter() target is now required"),t=new Vector2),t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return !(e.max.xthis.max.x||e.max.ythis.max.y)}clampPoint(e,t){return void 0===t&&(console.warn("THREE.Box2: .clampPoint() target is now required"),t=new Vector2),t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return _vector$8.copy(e).clamp(this.min,this.max).sub(e).length()}intersect(e){return this.min.max(e.min),this.max.min(e.max),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}Box2.prototype.isBox2=!0;const _startP=new Vector3,_startEnd=new Vector3;class Line3{constructor(e=new Vector3,t=new Vector3){this.start=e,this.end=t;}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return void 0===e&&(console.warn("THREE.Line3: .getCenter() target is now required"),e=new Vector3),e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return void 0===e&&(console.warn("THREE.Line3: .delta() target is now required"),e=new Vector3),e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return void 0===t&&(console.warn("THREE.Line3: .at() target is now required"),t=new Vector3),this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){_startP.subVectors(e,this.start),_startEnd.subVectors(this.end,this.start);const n=_startEnd.dot(_startEnd);let r=_startEnd.dot(_startP)/n;return t&&(r=MathUtils.clamp(r,0,1)),r}closestPointToPoint(e,t,n){const r=this.closestPointToPointParameter(e,t);return void 0===n&&(console.warn("THREE.Line3: .closestPointToPoint() target is now required"),n=new Vector3),this.delta(n).multiplyScalar(r).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return (new this.constructor).copy(this)}}function ImmediateRenderObject(e){Object3D.call(this),this.material=e,this.render=function(){},this.hasPositions=!1,this.hasNormals=!1,this.hasColors=!1,this.hasUvs=!1,this.positionArray=null,this.normalArray=null,this.colorArray=null,this.uvArray=null,this.count=0;}ImmediateRenderObject.prototype=Object.create(Object3D.prototype),ImmediateRenderObject.prototype.constructor=ImmediateRenderObject,ImmediateRenderObject.prototype.isImmediateRenderObject=!0;const _vector$9=new Vector3;class SpotLightHelper extends Object3D{constructor(e,t){super(),this.light=e,this.light.updateMatrixWorld(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=t;const n=new BufferGeometry,r=[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(let e=0,t=1,n=32;e.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else {_axis.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(_axis,t);}}setLength(e,t=.2*e,n=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix();}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e);}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}}class AxesHelper extends LineSegments{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=new BufferGeometry;n.setAttribute("position",new Float32BufferAttribute(t,3)),n.setAttribute("color",new Float32BufferAttribute([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(n,new LineBasicMaterial({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper";}}const _floatView=new Float32Array(1),_int32View=new Int32Array(_floatView.buffer),DataUtils={toHalfFloat:function(e){_floatView[0]=e;const t=_int32View[0];let n=t>>16&32768,r=t>>12&2047;const i=t>>23&255;return i<103?n:i>142?(n|=31744,n|=(255==i?0:1)&&8388607&t,n):i<113?(r|=2048,n|=(r>>114-i)+(r>>113-i&1),n):(n|=i-112<<10|r>>1,n+=1&r,n)}},LOD_MIN=4,LOD_MAX=8,SIZE_MAX=Math.pow(2,8),EXTRA_LOD_SIGMA=[.125,.215,.35,.446,.526,.582],TOTAL_LODS=5+EXTRA_LOD_SIGMA.length,MAX_SAMPLES=20,ENCODINGS={3e3:0,3001:1,3002:2,3004:3,3005:4,3006:5,3007:6},backgroundMaterial=new MeshBasicMaterial({side:1,depthWrite:!1,depthTest:!1}),backgroundBox=new Mesh(new BoxGeometry,backgroundMaterial),_flatCamera=new OrthographicCamera,{_lodPlanes:_lodPlanes,_sizeLods:_sizeLods,_sigmas:_sigmas}=_createPlanes(),_clearColor=new Color;let _oldTarget=null;const PHI=(1+Math.sqrt(5))/2,INV_PHI=1/PHI,_axisDirections=[new Vector3(1,1,1),new Vector3(-1,1,1),new Vector3(1,1,-1),new Vector3(-1,1,-1),new Vector3(0,PHI,INV_PHI),new Vector3(0,PHI,-INV_PHI),new Vector3(INV_PHI,0,PHI),new Vector3(-INV_PHI,0,PHI),new Vector3(PHI,INV_PHI,0),new Vector3(-PHI,INV_PHI,0)];function convertLinearToRGBE(e){const t=Math.max(e.r,e.g,e.b),n=Math.min(Math.max(Math.ceil(Math.log2(t)),-128),127);e.multiplyScalar(Math.pow(2,-n));return (n+128)/255}class PMREMGenerator{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._blurMaterial=_getBlurShader(20),this._equirectShader=null,this._cubemapShader=null,this._compileMaterial(this._blurMaterial);}fromScene(e,t=0,n=.1,r=100){_oldTarget=this._renderer.getRenderTarget();const i=this._allocateTargets();return this._sceneToCubeUV(e,n,r,i),t>0&&this._blur(i,0,0,t),this._applyPMREM(i),this._cleanup(i),i}fromEquirectangular(e){return this._fromTexture(e)}fromCubemap(e){return this._fromTexture(e)}compileCubemapShader(){null===this._cubemapShader&&(this._cubemapShader=_getCubemapShader(),this._compileMaterial(this._cubemapShader));}compileEquirectangularShader(){null===this._equirectShader&&(this._equirectShader=_getEquirectShader(),this._compileMaterial(this._equirectShader));}dispose(){this._blurMaterial.dispose(),null!==this._cubemapShader&&this._cubemapShader.dispose(),null!==this._equirectShader&&this._equirectShader.dispose();for(let e=0;e<_lodPlanes.length;e++)_lodPlanes[e].dispose();}_cleanup(e){this._pingPongRenderTarget.dispose(),this._renderer.setRenderTarget(_oldTarget),e.scissorTest=!1,_setViewport(e,0,0,e.width,e.height);}_fromTexture(e){_oldTarget=this._renderer.getRenderTarget();const t=this._allocateTargets(e);return this._textureToCubeUV(e,t),this._applyPMREM(t),this._cleanup(t),t}_allocateTargets(e){const t={magFilter:1003,minFilter:1003,generateMipmaps:!1,type:1009,format:1023,encoding:_isLDR(e)?e.encoding:3002,depthBuffer:!1},n=_createRenderTarget(t);return n.depthBuffer=!e,this._pingPongRenderTarget=_createRenderTarget(t),n}_compileMaterial(e){const t=new Mesh(_lodPlanes[0],e);this._renderer.compile(t,_flatCamera);}_sceneToCubeUV(e,t,n,r){const i=new PerspectiveCamera(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],s=this._renderer,l=s.autoClear,c=s.outputEncoding,h=s.toneMapping;s.getClearColor(_clearColor),s.toneMapping=0,s.outputEncoding=3e3,s.autoClear=!1;let u=!1;const d=e.background;if(d){if(d.isColor){backgroundMaterial.color.copy(d).convertSRGBToLinear(),e.background=null;const t=convertLinearToRGBE(backgroundMaterial.color);backgroundMaterial.opacity=t,u=!0;}}else {backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();const e=convertLinearToRGBE(backgroundMaterial.color);backgroundMaterial.opacity=e,u=!0;}for(let t=0;t<6;t++){const n=t%3;0==n?(i.up.set(0,a[t],0),i.lookAt(o[t],0,0)):1==n?(i.up.set(0,0,a[t]),i.lookAt(0,o[t],0)):(i.up.set(0,a[t],0),i.lookAt(0,0,o[t])),_setViewport(r,n*SIZE_MAX,t>2?SIZE_MAX:0,SIZE_MAX,SIZE_MAX),s.setRenderTarget(r),u&&s.render(backgroundBox,i),s.render(e,i);}s.toneMapping=h,s.outputEncoding=c,s.autoClear=l;}_textureToCubeUV(e,t){const n=this._renderer;e.isCubeTexture?null==this._cubemapShader&&(this._cubemapShader=_getCubemapShader()):null==this._equirectShader&&(this._equirectShader=_getEquirectShader());const r=e.isCubeTexture?this._cubemapShader:this._equirectShader,i=new Mesh(_lodPlanes[0],r),a=r.uniforms;a.envMap.value=e,e.isCubeTexture||a.texelSize.value.set(1/e.image.width,1/e.image.height),a.inputEncoding.value=ENCODINGS[e.encoding],a.outputEncoding.value=ENCODINGS[t.texture.encoding],_setViewport(t,0,0,3*SIZE_MAX,2*SIZE_MAX),n.setRenderTarget(t),n.render(i,_flatCamera);}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;for(let t=1;t20&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let e=0;e<20;++e){const t=e/p,n=Math.exp(-t*t/2);f.push(n),0==e?g+=n:e4?r-8+4:0),3*v,2*v),s.setRenderTarget(t),s.render(c,_flatCamera);}}function _isLDR(e){return void 0!==e&&1009===e.type&&(3e3===e.encoding||3001===e.encoding||3007===e.encoding)}function _createPlanes(){const e=[],t=[],n=[];let r=8;for(let i=0;i4?o=EXTRA_LOD_SIGMA[i-8+4-1]:0==i&&(o=0),n.push(o);const s=1/(a-1),l=-s/2,c=1+s/2,h=[l,l,c,l,c,c,l,l,c,c,l,c],u=6,d=6,p=3,m=2,f=1,g=new Float32Array(p*d*u),v=new Float32Array(m*d*u),_=new Float32Array(f*d*u);for(let e=0;e2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];g.set(r,p*d*e),v.set(h,m*d*e);const i=[e,e,e,e,e,e];_.set(i,f*d*e);}const y=new BufferGeometry;y.setAttribute("position",new BufferAttribute(g,p)),y.setAttribute("uv",new BufferAttribute(v,m)),y.setAttribute("faceIndex",new BufferAttribute(_,f)),e.push(y),r>4&&r--;}return {_lodPlanes:e,_sizeLods:t,_sigmas:n}}function _createRenderTarget(e){const t=new WebGLRenderTarget(3*SIZE_MAX,3*SIZE_MAX,e);return t.texture.mapping=306,t.texture.name="PMREM.cubeUv",t.scissorTest=!0,t}function _setViewport(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i);}function _getBlurShader(e){const t=new Float32Array(e),n=new Vector3(0,1,0);return new RawShaderMaterial({name:"SphericalGaussianBlur",defines:{n:e},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:t},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n},inputEncoding:{value:ENCODINGS[3e3]},outputEncoding:{value:ENCODINGS[3e3]}},vertexShader:_getCommonVertexShader(),fragmentShader:`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t${_getEncodings()}\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t`,blending:0,depthTest:!1,depthWrite:!1})}function _getEquirectShader(){const e=new Vector2(1,1);return new RawShaderMaterial({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null},texelSize:{value:e},inputEncoding:{value:ENCODINGS[3e3]},outputEncoding:{value:ENCODINGS[3e3]}},vertexShader:_getCommonVertexShader(),fragmentShader:`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t${_getEncodings()}\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t`,blending:0,depthTest:!1,depthWrite:!1})}function _getCubemapShader(){return new RawShaderMaterial({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},inputEncoding:{value:ENCODINGS[3e3]},outputEncoding:{value:ENCODINGS[3e3]}},vertexShader:_getCommonVertexShader(),fragmentShader:`\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t${_getEncodings()}\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t`,blending:0,depthTest:!1,depthWrite:!1})}function _getCommonVertexShader(){return "\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function _getEncodings(){return "\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include \n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t"}const LineStrip=0,LinePieces=1,NoColors=0,FaceColors=1,VertexColors=2;function MeshFaceMaterial(e){return console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead."),e}function MultiMaterial(e=[]){return console.warn("THREE.MultiMaterial has been removed. Use an Array instead."),e.isMultiMaterial=!0,e.materials=e,e.clone=function(){return e.slice()},e}function PointCloud(e,t){return console.warn("THREE.PointCloud has been renamed to THREE.Points."),new Points(e,t)}function Particle(e){return console.warn("THREE.Particle has been renamed to THREE.Sprite."),new Sprite(e)}function ParticleSystem(e,t){return console.warn("THREE.ParticleSystem has been renamed to THREE.Points."),new Points(e,t)}function PointCloudMaterial(e){return console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial."),new PointsMaterial(e)}function ParticleBasicMaterial(e){return console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial."),new PointsMaterial(e)}function ParticleSystemMaterial(e){return console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial."),new PointsMaterial(e)}function Vertex(e,t,n){return console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead."),new Vector3(e,t,n)}function DynamicBufferAttribute(e,t){return console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead."),new BufferAttribute(e,t).setUsage(35048)}function Int8Attribute(e,t){return console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead."),new Int8BufferAttribute(e,t)}function Uint8Attribute(e,t){return console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead."),new Uint8BufferAttribute(e,t)}function Uint8ClampedAttribute(e,t){return console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead."),new Uint8ClampedBufferAttribute(e,t)}function Int16Attribute(e,t){return console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead."),new Int16BufferAttribute(e,t)}function Uint16Attribute(e,t){return console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead."),new Uint16BufferAttribute(e,t)}function Int32Attribute(e,t){return console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead."),new Int32BufferAttribute(e,t)}function Uint32Attribute(e,t){return console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead."),new Uint32BufferAttribute(e,t)}function Float32Attribute(e,t){return console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead."),new Float32BufferAttribute(e,t)}function Float64Attribute(e,t){return console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead."),new Float64BufferAttribute(e,t)}function AxisHelper(e){return console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper."),new AxesHelper(e)}function BoundingBoxHelper(e,t){return console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead."),new BoxHelper(e,t)}function EdgesHelper(e,t){return console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead."),new LineSegments(new EdgesGeometry(e.geometry),new LineBasicMaterial({color:void 0!==t?t:16777215}))}function WireframeHelper(e,t){return console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead."),new LineSegments(new WireframeGeometry(e.geometry),new LineBasicMaterial({color:void 0!==t?t:16777215}))}function XHRLoader(e){return console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader."),new FileLoader(e)}function BinaryTextureLoader(e){return console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader."),new DataTextureLoader(e)}function WebGLRenderTargetCube(e,t,n){return console.warn("THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options )."),new WebGLCubeRenderTarget(e,n)}function CanvasRenderer(){console.error("THREE.CanvasRenderer has been removed");}function JSONLoader(){console.error("THREE.JSONLoader has been removed.");}Curve.create=function(e,t){return console.log("THREE.Curve.create() has been deprecated"),e.prototype=Object.create(Curve.prototype),e.prototype.constructor=e,e.prototype.getPoint=t,e},Path.prototype.fromPoints=function(e){return console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints()."),this.setFromPoints(e)},GridHelper.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.");},SkeletonHelper.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.");},Loader.prototype.extractUrlBase=function(e){return console.warn("THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead."),LoaderUtils.extractUrlBase(e)},Loader.Handlers={add:function(){console.error("THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.");},get:function(){console.error("THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.");}},Box2.prototype.center=function(e){return console.warn("THREE.Box2: .center() has been renamed to .getCenter()."),this.getCenter(e)},Box2.prototype.empty=function(){return console.warn("THREE.Box2: .empty() has been renamed to .isEmpty()."),this.isEmpty()},Box2.prototype.isIntersectionBox=function(e){return console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(e)},Box2.prototype.size=function(e){return console.warn("THREE.Box2: .size() has been renamed to .getSize()."),this.getSize(e)},Box3.prototype.center=function(e){return console.warn("THREE.Box3: .center() has been renamed to .getCenter()."),this.getCenter(e)},Box3.prototype.empty=function(){return console.warn("THREE.Box3: .empty() has been renamed to .isEmpty()."),this.isEmpty()},Box3.prototype.isIntersectionBox=function(e){return console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(e)},Box3.prototype.isIntersectionSphere=function(e){return console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(e)},Box3.prototype.size=function(e){return console.warn("THREE.Box3: .size() has been renamed to .getSize()."),this.getSize(e)},Sphere.prototype.empty=function(){return console.warn("THREE.Sphere: .empty() has been renamed to .isEmpty()."),this.isEmpty()},Frustum.prototype.setFromMatrix=function(e){return console.warn("THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix()."),this.setFromProjectionMatrix(e)},Line3.prototype.center=function(e){return console.warn("THREE.Line3: .center() has been renamed to .getCenter()."),this.getCenter(e)},MathUtils.random16=function(){return console.warn("THREE.Math: .random16() has been deprecated. Use Math.random() instead."),Math.random()},MathUtils.nearestPowerOfTwo=function(e){return console.warn("THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo()."),MathUtils.floorPowerOfTwo(e)},MathUtils.nextPowerOfTwo=function(e){return console.warn("THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo()."),MathUtils.ceilPowerOfTwo(e)},Matrix3.prototype.flattenToArrayOffset=function(e,t){return console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(e,t)},Matrix3.prototype.multiplyVector3=function(e){return console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead."),e.applyMatrix3(this)},Matrix3.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.");},Matrix3.prototype.applyToBufferAttribute=function(e){return console.warn("THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead."),e.applyMatrix3(this)},Matrix3.prototype.applyToVector3Array=function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.");},Matrix3.prototype.getInverse=function(e){return console.warn("THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(e).invert()},Matrix4.prototype.extractPosition=function(e){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(e)},Matrix4.prototype.flattenToArrayOffset=function(e,t){return console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(e,t)},Matrix4.prototype.getPosition=function(){return console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead."),(new Vector3).setFromMatrixColumn(this,3)},Matrix4.prototype.setRotationFromQuaternion=function(e){return console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion()."),this.makeRotationFromQuaternion(e)},Matrix4.prototype.multiplyToArray=function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.");},Matrix4.prototype.multiplyVector3=function(e){return console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead."),e.applyMatrix4(this)},Matrix4.prototype.multiplyVector4=function(e){return console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead."),e.applyMatrix4(this)},Matrix4.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.");},Matrix4.prototype.rotateAxis=function(e){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead."),e.transformDirection(this);},Matrix4.prototype.crossVector=function(e){return console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead."),e.applyMatrix4(this)},Matrix4.prototype.translate=function(){console.error("THREE.Matrix4: .translate() has been removed.");},Matrix4.prototype.rotateX=function(){console.error("THREE.Matrix4: .rotateX() has been removed.");},Matrix4.prototype.rotateY=function(){console.error("THREE.Matrix4: .rotateY() has been removed.");},Matrix4.prototype.rotateZ=function(){console.error("THREE.Matrix4: .rotateZ() has been removed.");},Matrix4.prototype.rotateByAxis=function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.");},Matrix4.prototype.applyToBufferAttribute=function(e){return console.warn("THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead."),e.applyMatrix4(this)},Matrix4.prototype.applyToVector3Array=function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.");},Matrix4.prototype.makeFrustum=function(e,t,n,r,i,a){return console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead."),this.makePerspective(e,t,r,n,i,a)},Matrix4.prototype.getInverse=function(e){return console.warn("THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(e).invert()},Plane.prototype.isIntersectionLine=function(e){return console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine()."),this.intersectsLine(e)},Quaternion.prototype.multiplyVector3=function(e){return console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead."),e.applyQuaternion(this)},Quaternion.prototype.inverse=function(){return console.warn("THREE.Quaternion: .inverse() has been renamed to invert()."),this.invert()},Ray.prototype.isIntersectionBox=function(e){return console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(e)},Ray.prototype.isIntersectionPlane=function(e){return console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane()."),this.intersectsPlane(e)},Ray.prototype.isIntersectionSphere=function(e){return console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(e)},Triangle.prototype.area=function(){return console.warn("THREE.Triangle: .area() has been renamed to .getArea()."),this.getArea()},Triangle.prototype.barycoordFromPoint=function(e,t){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),this.getBarycoord(e,t)},Triangle.prototype.midpoint=function(e){return console.warn("THREE.Triangle: .midpoint() has been renamed to .getMidpoint()."),this.getMidpoint(e)},Triangle.prototypenormal=function(e){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),this.getNormal(e)},Triangle.prototype.plane=function(e){return console.warn("THREE.Triangle: .plane() has been renamed to .getPlane()."),this.getPlane(e)},Triangle.barycoordFromPoint=function(e,t,n,r,i){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),Triangle.getBarycoord(e,t,n,r,i)},Triangle.normal=function(e,t,n,r){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),Triangle.getNormal(e,t,n,r)},Shape.prototype.extractAllPoints=function(e){return console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead."),this.extractPoints(e)},Shape.prototype.extrude=function(e){return console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead."),new ExtrudeGeometry(this,e)},Shape.prototype.makeGeometry=function(e){return console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead."),new ShapeGeometry(this,e)},Vector2.prototype.fromAttribute=function(e,t,n){return console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(e,t,n)},Vector2.prototype.distanceToManhattan=function(e){return console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(e)},Vector2.prototype.lengthManhattan=function(){return console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Vector3.prototype.setEulerFromRotationMatrix=function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.");},Vector3.prototype.setEulerFromQuaternion=function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.");},Vector3.prototype.getPositionFromMatrix=function(e){return console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition()."),this.setFromMatrixPosition(e)},Vector3.prototype.getScaleFromMatrix=function(e){return console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale()."),this.setFromMatrixScale(e)},Vector3.prototype.getColumnFromMatrix=function(e,t){return console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn()."),this.setFromMatrixColumn(t,e)},Vector3.prototype.applyProjection=function(e){return console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead."),this.applyMatrix4(e)},Vector3.prototype.fromAttribute=function(e,t,n){return console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(e,t,n)},Vector3.prototype.distanceToManhattan=function(e){return console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(e)},Vector3.prototype.lengthManhattan=function(){return console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Vector4.prototype.fromAttribute=function(e,t,n){return console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(e,t,n)},Vector4.prototype.lengthManhattan=function(){return console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Object3D.prototype.getChildByName=function(e){return console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName()."),this.getObjectByName(e)},Object3D.prototype.renderDepth=function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.");},Object3D.prototype.translate=function(e,t){return console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead."),this.translateOnAxis(t,e)},Object3D.prototype.getWorldRotation=function(){console.error("THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.");},Object3D.prototype.applyMatrix=function(e){return console.warn("THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(e)},Object.defineProperties(Object3D.prototype,{eulerOrder:{get:function(){return console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order},set:function(e){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order=e;}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.");},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.");}}}),Mesh.prototype.setDrawMode=function(){console.error("THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.");},Object.defineProperties(Mesh.prototype,{drawMode:{get:function(){return console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode."),0},set:function(){console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.");}}}),Object.defineProperties(LOD.prototype,{objects:{get:function(){return console.warn("THREE.LOD: .objects has been renamed to .levels."),this.levels}}}),Object.defineProperty(Skeleton.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.");},set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.");}}),SkinnedMesh.prototype.initBones=function(){console.error("THREE.SkinnedMesh: initBones() has been removed.");},Object.defineProperty(Curve.prototype,"__arcLengthDivisions",{get:function(){return console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions."),this.arcLengthDivisions},set:function(e){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions."),this.arcLengthDivisions=e;}}),PerspectiveCamera.prototype.setLens=function(e,t){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup."),void 0!==t&&(this.filmGauge=t),this.setFocalLength(e);},Object.defineProperties(Light.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.");}},shadowCameraFov:{set:function(e){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov."),this.shadow.camera.fov=e;}},shadowCameraLeft:{set:function(e){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left."),this.shadow.camera.left=e;}},shadowCameraRight:{set:function(e){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right."),this.shadow.camera.right=e;}},shadowCameraTop:{set:function(e){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top."),this.shadow.camera.top=e;}},shadowCameraBottom:{set:function(e){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom."),this.shadow.camera.bottom=e;}},shadowCameraNear:{set:function(e){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near."),this.shadow.camera.near=e;}},shadowCameraFar:{set:function(e){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far."),this.shadow.camera.far=e;}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.");}},shadowBias:{set:function(e){console.warn("THREE.Light: .shadowBias is now .shadow.bias."),this.shadow.bias=e;}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.");}},shadowMapWidth:{set:function(e){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width."),this.shadow.mapSize.width=e;}},shadowMapHeight:{set:function(e){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height."),this.shadow.mapSize.height=e;}}}),Object.defineProperties(BufferAttribute.prototype,{length:{get:function(){return console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead."),this.array.length}},dynamic:{get:function(){return console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),35048===this.usage},set:function(){console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),this.setUsage(35048);}}}),BufferAttribute.prototype.setDynamic=function(e){return console.warn("THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(!0===e?35048:35044),this},BufferAttribute.prototype.copyIndicesArray=function(){console.error("THREE.BufferAttribute: .copyIndicesArray() has been removed.");},BufferAttribute.prototype.setArray=function(){console.error("THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers");},BufferGeometry.prototype.addIndex=function(e){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex()."),this.setIndex(e);},BufferGeometry.prototype.addAttribute=function(e,t){return console.warn("THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute()."),t&&t.isBufferAttribute||t&&t.isInterleavedBufferAttribute?"index"===e?(console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(t),this):this.setAttribute(e,t):(console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.setAttribute(e,new BufferAttribute(arguments[1],arguments[2])))},BufferGeometry.prototype.addDrawCall=function(e,t,n){void 0!==n&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset."),console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup()."),this.addGroup(e,t);},BufferGeometry.prototype.clearDrawCalls=function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups()."),this.clearGroups();},BufferGeometry.prototype.computeOffsets=function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.");},BufferGeometry.prototype.removeAttribute=function(e){return console.warn("THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute()."),this.deleteAttribute(e)},BufferGeometry.prototype.applyMatrix=function(e){return console.warn("THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(e)},Object.defineProperties(BufferGeometry.prototype,{drawcalls:{get:function(){return console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups."),this.groups}},offsets:{get:function(){return console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups."),this.groups}}}),Object.defineProperties(InstancedBufferGeometry.prototype,{maxInstancedCount:{get:function(){return console.warn("THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount."),this.instanceCount},set:function(e){console.warn("THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount."),this.instanceCount=e;}}}),Object.defineProperties(Raycaster.prototype,{linePrecision:{get:function(){return console.warn("THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead."),this.params.Line.threshold},set:function(e){console.warn("THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead."),this.params.Line.threshold=e;}}}),Object.defineProperties(InterleavedBuffer.prototype,{dynamic:{get:function(){return console.warn("THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead."),35048===this.usage},set:function(e){console.warn("THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead."),this.setUsage(e);}}}),InterleavedBuffer.prototype.setDynamic=function(e){return console.warn("THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(!0===e?35048:35044),this},InterleavedBuffer.prototype.setArray=function(){console.error("THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers");},ExtrudeGeometry.prototype.getArrays=function(){console.error("THREE.ExtrudeGeometry: .getArrays() has been removed.");},ExtrudeGeometry.prototype.addShapeList=function(){console.error("THREE.ExtrudeGeometry: .addShapeList() has been removed.");},ExtrudeGeometry.prototype.addShape=function(){console.error("THREE.ExtrudeGeometry: .addShape() has been removed.");},Scene.prototype.dispose=function(){console.error("THREE.Scene: .dispose() has been removed.");},Object.defineProperties(Uniform.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.");}},onUpdate:{value:function(){return console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead."),this}}}),Object.defineProperties(Material.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.");},set:function(){console.warn("THREE.Material: .wrapAround has been removed.");}},overdraw:{get:function(){console.warn("THREE.Material: .overdraw has been removed.");},set:function(){console.warn("THREE.Material: .overdraw has been removed.");}},wrapRGB:{get:function(){return console.warn("THREE.Material: .wrapRGB has been removed."),new Color}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");},set:function(e){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===e;}},stencilMask:{get:function(){return console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask},set:function(e){console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask=e;}}}),Object.defineProperties(MeshPhongMaterial.prototype,{metal:{get:function(){return console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead."),!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead");}}}),Object.defineProperties(MeshPhysicalMaterial.prototype,{transparency:{get:function(){return console.warn("THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission."),this.transmission},set:function(e){console.warn("THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission."),this.transmission=e;}}}),Object.defineProperties(ShaderMaterial.prototype,{derivatives:{get:function(){return console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives},set:function(e){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives=e;}}}),WebGLRenderer.prototype.clearTarget=function(e,t,n,r){console.warn("THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead."),this.setRenderTarget(e),this.clear(t,n,r);},WebGLRenderer.prototype.animate=function(e){console.warn("THREE.WebGLRenderer: .animate() is now .setAnimationLoop()."),this.setAnimationLoop(e);},WebGLRenderer.prototype.getCurrentRenderTarget=function(){return console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget()."),this.getRenderTarget()},WebGLRenderer.prototype.getMaxAnisotropy=function(){return console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy()."),this.capabilities.getMaxAnisotropy()},WebGLRenderer.prototype.getPrecision=function(){return console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision."),this.capabilities.precision},WebGLRenderer.prototype.resetGLState=function(){return console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset()."),this.state.reset()},WebGLRenderer.prototype.supportsFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' )."),this.extensions.get("OES_texture_float")},WebGLRenderer.prototype.supportsHalfFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' )."),this.extensions.get("OES_texture_half_float")},WebGLRenderer.prototype.supportsStandardDerivatives=function(){return console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' )."),this.extensions.get("OES_standard_derivatives")},WebGLRenderer.prototype.supportsCompressedTextureS3TC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' )."),this.extensions.get("WEBGL_compressed_texture_s3tc")},WebGLRenderer.prototype.supportsCompressedTexturePVRTC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' )."),this.extensions.get("WEBGL_compressed_texture_pvrtc")},WebGLRenderer.prototype.supportsBlendMinMax=function(){return console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' )."),this.extensions.get("EXT_blend_minmax")},WebGLRenderer.prototype.supportsVertexTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures."),this.capabilities.vertexTextures},WebGLRenderer.prototype.supportsInstancedArrays=function(){return console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' )."),this.extensions.get("ANGLE_instanced_arrays")},WebGLRenderer.prototype.enableScissorTest=function(e){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest()."),this.setScissorTest(e);},WebGLRenderer.prototype.initMaterial=function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.");},WebGLRenderer.prototype.addPrePlugin=function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.");},WebGLRenderer.prototype.addPostPlugin=function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.");},WebGLRenderer.prototype.updateShadowMap=function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.");},WebGLRenderer.prototype.setFaceCulling=function(){console.warn("THREE.WebGLRenderer: .setFaceCulling() has been removed.");},WebGLRenderer.prototype.allocTextureUnit=function(){console.warn("THREE.WebGLRenderer: .allocTextureUnit() has been removed.");},WebGLRenderer.prototype.setTexture=function(){console.warn("THREE.WebGLRenderer: .setTexture() has been removed.");},WebGLRenderer.prototype.setTexture2D=function(){console.warn("THREE.WebGLRenderer: .setTexture2D() has been removed.");},WebGLRenderer.prototype.setTextureCube=function(){console.warn("THREE.WebGLRenderer: .setTextureCube() has been removed.");},WebGLRenderer.prototype.getActiveMipMapLevel=function(){return console.warn("THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel()."),this.getActiveMipmapLevel()},Object.defineProperties(WebGLRenderer.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(e){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled."),this.shadowMap.enabled=e;}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(e){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type."),this.shadowMap.type=e;}},shadowMapCullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.");},set:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.");}},context:{get:function(){return console.warn("THREE.WebGLRenderer: .context has been removed. Use .getContext() instead."),this.getContext()}},vr:{get:function(){return console.warn("THREE.WebGLRenderer: .vr has been renamed to .xr"),this.xr}},gammaInput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead."),!1},set:function(){console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.");}},gammaOutput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),!1},set:function(e){console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),this.outputEncoding=!0===e?3001:3e3;}},toneMappingWhitePoint:{get:function(){return console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed."),1},set:function(){console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.");}}}),Object.defineProperties(WebGLShadowMap.prototype,{cullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.");},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.");}},renderReverseSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.");},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.");}},renderSingleSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.");},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.");}}}),Object.defineProperties(WebGLRenderTarget.prototype,{wrapS:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS},set:function(e){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS=e;}},wrapT:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT},set:function(e){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT=e;}},magFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter},set:function(e){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter=e;}},minFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter},set:function(e){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter=e;}},anisotropy:{get:function(){return console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy},set:function(e){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy=e;}},offset:{get:function(){return console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset},set:function(e){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset=e;}},repeat:{get:function(){return console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat},set:function(e){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat=e;}},format:{get:function(){return console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format},set:function(e){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format=e;}},type:{get:function(){return console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type},set:function(e){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type=e;}},generateMipmaps:{get:function(){return console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps},set:function(e){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps=e;}}}),Object.defineProperties(Audio.prototype,{load:{value:function(e){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");const t=this;return (new AudioLoader).load(e,(function(e){t.setBuffer(e);})),this}},startTime:{set:function(){console.warn("THREE.Audio: .startTime is now .play( delay ).");}}}),AudioAnalyser.prototype.getData=function(){return console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData()."),this.getFrequencyData()},CubeCamera.prototype.updateCubeMap=function(e,t){return console.warn("THREE.CubeCamera: .updateCubeMap() is now .update()."),this.update(e,t)},CubeCamera.prototype.clear=function(e,t,n,r){return console.warn("THREE.CubeCamera: .clear() is now .renderTarget.clear()."),this.renderTarget.clear(e,t,n,r)},ImageUtils.crossOrigin=void 0,ImageUtils.loadTexture=function(e,t,n,r){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");const i=new TextureLoader;i.setCrossOrigin(this.crossOrigin);const a=i.load(e,n,void 0,r);return t&&(a.mapping=t),a},ImageUtils.loadTextureCube=function(e,t,n,r){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");const i=new CubeTextureLoader;i.setCrossOrigin(this.crossOrigin);const a=i.load(e,n,void 0,r);return t&&(a.mapping=t),a},ImageUtils.loadCompressedTexture=function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.");},ImageUtils.loadCompressedTextureCube=function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.");};const SceneUtils={createMultiMaterialObject:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js");},detach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js");},attach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js");}};function LensFlare(){console.error("THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js");}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"126"}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="126"); -var THREE=/*#__PURE__*/Object.freeze({__proto__:null,ACESFilmicToneMapping:ACESFilmicToneMapping,AddEquation:AddEquation,AddOperation:AddOperation,AdditiveAnimationBlendMode:AdditiveAnimationBlendMode,AdditiveBlending:AdditiveBlending,AlphaFormat:AlphaFormat,AlwaysDepth:AlwaysDepth,AlwaysStencilFunc:AlwaysStencilFunc,AmbientLight:AmbientLight,AmbientLightProbe:AmbientLightProbe,AnimationClip:AnimationClip,AnimationLoader:AnimationLoader,AnimationMixer:AnimationMixer,AnimationObjectGroup:AnimationObjectGroup,AnimationUtils:AnimationUtils,ArcCurve:ArcCurve,ArrayCamera:ArrayCamera,ArrowHelper:ArrowHelper,Audio:Audio,AudioAnalyser:AudioAnalyser,AudioContext:AudioContext,AudioListener:AudioListener,AudioLoader:AudioLoader,AxesHelper:AxesHelper,AxisHelper:AxisHelper,BackSide:BackSide,BasicDepthPacking:BasicDepthPacking,BasicShadowMap:BasicShadowMap,BinaryTextureLoader:BinaryTextureLoader,Bone:Bone,BooleanKeyframeTrack:BooleanKeyframeTrack,BoundingBoxHelper:BoundingBoxHelper,Box2:Box2,Box3:Box3,Box3Helper:Box3Helper,BoxBufferGeometry:BoxGeometry,BoxGeometry:BoxGeometry,BoxHelper:BoxHelper,BufferAttribute:BufferAttribute,BufferGeometry:BufferGeometry,BufferGeometryLoader:BufferGeometryLoader,ByteType:ByteType,Cache:Cache,Camera:Camera,CameraHelper:CameraHelper,CanvasRenderer:CanvasRenderer,CanvasTexture:CanvasTexture,CatmullRomCurve3:CatmullRomCurve3,CineonToneMapping:CineonToneMapping,CircleBufferGeometry:CircleGeometry,CircleGeometry:CircleGeometry,ClampToEdgeWrapping:ClampToEdgeWrapping,Clock:Clock,Color:Color,ColorKeyframeTrack:ColorKeyframeTrack,CompressedTexture:CompressedTexture,CompressedTextureLoader:CompressedTextureLoader,ConeBufferGeometry:ConeGeometry,ConeGeometry:ConeGeometry,CubeCamera:CubeCamera,CubeReflectionMapping:CubeReflectionMapping,CubeRefractionMapping:CubeRefractionMapping,CubeTexture:CubeTexture,CubeTextureLoader:CubeTextureLoader,CubeUVReflectionMapping:CubeUVReflectionMapping,CubeUVRefractionMapping:CubeUVRefractionMapping,CubicBezierCurve:CubicBezierCurve,CubicBezierCurve3:CubicBezierCurve3,CubicInterpolant:CubicInterpolant,CullFaceBack:CullFaceBack,CullFaceFront:CullFaceFront,CullFaceFrontBack:CullFaceFrontBack,CullFaceNone:CullFaceNone,Curve:Curve,CurvePath:CurvePath,CustomBlending:CustomBlending,CustomToneMapping:CustomToneMapping,CylinderBufferGeometry:CylinderGeometry,CylinderGeometry:CylinderGeometry,Cylindrical:Cylindrical,DataTexture:DataTexture,DataTexture2DArray:DataTexture2DArray,DataTexture3D:DataTexture3D,DataTextureLoader:DataTextureLoader,DataUtils:DataUtils,DecrementStencilOp:DecrementStencilOp,DecrementWrapStencilOp:DecrementWrapStencilOp,DefaultLoadingManager:DefaultLoadingManager,DepthFormat:DepthFormat,DepthStencilFormat:DepthStencilFormat,DepthTexture:DepthTexture,DirectionalLight:DirectionalLight,DirectionalLightHelper:DirectionalLightHelper,DiscreteInterpolant:DiscreteInterpolant,DodecahedronBufferGeometry:DodecahedronGeometry,DodecahedronGeometry:DodecahedronGeometry,DoubleSide:DoubleSide,DstAlphaFactor:DstAlphaFactor,DstColorFactor:DstColorFactor,DynamicBufferAttribute:DynamicBufferAttribute,DynamicCopyUsage:DynamicCopyUsage,DynamicDrawUsage:DynamicDrawUsage,DynamicReadUsage:DynamicReadUsage,EdgesGeometry:EdgesGeometry,EdgesHelper:EdgesHelper,EllipseCurve:EllipseCurve,EqualDepth:EqualDepth,EqualStencilFunc:EqualStencilFunc,EquirectangularReflectionMapping:EquirectangularReflectionMapping,EquirectangularRefractionMapping:EquirectangularRefractionMapping,Euler:Euler,EventDispatcher:EventDispatcher,ExtrudeBufferGeometry:ExtrudeGeometry,ExtrudeGeometry:ExtrudeGeometry,FaceColors:FaceColors,FileLoader:FileLoader,FlatShading:FlatShading,Float16BufferAttribute:Float16BufferAttribute,Float32Attribute:Float32Attribute,Float32BufferAttribute:Float32BufferAttribute,Float64Attribute:Float64Attribute,Float64BufferAttribute:Float64BufferAttribute,FloatType:FloatType,Fog:Fog,FogExp2:FogExp2,Font:Font,FontLoader:FontLoader,FrontSide:FrontSide,Frustum:Frustum,GLBufferAttribute:GLBufferAttribute,GLSL1:GLSL1,GLSL3:GLSL3,GammaEncoding:GammaEncoding,GreaterDepth:GreaterDepth,GreaterEqualDepth:GreaterEqualDepth,GreaterEqualStencilFunc:GreaterEqualStencilFunc,GreaterStencilFunc:GreaterStencilFunc,GridHelper:GridHelper,Group:Group,HalfFloatType:HalfFloatType,HemisphereLight:HemisphereLight,HemisphereLightHelper:HemisphereLightHelper,HemisphereLightProbe:HemisphereLightProbe,IcosahedronBufferGeometry:IcosahedronGeometry,IcosahedronGeometry:IcosahedronGeometry,ImageBitmapLoader:ImageBitmapLoader,ImageLoader:ImageLoader,ImageUtils:ImageUtils,ImmediateRenderObject:ImmediateRenderObject,IncrementStencilOp:IncrementStencilOp,IncrementWrapStencilOp:IncrementWrapStencilOp,InstancedBufferAttribute:InstancedBufferAttribute,InstancedBufferGeometry:InstancedBufferGeometry,InstancedInterleavedBuffer:InstancedInterleavedBuffer,InstancedMesh:InstancedMesh,Int16Attribute:Int16Attribute,Int16BufferAttribute:Int16BufferAttribute,Int32Attribute:Int32Attribute,Int32BufferAttribute:Int32BufferAttribute,Int8Attribute:Int8Attribute,Int8BufferAttribute:Int8BufferAttribute,IntType:IntType,InterleavedBuffer:InterleavedBuffer,InterleavedBufferAttribute:InterleavedBufferAttribute,Interpolant:Interpolant,InterpolateDiscrete:InterpolateDiscrete,InterpolateLinear:InterpolateLinear,InterpolateSmooth:InterpolateSmooth,InvertStencilOp:InvertStencilOp,JSONLoader:JSONLoader,KeepStencilOp:KeepStencilOp,KeyframeTrack:KeyframeTrack,LOD:LOD,LatheBufferGeometry:LatheGeometry,LatheGeometry:LatheGeometry,Layers:Layers,LensFlare:LensFlare,LessDepth:LessDepth,LessEqualDepth:LessEqualDepth,LessEqualStencilFunc:LessEqualStencilFunc,LessStencilFunc:LessStencilFunc,Light:Light,LightProbe:LightProbe,Line:Line,Line3:Line3,LineBasicMaterial:LineBasicMaterial,LineCurve:LineCurve,LineCurve3:LineCurve3,LineDashedMaterial:LineDashedMaterial,LineLoop:LineLoop,LinePieces:LinePieces,LineSegments:LineSegments,LineStrip:LineStrip,LinearEncoding:LinearEncoding,LinearFilter:LinearFilter,LinearInterpolant:LinearInterpolant,LinearMipMapLinearFilter:LinearMipMapLinearFilter,LinearMipMapNearestFilter:LinearMipMapNearestFilter,LinearMipmapLinearFilter:LinearMipmapLinearFilter,LinearMipmapNearestFilter:LinearMipmapNearestFilter,LinearToneMapping:LinearToneMapping,Loader:Loader,LoaderUtils:LoaderUtils,LoadingManager:LoadingManager,LogLuvEncoding:LogLuvEncoding,LoopOnce:LoopOnce,LoopPingPong:LoopPingPong,LoopRepeat:LoopRepeat,LuminanceAlphaFormat:LuminanceAlphaFormat,LuminanceFormat:LuminanceFormat,MOUSE:MOUSE,Material:Material,MaterialLoader:MaterialLoader,Math:MathUtils,MathUtils:MathUtils,Matrix3:Matrix3,Matrix4:Matrix4,MaxEquation:MaxEquation,Mesh:Mesh,MeshBasicMaterial:MeshBasicMaterial,MeshDepthMaterial:MeshDepthMaterial,MeshDistanceMaterial:MeshDistanceMaterial,MeshFaceMaterial:MeshFaceMaterial,MeshLambertMaterial:MeshLambertMaterial,MeshMatcapMaterial:MeshMatcapMaterial,MeshNormalMaterial:MeshNormalMaterial,MeshPhongMaterial:MeshPhongMaterial,MeshPhysicalMaterial:MeshPhysicalMaterial,MeshStandardMaterial:MeshStandardMaterial,MeshToonMaterial:MeshToonMaterial,MinEquation:MinEquation,MirroredRepeatWrapping:MirroredRepeatWrapping,MixOperation:MixOperation,MultiMaterial:MultiMaterial,MultiplyBlending:MultiplyBlending,MultiplyOperation:MultiplyOperation,NearestFilter:NearestFilter,NearestMipMapLinearFilter:NearestMipMapLinearFilter,NearestMipMapNearestFilter:NearestMipMapNearestFilter,NearestMipmapLinearFilter:NearestMipmapLinearFilter,NearestMipmapNearestFilter:NearestMipmapNearestFilter,NeverDepth:NeverDepth,NeverStencilFunc:NeverStencilFunc,NoBlending:NoBlending,NoColors:NoColors,NoToneMapping:NoToneMapping,NormalAnimationBlendMode:NormalAnimationBlendMode,NormalBlending:NormalBlending,NotEqualDepth:NotEqualDepth,NotEqualStencilFunc:NotEqualStencilFunc,NumberKeyframeTrack:NumberKeyframeTrack,Object3D:Object3D,ObjectLoader:ObjectLoader,ObjectSpaceNormalMap:ObjectSpaceNormalMap,OctahedronBufferGeometry:OctahedronGeometry,OctahedronGeometry:OctahedronGeometry,OneFactor:OneFactor,OneMinusDstAlphaFactor:OneMinusDstAlphaFactor,OneMinusDstColorFactor:OneMinusDstColorFactor,OneMinusSrcAlphaFactor:OneMinusSrcAlphaFactor,OneMinusSrcColorFactor:OneMinusSrcColorFactor,OrthographicCamera:OrthographicCamera,PCFShadowMap:PCFShadowMap,PCFSoftShadowMap:PCFSoftShadowMap,PMREMGenerator:PMREMGenerator,ParametricBufferGeometry:ParametricGeometry,ParametricGeometry:ParametricGeometry,Particle:Particle,ParticleBasicMaterial:ParticleBasicMaterial,ParticleSystem:ParticleSystem,ParticleSystemMaterial:ParticleSystemMaterial,Path:Path,PerspectiveCamera:PerspectiveCamera,Plane:Plane,PlaneBufferGeometry:PlaneGeometry,PlaneGeometry:PlaneGeometry,PlaneHelper:PlaneHelper,PointCloud:PointCloud,PointCloudMaterial:PointCloudMaterial,PointLight:PointLight,PointLightHelper:PointLightHelper,Points:Points,PointsMaterial:PointsMaterial,PolarGridHelper:PolarGridHelper,PolyhedronBufferGeometry:PolyhedronGeometry,PolyhedronGeometry:PolyhedronGeometry,PositionalAudio:PositionalAudio,PropertyBinding:PropertyBinding,PropertyMixer:PropertyMixer,QuadraticBezierCurve:QuadraticBezierCurve,QuadraticBezierCurve3:QuadraticBezierCurve3,Quaternion:Quaternion,QuaternionKeyframeTrack:QuaternionKeyframeTrack,QuaternionLinearInterpolant:QuaternionLinearInterpolant,REVISION:REVISION,RGBADepthPacking:RGBADepthPacking,RGBAFormat:RGBAFormat,RGBAIntegerFormat:RGBAIntegerFormat,RGBA_ASTC_10x10_Format:RGBA_ASTC_10x10_Format,RGBA_ASTC_10x5_Format:RGBA_ASTC_10x5_Format,RGBA_ASTC_10x6_Format:RGBA_ASTC_10x6_Format,RGBA_ASTC_10x8_Format:RGBA_ASTC_10x8_Format,RGBA_ASTC_12x10_Format:RGBA_ASTC_12x10_Format,RGBA_ASTC_12x12_Format:RGBA_ASTC_12x12_Format,RGBA_ASTC_4x4_Format:RGBA_ASTC_4x4_Format,RGBA_ASTC_5x4_Format:RGBA_ASTC_5x4_Format,RGBA_ASTC_5x5_Format:RGBA_ASTC_5x5_Format,RGBA_ASTC_6x5_Format:RGBA_ASTC_6x5_Format,RGBA_ASTC_6x6_Format:RGBA_ASTC_6x6_Format,RGBA_ASTC_8x5_Format:RGBA_ASTC_8x5_Format,RGBA_ASTC_8x6_Format:RGBA_ASTC_8x6_Format,RGBA_ASTC_8x8_Format:RGBA_ASTC_8x8_Format,RGBA_BPTC_Format:RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:RGBA_ETC2_EAC_Format,RGBA_PVRTC_2BPPV1_Format:RGBA_PVRTC_2BPPV1_Format,RGBA_PVRTC_4BPPV1_Format:RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:RGBA_S3TC_DXT1_Format,RGBA_S3TC_DXT3_Format:RGBA_S3TC_DXT3_Format,RGBA_S3TC_DXT5_Format:RGBA_S3TC_DXT5_Format,RGBDEncoding:RGBDEncoding,RGBEEncoding:RGBEEncoding,RGBEFormat:RGBEFormat,RGBFormat:RGBFormat,RGBIntegerFormat:RGBIntegerFormat,RGBM16Encoding:RGBM16Encoding,RGBM7Encoding:RGBM7Encoding,RGB_ETC1_Format:RGB_ETC1_Format,RGB_ETC2_Format:RGB_ETC2_Format,RGB_PVRTC_2BPPV1_Format:RGB_PVRTC_2BPPV1_Format,RGB_PVRTC_4BPPV1_Format:RGB_PVRTC_4BPPV1_Format,RGB_S3TC_DXT1_Format:RGB_S3TC_DXT1_Format,RGFormat:RGFormat,RGIntegerFormat:RGIntegerFormat,RawShaderMaterial:RawShaderMaterial,Ray:Ray,Raycaster:Raycaster,RectAreaLight:RectAreaLight,RedFormat:RedFormat,RedIntegerFormat:RedIntegerFormat,ReinhardToneMapping:ReinhardToneMapping,RepeatWrapping:RepeatWrapping,ReplaceStencilOp:ReplaceStencilOp,ReverseSubtractEquation:ReverseSubtractEquation,RingBufferGeometry:RingGeometry,RingGeometry:RingGeometry,SRGB8_ALPHA8_ASTC_10x10_Format:SRGB8_ALPHA8_ASTC_10x10_Format,SRGB8_ALPHA8_ASTC_10x5_Format:SRGB8_ALPHA8_ASTC_10x5_Format,SRGB8_ALPHA8_ASTC_10x6_Format:SRGB8_ALPHA8_ASTC_10x6_Format,SRGB8_ALPHA8_ASTC_10x8_Format:SRGB8_ALPHA8_ASTC_10x8_Format,SRGB8_ALPHA8_ASTC_12x10_Format:SRGB8_ALPHA8_ASTC_12x10_Format,SRGB8_ALPHA8_ASTC_12x12_Format:SRGB8_ALPHA8_ASTC_12x12_Format,SRGB8_ALPHA8_ASTC_4x4_Format:SRGB8_ALPHA8_ASTC_4x4_Format,SRGB8_ALPHA8_ASTC_5x4_Format:SRGB8_ALPHA8_ASTC_5x4_Format,SRGB8_ALPHA8_ASTC_5x5_Format:SRGB8_ALPHA8_ASTC_5x5_Format,SRGB8_ALPHA8_ASTC_6x5_Format:SRGB8_ALPHA8_ASTC_6x5_Format,SRGB8_ALPHA8_ASTC_6x6_Format:SRGB8_ALPHA8_ASTC_6x6_Format,SRGB8_ALPHA8_ASTC_8x5_Format:SRGB8_ALPHA8_ASTC_8x5_Format,SRGB8_ALPHA8_ASTC_8x6_Format:SRGB8_ALPHA8_ASTC_8x6_Format,SRGB8_ALPHA8_ASTC_8x8_Format:SRGB8_ALPHA8_ASTC_8x8_Format,Scene:Scene,SceneUtils:SceneUtils,ShaderChunk:ShaderChunk,ShaderLib:ShaderLib,ShaderMaterial:ShaderMaterial,ShadowMaterial:ShadowMaterial,Shape:Shape,ShapeBufferGeometry:ShapeGeometry,ShapeGeometry:ShapeGeometry,ShapePath:ShapePath,ShapeUtils:ShapeUtils,ShortType:ShortType,Skeleton:Skeleton,SkeletonHelper:SkeletonHelper,SkinnedMesh:SkinnedMesh,SmoothShading:SmoothShading,Sphere:Sphere,SphereBufferGeometry:SphereGeometry,SphereGeometry:SphereGeometry,Spherical:Spherical,SphericalHarmonics3:SphericalHarmonics3,SplineCurve:SplineCurve,SpotLight:SpotLight,SpotLightHelper:SpotLightHelper,Sprite:Sprite,SpriteMaterial:SpriteMaterial,SrcAlphaFactor:SrcAlphaFactor,SrcAlphaSaturateFactor:SrcAlphaSaturateFactor,SrcColorFactor:SrcColorFactor,StaticCopyUsage:StaticCopyUsage,StaticDrawUsage:StaticDrawUsage,StaticReadUsage:StaticReadUsage,StereoCamera:StereoCamera,StreamCopyUsage:StreamCopyUsage,StreamDrawUsage:StreamDrawUsage,StreamReadUsage:StreamReadUsage,StringKeyframeTrack:StringKeyframeTrack,SubtractEquation:SubtractEquation,SubtractiveBlending:SubtractiveBlending,TOUCH:TOUCH,TangentSpaceNormalMap:TangentSpaceNormalMap,TetrahedronBufferGeometry:TetrahedronGeometry,TetrahedronGeometry:TetrahedronGeometry,TextBufferGeometry:TextGeometry,TextGeometry:TextGeometry,Texture:Texture,TextureLoader:TextureLoader,TorusBufferGeometry:TorusGeometry,TorusGeometry:TorusGeometry,TorusKnotBufferGeometry:TorusKnotGeometry,TorusKnotGeometry:TorusKnotGeometry,Triangle:Triangle,TriangleFanDrawMode:TriangleFanDrawMode,TriangleStripDrawMode:TriangleStripDrawMode,TrianglesDrawMode:TrianglesDrawMode,TubeBufferGeometry:TubeGeometry,TubeGeometry:TubeGeometry,UVMapping:UVMapping,Uint16Attribute:Uint16Attribute,Uint16BufferAttribute:Uint16BufferAttribute,Uint32Attribute:Uint32Attribute,Uint32BufferAttribute:Uint32BufferAttribute,Uint8Attribute:Uint8Attribute,Uint8BufferAttribute:Uint8BufferAttribute,Uint8ClampedAttribute:Uint8ClampedAttribute,Uint8ClampedBufferAttribute:Uint8ClampedBufferAttribute,Uniform:Uniform,UniformsLib:UniformsLib,UniformsUtils:UniformsUtils,UnsignedByteType:UnsignedByteType,UnsignedInt248Type:UnsignedInt248Type,UnsignedIntType:UnsignedIntType,UnsignedShort4444Type:UnsignedShort4444Type,UnsignedShort5551Type:UnsignedShort5551Type,UnsignedShort565Type:UnsignedShort565Type,UnsignedShortType:UnsignedShortType,VSMShadowMap:VSMShadowMap,Vector2:Vector2,Vector3:Vector3,Vector4:Vector4,VectorKeyframeTrack:VectorKeyframeTrack,Vertex:Vertex,VertexColors:VertexColors,VideoTexture:VideoTexture,WebGL1Renderer:WebGL1Renderer,WebGLCubeRenderTarget:WebGLCubeRenderTarget,WebGLMultisampleRenderTarget:WebGLMultisampleRenderTarget,WebGLRenderTarget:WebGLRenderTarget,WebGLRenderTargetCube:WebGLRenderTargetCube,WebGLRenderer:WebGLRenderer,WebGLUtils:WebGLUtils,WireframeGeometry:WireframeGeometry,WireframeHelper:WireframeHelper,WrapAroundEnding:WrapAroundEnding,XHRLoader:XHRLoader,ZeroCurvatureEnding:ZeroCurvatureEnding,ZeroFactor:ZeroFactor,ZeroSlopeEnding:ZeroSlopeEnding,ZeroStencilOp:ZeroStencilOp,sRGBEncoding:sRGBEncoding});var OrbitControls=function(e,t){var n,o,a,i,r,c;void 0===t&&console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.'),t===document&&console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),this.object=e,this.domElement=t,this.enabled=!0,this.target=new Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:37,UP:38,RIGHT:39,BOTTOM:40},this.mouseButtons={LEFT:MOUSE.ROTATE,MIDDLE:MOUSE.DOLLY,RIGHT:MOUSE.PAN},this.touches={ONE:TOUCH.ROTATE,TWO:TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return b.phi},this.getAzimuthalAngle=function(){return b.theta},this.listenToKeyEvents=function(e){e.addEventListener("keydown",q),this._domElementKeyEvents=e;},this.saveState=function(){s.target0.copy(s.target),s.position0.copy(s.object.position),s.zoom0=s.object.zoom;},this.reset=function(){s.target.copy(s.target0),s.object.position.copy(s.position0),s.object.zoom=s.zoom0,s.object.updateProjectionMatrix(),s.dispatchEvent(u),s.update(),h=p.NONE;},this.update=(n=new Vector3,o=(new Quaternion).setFromUnitVectors(e.up,new Vector3(0,1,0)),a=o.clone().invert(),i=new Vector3,r=new Quaternion,c=2*Math.PI,function(){var e=s.object.position;n.copy(e).sub(s.target),n.applyQuaternion(o),b.setFromVector3(n),s.autoRotate&&h===p.NONE&&C(2*Math.PI/60/60*s.autoRotateSpeed),s.enableDamping?(b.theta+=E.theta*s.dampingFactor,b.phi+=E.phi*s.dampingFactor):(b.theta+=E.theta,b.phi+=E.phi);var t=s.minAzimuthAngle,l=s.maxAzimuthAngle;return isFinite(t)&&isFinite(l)&&(t<-Math.PI?t+=c:t>Math.PI&&(t-=c),l<-Math.PI?l+=c:l>Math.PI&&(l-=c),b.theta=t<=l?Math.max(t,Math.min(l,b.theta)):b.theta>(t+l)/2?Math.max(t,b.theta):Math.min(l,b.theta)),b.phi=Math.max(s.minPolarAngle,Math.min(s.maxPolarAngle,b.phi)),b.makeSafe(),b.radius*=O,b.radius=Math.max(s.minDistance,Math.min(s.maxDistance,b.radius)),!0===s.enableDamping?s.target.addScaledVector(f,s.dampingFactor):s.target.add(f),n.setFromSpherical(b),n.applyQuaternion(a),e.copy(s.target).add(n),s.object.lookAt(s.target),!0===s.enableDamping?(E.theta*=1-s.dampingFactor,E.phi*=1-s.dampingFactor,f.multiplyScalar(1-s.dampingFactor)):(E.set(0,0,0),f.set(0,0,0)),O=1,!!(g||i.distanceToSquared(s.object.position)>d||8*(1-r.dot(s.object.quaternion))>d)&&(s.dispatchEvent(u),i.copy(s.object.position),r.copy(s.object.quaternion),g=!1,!0)}),this.dispose=function(){s.domElement.removeEventListener("contextmenu",ee),s.domElement.removeEventListener("pointerdown",K),s.domElement.removeEventListener("wheel",W),s.domElement.removeEventListener("touchstart",Q),s.domElement.removeEventListener("touchend",$),s.domElement.removeEventListener("touchmove",J),s.domElement.ownerDocument.removeEventListener("pointermove",B),s.domElement.ownerDocument.removeEventListener("pointerup",G),null!==s._domElementKeyEvents&&s._domElementKeyEvents.removeEventListener("keydown",q);};var s=this,u={type:"change"},l={type:"start"},m={type:"end"},p={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},h=p.NONE,d=1e-6,b=new Spherical,E=new Spherical,O=1,f=new Vector3,g=!1,v=new Vector2,T=new Vector2,y=new Vector2,P=new Vector2,L=new Vector2,w=new Vector2,A=new Vector2,N=new Vector2,M=new Vector2;function j(){return Math.pow(.95,s.zoomSpeed)}function C(e){E.theta-=e;}function D(e){E.phi-=e;}var S,R=(S=new Vector3,function(e,t){S.setFromMatrixColumn(t,0),S.multiplyScalar(-e),f.add(S);}),k=function(){var e=new Vector3;return function(t,n){!0===s.screenSpacePanning?e.setFromMatrixColumn(n,1):(e.setFromMatrixColumn(n,0),e.crossVectors(s.object.up,e)),e.multiplyScalar(t),f.add(e);}}(),Y=function(){var e=new Vector3;return function(t,n){var o=s.domElement;if(s.object.isPerspectiveCamera){var a=s.object.position;e.copy(a).sub(s.target);var i=e.length();i*=Math.tan(s.object.fov/2*Math.PI/180),R(2*t*i/o.clientHeight,s.object.matrix),k(2*n*i/o.clientHeight,s.object.matrix);}else s.object.isOrthographicCamera?(R(t*(s.object.right-s.object.left)/s.object.zoom/o.clientWidth,s.object.matrix),k(n*(s.object.top-s.object.bottom)/s.object.zoom/o.clientHeight,s.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),s.enablePan=!1);}}();function H(e){s.object.isPerspectiveCamera?O/=e:s.object.isOrthographicCamera?(s.object.zoom=Math.max(s.minZoom,Math.min(s.maxZoom,s.object.zoom*e)),s.object.updateProjectionMatrix(),g=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),s.enableZoom=!1);}function U(e){s.object.isPerspectiveCamera?O*=e:s.object.isOrthographicCamera?(s.object.zoom=Math.max(s.minZoom,Math.min(s.maxZoom,s.object.zoom/e)),s.object.updateProjectionMatrix(),g=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),s.enableZoom=!1);}function x(e){v.set(e.clientX,e.clientY);}function V(e){P.set(e.clientX,e.clientY);}function _(e){if(1==e.touches.length)v.set(e.touches[0].pageX,e.touches[0].pageY);else {var t=.5*(e.touches[0].pageX+e.touches[1].pageX),n=.5*(e.touches[0].pageY+e.touches[1].pageY);v.set(t,n);}}function z(e){if(1==e.touches.length)P.set(e.touches[0].pageX,e.touches[0].pageY);else {var t=.5*(e.touches[0].pageX+e.touches[1].pageX),n=.5*(e.touches[0].pageY+e.touches[1].pageY);P.set(t,n);}}function I(e){var t=e.touches[0].pageX-e.touches[1].pageX,n=e.touches[0].pageY-e.touches[1].pageY,o=Math.sqrt(t*t+n*n);A.set(0,o);}function X(e){if(1==e.touches.length)T.set(e.touches[0].pageX,e.touches[0].pageY);else {var t=.5*(e.touches[0].pageX+e.touches[1].pageX),n=.5*(e.touches[0].pageY+e.touches[1].pageY);T.set(t,n);}y.subVectors(T,v).multiplyScalar(s.rotateSpeed);var o=s.domElement;C(2*Math.PI*y.x/o.clientHeight),D(2*Math.PI*y.y/o.clientHeight),v.copy(T);}function F(e){if(1==e.touches.length)L.set(e.touches[0].pageX,e.touches[0].pageY);else {var t=.5*(e.touches[0].pageX+e.touches[1].pageX),n=.5*(e.touches[0].pageY+e.touches[1].pageY);L.set(t,n);}w.subVectors(L,P).multiplyScalar(s.panSpeed),Y(w.x,w.y),P.copy(L);}function Z(e){var t=e.touches[0].pageX-e.touches[1].pageX,n=e.touches[0].pageY-e.touches[1].pageY,o=Math.sqrt(t*t+n*n);N.set(0,o),M.set(0,Math.pow(N.y/A.y,s.zoomSpeed)),H(M.y),A.copy(N);}function K(e){if(!1!==s.enabled)switch(e.pointerType){case"mouse":case"pen":!function(e){var t;switch(e.preventDefault(),s.domElement.focus?s.domElement.focus():window.focus(),e.button){case 0:t=s.mouseButtons.LEFT;break;case 1:t=s.mouseButtons.MIDDLE;break;case 2:t=s.mouseButtons.RIGHT;break;default:t=-1;}switch(t){case MOUSE.DOLLY:if(!1===s.enableZoom)return;!function(e){A.set(e.clientX,e.clientY);}(e),h=p.DOLLY;break;case MOUSE.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===s.enablePan)return;V(e),h=p.PAN;}else {if(!1===s.enableRotate)return;x(e),h=p.ROTATE;}break;case MOUSE.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===s.enableRotate)return;x(e),h=p.ROTATE;}else {if(!1===s.enablePan)return;V(e),h=p.PAN;}break;default:h=p.NONE;}h!==p.NONE&&(s.domElement.ownerDocument.addEventListener("pointermove",B),s.domElement.ownerDocument.addEventListener("pointerup",G),s.dispatchEvent(l));}(e);}}function B(e){if(!1!==s.enabled)switch(e.pointerType){case"mouse":case"pen":!function(e){if(!1===s.enabled)return;switch(e.preventDefault(),h){case p.ROTATE:if(!1===s.enableRotate)return;!function(e){T.set(e.clientX,e.clientY),y.subVectors(T,v).multiplyScalar(s.rotateSpeed);var t=s.domElement;C(2*Math.PI*y.x/t.clientHeight),D(2*Math.PI*y.y/t.clientHeight),v.copy(T),s.update();}(e);break;case p.DOLLY:if(!1===s.enableZoom)return;!function(e){N.set(e.clientX,e.clientY),M.subVectors(N,A),M.y>0?H(j()):M.y<0&&U(j()),A.copy(N),s.update();}(e);break;case p.PAN:if(!1===s.enablePan)return;!function(e){L.set(e.clientX,e.clientY),w.subVectors(L,P).multiplyScalar(s.panSpeed),Y(w.x,w.y),P.copy(L),s.update();}(e);}}(e);}}function G(e){switch(e.pointerType){case"mouse":case"pen":!function(e){if(s.domElement.ownerDocument.removeEventListener("pointermove",B),s.domElement.ownerDocument.removeEventListener("pointerup",G),!1===s.enabled)return;s.dispatchEvent(m),h=p.NONE;}();}}function W(e){!1===s.enabled||!1===s.enableZoom||h!==p.NONE&&h!==p.ROTATE||(e.preventDefault(),e.stopPropagation(),s.dispatchEvent(l),function(e){e.deltaY<0?U(j()):e.deltaY>0&&H(j()),s.update();}(e),s.dispatchEvent(m));}function q(e){!1!==s.enabled&&!1!==s.enablePan&&function(e){var t=!1;switch(e.keyCode){case s.keys.UP:Y(0,s.keyPanSpeed),t=!0;break;case s.keys.BOTTOM:Y(0,-s.keyPanSpeed),t=!0;break;case s.keys.LEFT:Y(s.keyPanSpeed,0),t=!0;break;case s.keys.RIGHT:Y(-s.keyPanSpeed,0),t=!0;}t&&(e.preventDefault(),s.update());}(e);}function Q(e){if(!1!==s.enabled){switch(e.preventDefault(),e.touches.length){case 1:switch(s.touches.ONE){case TOUCH.ROTATE:if(!1===s.enableRotate)return;_(e),h=p.TOUCH_ROTATE;break;case TOUCH.PAN:if(!1===s.enablePan)return;z(e),h=p.TOUCH_PAN;break;default:h=p.NONE;}break;case 2:switch(s.touches.TWO){case TOUCH.DOLLY_PAN:if(!1===s.enableZoom&&!1===s.enablePan)return;!function(e){s.enableZoom&&I(e),s.enablePan&&z(e);}(e),h=p.TOUCH_DOLLY_PAN;break;case TOUCH.DOLLY_ROTATE:if(!1===s.enableZoom&&!1===s.enableRotate)return;!function(e){s.enableZoom&&I(e),s.enableRotate&&_(e);}(e),h=p.TOUCH_DOLLY_ROTATE;break;default:h=p.NONE;}break;default:h=p.NONE;}h!==p.NONE&&s.dispatchEvent(l);}}function J(e){if(!1!==s.enabled)switch(e.preventDefault(),e.stopPropagation(),h){case p.TOUCH_ROTATE:if(!1===s.enableRotate)return;X(e),s.update();break;case p.TOUCH_PAN:if(!1===s.enablePan)return;F(e),s.update();break;case p.TOUCH_DOLLY_PAN:if(!1===s.enableZoom&&!1===s.enablePan)return;!function(e){s.enableZoom&&Z(e),s.enablePan&&F(e);}(e),s.update();break;case p.TOUCH_DOLLY_ROTATE:if(!1===s.enableZoom&&!1===s.enableRotate)return;!function(e){s.enableZoom&&Z(e),s.enableRotate&&X(e);}(e),s.update();break;default:h=p.NONE;}}function $(e){!1!==s.enabled&&(s.dispatchEvent(m),h=p.NONE);}function ee(e){!1!==s.enabled&&e.preventDefault();}s.domElement.addEventListener("contextmenu",ee),s.domElement.addEventListener("pointerdown",K),s.domElement.addEventListener("wheel",W),s.domElement.addEventListener("touchstart",Q),s.domElement.addEventListener("touchend",$),s.domElement.addEventListener("touchmove",J),this.update();};OrbitControls.prototype=Object.create(EventDispatcher.prototype),OrbitControls.prototype.constructor=OrbitControls;var MapControls=function(e,t){OrbitControls.call(this,e,t),this.screenSpacePanning=!1,this.mouseButtons.LEFT=MOUSE.PAN,this.mouseButtons.RIGHT=MOUSE.ROTATE,this.touches.ONE=TOUCH.PAN,this.touches.TWO=TOUCH.DOLLY_ROTATE;};MapControls.prototype=Object.create(EventDispatcher.prototype),MapControls.prototype.constructor=MapControls;var GLTFLoader=function(){function e(e){Loader.call(this,e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register((function(e){return new n(e)})),this.register((function(e){return new o(e)})),this.register((function(e){return new l(e)})),this.register((function(e){return new i(e)})),this.register((function(e){return new a(e)})),this.register((function(e){return new u(e)}));}function t(){var e={};return {get:function(t){return e[t]},add:function(t,r){e[t]=r;},remove:function(t){delete e[t];},removeAll:function(){e={};}}}e.prototype=Object.assign(Object.create(Loader.prototype),{constructor:e,load:function(e,t,r,a){var s,n=this;s=""!==this.resourcePath?this.resourcePath:""!==this.path?this.path:LoaderUtils.extractUrlBase(e),this.manager.itemStart(e);var i=function(t){a?a(t):console.error(t),n.manager.itemError(e),n.manager.itemEnd(e);},o=new FileLoader(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,(function(r){try{n.parse(r,s,(function(r){t(r),n.manager.itemEnd(e);}),i);}catch(e){i(e);}}),r,i);},setDRACOLoader:function(e){return this.dracoLoader=e,this},setDDSLoader:function(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')},setKTX2Loader:function(e){return this.ktx2Loader=e,this},setMeshoptDecoder:function(e){return this.meshoptDecoder=e,this},register:function(e){return -1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this},unregister:function(e){return -1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this},parse:function(e,t,a,n){var i,o={},l={};if("string"==typeof e)i=e;else if(LoaderUtils.decodeText(new Uint8Array(e,0,4))===c){try{o[r.KHR_BINARY_GLTF]=new d(e);}catch(e){return void(n&&n(e))}i=o[r.KHR_BINARY_GLTF].content;}else i=LoaderUtils.decodeText(new Uint8Array(e));var u=JSON.parse(i);if(void 0===u.asset||u.asset.version[0]<2)n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));else {var p=new j(u,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});p.fileLoader.setRequestHeader(this.requestHeader);for(var h=0;h=0&&void 0===l[M]&&console.warn('THREE.GLTFLoader: Unknown extension "'+M+'".');}}p.setExtensions(o),p.setPlugins(l),p.parse(a,n);}}});var r={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:"KHR_materials_pbrSpecularGlossiness",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression"};function a(e){this.parser=e,this.name=r.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}};}function s(){this.name=r.KHR_MATERIALS_UNLIT;}function n(e){this.parser=e,this.name=r.KHR_MATERIALS_CLEARCOAT;}function i(e){this.parser=e,this.name=r.KHR_MATERIALS_TRANSMISSION;}function o(e){this.parser=e,this.name=r.KHR_TEXTURE_BASISU;}function l(e){this.parser=e,this.name=r.EXT_TEXTURE_WEBP,this.isSupported=null;}function u(e){this.name=r.EXT_MESHOPT_COMPRESSION,this.parser=e;}a.prototype._markDefs=function(){for(var e=this.parser,t=this.parser.json.nodes||[],r=0,a=t.length;r=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,n,i)},l.prototype.loadTexture=function(e){var t=this.name,r=this.parser,a=r.json,s=a.textures[e];if(!s.extensions||!s.extensions[t])return null;var n=s.extensions[t],i=a.images[n.source],o=r.textureLoader;if(i.uri){var l=r.options.manager.getHandler(i.uri);null!==l&&(o=l);}return this.detectSupport().then((function(s){if(s)return r.loadTextureImage(e,i,o);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return r.loadTexture(e)}))},l.prototype.detectSupport=function(){return this.isSupported||(this.isSupported=new Promise((function(e){var t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(1===t.height);};}))),this.isSupported},u.prototype.loadBufferView=function(e){var t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){var a=r.extensions[this.name],s=this.parser.getDependency("buffer",a.buffer),n=this.parser.options.meshoptDecoder;if(!n||!n.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return Promise.all([s,n.ready]).then((function(e){var t=a.byteOffset||0,r=a.byteLength||0,s=a.count,i=a.byteStride,o=new ArrayBuffer(s*i),l=new Uint8Array(e[0],t,r);return n.decodeGltfBuffer(new Uint8Array(o),s,i,l,a.mode,a.filter),o}))}return null};var c="glTF",p=1313821514,h=5130562;function d(e){this.name=r.KHR_BINARY_GLTF,this.content=null,this.body=null;var t=new DataView(e,0,12);if(this.header={magic:LoaderUtils.decodeText(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==c)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");for(var a=this.header.length-12,s=new DataView(e,12),n=0;n",t).replace("#include ",r).replace("#include ",a).replace("#include ",s).replace("#include ",n);},Object.defineProperties(this,{specular:{get:function(){return i.specular.value},set:function(e){i.specular.value=e;}},specularMap:{get:function(){return i.specularMap.value},set:function(e){i.specularMap.value=e,e?this.defines.USE_SPECULARMAP="":delete this.defines.USE_SPECULARMAP;}},glossiness:{get:function(){return i.glossiness.value},set:function(e){i.glossiness.value=e;}},glossinessMap:{get:function(){return i.glossinessMap.value},set:function(e){i.glossinessMap.value=e,e?(this.defines.USE_GLOSSINESSMAP="",this.defines.USE_UV=""):(delete this.defines.USE_GLOSSINESSMAP,delete this.defines.USE_UV);}}}),delete this.metalness,delete this.roughness,delete this.metalnessMap,delete this.roughnessMap,this.setValues(e);}function v(){return {name:r.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,specularGlossinessParams:["color","map","lightMap","lightMapIntensity","aoMap","aoMapIntensity","emissive","emissiveIntensity","emissiveMap","bumpMap","bumpScale","normalMap","normalMapType","displacementMap","displacementScale","displacementBias","specularMap","specular","glossinessMap","glossiness","alphaMap","envMap","envMapIntensity","refractionRatio"],getMaterialType:function(){return g},extendParams:function(e,t,r){var a=t.extensions[this.name];e.color=new Color(1,1,1),e.opacity=1;var s=[];if(Array.isArray(a.diffuseFactor)){var n=a.diffuseFactor;e.color.fromArray(n),e.opacity=n[3];}if(void 0!==a.diffuseTexture&&s.push(r.assignTexture(e,"map",a.diffuseTexture)),e.emissive=new Color(0,0,0),e.glossiness=void 0!==a.glossinessFactor?a.glossinessFactor:1,e.specular=new Color(1,1,1),Array.isArray(a.specularFactor)&&e.specular.fromArray(a.specularFactor),void 0!==a.specularGlossinessTexture){var i=a.specularGlossinessTexture;s.push(r.assignTexture(e,"glossinessMap",i)),s.push(r.assignTexture(e,"specularMap",i));}return Promise.all(s)},createMaterial:function(e){var t=new g(e);return t.fog=!0,t.color=e.color,t.map=void 0===e.map?null:e.map,t.lightMap=null,t.lightMapIntensity=1,t.aoMap=void 0===e.aoMap?null:e.aoMap,t.aoMapIntensity=1,t.emissive=e.emissive,t.emissiveIntensity=1,t.emissiveMap=void 0===e.emissiveMap?null:e.emissiveMap,t.bumpMap=void 0===e.bumpMap?null:e.bumpMap,t.bumpScale=1,t.normalMap=void 0===e.normalMap?null:e.normalMap,t.normalMapType=TangentSpaceNormalMap,e.normalScale&&(t.normalScale=e.normalScale),t.displacementMap=null,t.displacementScale=1,t.displacementBias=0,t.specularMap=void 0===e.specularMap?null:e.specularMap,t.specular=e.specular,t.glossinessMap=void 0===e.glossinessMap?null:e.glossinessMap,t.glossiness=e.glossiness,t.alphaMap=null,t.envMap=void 0===e.envMap?null:e.envMap,t.envMapIntensity=1,t.refractionRatio=.98,t}}}function T(){this.name=r.KHR_MESH_QUANTIZATION;}function M(e,t,r,a){Interpolant.call(this,e,t,r,a);}f.prototype.decodePrimitive=function(e,t){var r=this.json,a=this.dracoLoader,s=e.extensions[this.name].bufferView,n=e.extensions[this.name].attributes,i={},o={},l={};for(var u in n){var c=P[u]||u.toLowerCase();i[c]=n[u];}for(u in e.attributes){c=P[u]||u.toLowerCase();if(void 0!==n[u]){var p=r.accessors[e.attributes[u]],h=_[p.componentType];l[c]=h,o[c]=!0===p.normalized;}}return t.getDependency("bufferView",s).then((function(e){return new Promise((function(t){a.decodeDracoFile(e,(function(e){for(var r in e.attributes){var a=e.attributes[r],s=o[r];void 0!==s&&(a.normalized=s);}t(e);}),i,l);}))}))},m.prototype.extendTexture=function(e,t){return e=e.clone(),void 0!==t.offset&&e.offset.fromArray(t.offset),void 0!==t.rotation&&(e.rotation=t.rotation),void 0!==t.scale&&e.repeat.fromArray(t.scale),void 0!==t.texCoord&&console.warn('THREE.GLTFLoader: Custom UV sets in "'+this.name+'" extension not yet supported.'),e.needsUpdate=!0,e},g.prototype=Object.create(MeshStandardMaterial.prototype),g.prototype.constructor=g,g.prototype.copy=function(e){return MeshStandardMaterial.prototype.copy.call(this,e),this.specularMap=e.specularMap,this.specular.copy(e.specular),this.glossinessMap=e.glossinessMap,this.glossiness=e.glossiness,delete this.metalness,delete this.roughness,delete this.metalnessMap,delete this.roughnessMap,this},M.prototype=Object.create(Interpolant.prototype),M.prototype.constructor=M,M.prototype.copySampleValue_=function(e){for(var t=this.resultBuffer,r=this.sampleValues,a=this.valueSize,s=e*a*3+a,n=0;n!==a;n++)t[n]=r[s+n];return t},M.prototype.beforeStart_=M.prototype.copySampleValue_,M.prototype.afterEnd_=M.prototype.copySampleValue_,M.prototype.interpolate_=function(e,t,r,a){for(var s=this.resultBuffer,n=this.sampleValues,i=this.valueSize,o=2*i,l=3*i,u=a-t,c=(r-t)/u,p=c*c,h=p*c,d=e*l,f=d-l,m=-2*h+3*p,g=h-p,v=1-m,T=g-p+c,M=0;M!==i;M++){var y=n[f+M+i],x=n[f+M+o]*u,R=n[d+M+i],S=n[d+M]*u;s[M]=v*y+T*x+m*R+g*S;}return s};var y=0,x=1,R=2,S=3,L=4,A=5,E=6,_={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},w={9728:NearestFilter,9729:LinearFilter,9984:NearestMipmapNearestFilter,9985:LinearMipmapNearestFilter,9986:NearestMipmapLinearFilter,9987:LinearMipmapLinearFilter},b={33071:ClampToEdgeWrapping,33648:MirroredRepeatWrapping,10497:RepeatWrapping},I={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},P={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv2",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},C={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},N={CUBICSPLINE:void 0,LINEAR:InterpolateLinear,STEP:InterpolateDiscrete},O="OPAQUE",F="MASK",U="BLEND";function H(e,t){return "string"!=typeof e||""===e?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}function D(e,t,r){for(var a in r.extensions)void 0===e[a]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[a]=r.extensions[a]);}function k(e,t){void 0!==t.extras&&("object"==typeof t.extras?Object.assign(e.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras));}function B(e,t){if(e.updateMorphTargets(),void 0!==t.weights)for(var r=0,a=t.weights.length;r=2&&n.setY(A,R[S*o+1]),o>=3&&n.setZ(A,R[S*o+2]),o>=4&&n.setW(A,R[S*o+3]),o>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return n}))},j.prototype.loadTexture=function(e){var t=this.json,r=this.options,a=t.textures[e],s=t.images[a.source],n=this.textureLoader;if(s.uri){var i=r.manager.getHandler(s.uri);null!==i&&(n=i);}return this.loadTextureImage(e,s,n)},j.prototype.loadTextureImage=function(e,t,r){var a=this,s=this.json,n=this.options,i=s.textures[e],o=self.URL||self.webkitURL,l=t.uri,u=!1,c=!0;if("image/jpeg"===t.mimeType&&(c=!1),void 0!==t.bufferView)l=a.getDependency("bufferView",t.bufferView).then((function(e){if("image/png"===t.mimeType){var r=new DataView(e,25,1).getUint8(0,!1);c=6===r||4===r||3===r;}u=!0;var a=new Blob([e],{type:t.mimeType});return l=o.createObjectURL(a)}));else if(void 0===t.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");return Promise.resolve(l).then((function(e){return new Promise((function(t,a){var s=t;!0===r.isImageBitmapLoader&&(s=function(e){t(new CanvasTexture(e));}),r.load(H(e,n.path),s,void 0,a);}))})).then((function(t){!0===u&&o.revokeObjectURL(l),t.flipY=!1,i.name&&(t.name=i.name),c||(t.format=RGBFormat);var r=(s.samplers||{})[i.sampler]||{};return t.magFilter=w[r.magFilter]||LinearFilter,t.minFilter=w[r.minFilter]||LinearMipmapLinearFilter,t.wrapS=b[r.wrapS]||RepeatWrapping,t.wrapT=b[r.wrapT]||RepeatWrapping,a.associations.set(t,{type:"textures",index:e}),t}))},j.prototype.assignTexture=function(e,t,a){var s=this;return this.getDependency("texture",a.index).then((function(n){if(void 0===a.texCoord||0==a.texCoord||"aoMap"===t&&1==a.texCoord||console.warn("THREE.GLTFLoader: Custom UV set "+a.texCoord+" for texture "+t+" not yet supported."),s.extensions[r.KHR_TEXTURE_TRANSFORM]){var i=void 0!==a.extensions?a.extensions[r.KHR_TEXTURE_TRANSFORM]:void 0;if(i){var o=s.associations.get(n);n=s.extensions[r.KHR_TEXTURE_TRANSFORM].extendTexture(n,i),s.associations.set(n,o);}}e[t]=n;}))},j.prototype.assignFinalMaterial=function(e){var t=e.geometry,r=e.material,a=void 0!==t.attributes.tangent,s=void 0!==t.attributes.color,n=void 0===t.attributes.normal,i=!0===e.isSkinnedMesh,o=Object.keys(t.morphAttributes).length>0,l=o&&void 0!==t.morphAttributes.normal;if(e.isPoints){var u="PointsMaterial:"+r.uuid,c=this.cache.get(u);c||(c=new PointsMaterial,Material.prototype.copy.call(c,r),c.color.copy(r.color),c.map=r.map,c.sizeAttenuation=!1,this.cache.add(u,c)),r=c;}else if(e.isLine){u="LineBasicMaterial:"+r.uuid;var p=this.cache.get(u);p||(p=new LineBasicMaterial,Material.prototype.copy.call(p,r),p.color.copy(r.color),this.cache.add(u,p)),r=p;}if(a||s||n||i||o){u="ClonedMaterial:"+r.uuid+":";r.isGLTFSpecularGlossinessMaterial&&(u+="specular-glossiness:"),i&&(u+="skinning:"),a&&(u+="vertex-tangents:"),s&&(u+="vertex-colors:"),n&&(u+="flat-shading:"),o&&(u+="morph-targets:"),l&&(u+="morph-normals:");var h=this.cache.get(u);h||(h=r.clone(),i&&(h.skinning=!0),s&&(h.vertexColors=!0),n&&(h.flatShading=!0),o&&(h.morphTargets=!0),l&&(h.morphNormals=!0),a&&(h.vertexTangents=!0,h.normalScale&&(h.normalScale.y*=-1),h.clearcoatNormalScale&&(h.clearcoatNormalScale.y*=-1)),this.cache.add(u,h),this.associations.set(h,this.associations.get(r))),r=h;}r.aoMap&&void 0===t.attributes.uv2&&void 0!==t.attributes.uv&&t.setAttribute("uv2",t.attributes.uv),e.material=r;},j.prototype.getMaterialType=function(){return MeshStandardMaterial},j.prototype.loadMaterial=function(e){var t,a=this,s=this.json,n=this.extensions,i=s.materials[e],o={},l=i.extensions||{},u=[];if(l[r.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]){var c=n[r.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];t=c.getMaterialType(),u.push(c.extendParams(o,i,a));}else if(l[r.KHR_MATERIALS_UNLIT]){var p=n[r.KHR_MATERIALS_UNLIT];t=p.getMaterialType(),u.push(p.extendParams(o,i,a));}else {var h=i.pbrMetallicRoughness||{};if(o.color=new Color(1,1,1),o.opacity=1,Array.isArray(h.baseColorFactor)){var d=h.baseColorFactor;o.color.fromArray(d),o.opacity=d[3];}void 0!==h.baseColorTexture&&u.push(a.assignTexture(o,"map",h.baseColorTexture)),o.metalness=void 0!==h.metallicFactor?h.metallicFactor:1,o.roughness=void 0!==h.roughnessFactor?h.roughnessFactor:1,void 0!==h.metallicRoughnessTexture&&(u.push(a.assignTexture(o,"metalnessMap",h.metallicRoughnessTexture)),u.push(a.assignTexture(o,"roughnessMap",h.metallicRoughnessTexture))),t=this._invokeOne((function(t){return t.getMaterialType&&t.getMaterialType(e)})),u.push(Promise.all(this._invokeAll((function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)}))));}!0===i.doubleSided&&(o.side=DoubleSide);var f=i.alphaMode||O;return f===U?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,f===F&&(o.alphaTest=void 0!==i.alphaCutoff?i.alphaCutoff:.5)),void 0!==i.normalTexture&&t!==MeshBasicMaterial&&(u.push(a.assignTexture(o,"normalMap",i.normalTexture)),o.normalScale=new Vector2(1,-1),void 0!==i.normalTexture.scale&&o.normalScale.set(i.normalTexture.scale,-i.normalTexture.scale)),void 0!==i.occlusionTexture&&t!==MeshBasicMaterial&&(u.push(a.assignTexture(o,"aoMap",i.occlusionTexture)),void 0!==i.occlusionTexture.strength&&(o.aoMapIntensity=i.occlusionTexture.strength)),void 0!==i.emissiveFactor&&t!==MeshBasicMaterial&&(o.emissive=(new Color).fromArray(i.emissiveFactor)),void 0!==i.emissiveTexture&&t!==MeshBasicMaterial&&u.push(a.assignTexture(o,"emissiveMap",i.emissiveTexture)),Promise.all(u).then((function(){var s;return s=t===g?n[r.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(o):new t(o),i.name&&(s.name=i.name),s.map&&(s.map.encoding=sRGBEncoding),s.emissiveMap&&(s.emissiveMap.encoding=sRGBEncoding),k(s,i),a.associations.set(s,{type:"materials",index:e}),i.extensions&&D(n,s,i),s}))},j.prototype.createUniqueName=function(e){for(var t=PropertyBinding.sanitizeNodeName(e||""),r=t,a=1;this.nodeNamesUsed[r];++a)r=t+"_"+a;return this.nodeNamesUsed[r]=!0,r},j.prototype.loadGeometries=function(e){var t=this,a=this.extensions,s=this.primitiveCache;function n(e){return a[r.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then((function(r){return K(r,e,t)}))}for(var i,o,l=[],u=0,c=e.length;u0&&B(p,n),p.name=r.createUniqueName(n.name||"mesh_"+e),k(p,n),d.extensions&&D(s,p,d),r.assignFinalMaterial(p),l.push(p);}if(1===l.length)return l[0];var m=new Group;for(u=0,c=l.length;u1?new Group:1===t.length?t[0]:new Object3D)!==t[0])for(var o=0,l=t.length;o>8&255]+_lut[e>>16&255]+_lut[e>>24&255]+"-"+_lut[255&t]+_lut[t>>8&255]+"-"+_lut[t>>16&15|64]+_lut[t>>24&255]+"-"+_lut[63&r|128]+_lut[r>>8&255]+"-"+_lut[r>>16&255]+_lut[r>>24&255]+_lut[255&i]+_lut[i>>8&255]+_lut[i>>16&255]+_lut[i>>24&255]).toLowerCase()}function clamp(e,t,r){return Math.max(t,Math.min(r,e))}function euclideanModulo(e,t){return (e%t+t)%t}function mapLinear(e,t,r,i,n){return i+(e-t)*(n-i)/(r-t)}function inverseLerp(e,t,r){return e!==t?(r-e)/(t-e):0}function lerp(e,t,r){return (1-r)*e+r*t}function damp(e,t,r,i){return lerp(e,t,1-Math.exp(-r*i))}function pingpong(e,t=1){return t-Math.abs(euclideanModulo(e,2*t)-t)}function smoothstep(e,t,r){return e<=t?0:e>=r?1:(e=(e-t)/(r-t))*e*(3-2*e)}function smootherstep(e,t,r){return e<=t?0:e>=r?1:(e=(e-t)/(r-t))*e*e*(e*(6*e-15)+10)}function randInt(e,t){return e+Math.floor(Math.random()*(t-e+1))}function randFloat(e,t){return e+Math.random()*(t-e)}function randFloatSpread(e){return e*(.5-Math.random())}function seededRandom(e){void 0!==e&&(_seed=e);let t=_seed+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}function degToRad(e){return e*DEG2RAD}function radToDeg(e){return e*RAD2DEG}function isPowerOfTwo(e){return 0==(e&e-1)&&0!==e}function ceilPowerOfTwo(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function floorPowerOfTwo(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function setQuaternionFromProperEuler(e,t,r,i,n){const a=Math.cos,s=Math.sin,o=a(r/2),l=s(r/2),c=a((t+i)/2),h=s((t+i)/2),u=a((t-i)/2),d=s((t-i)/2),p=a((i-t)/2),m=s((i-t)/2);switch(n){case"XYX":e.set(o*h,l*u,l*d,o*c);break;case"YZY":e.set(l*d,o*h,l*u,o*c);break;case"ZXZ":e.set(l*u,l*d,o*h,o*c);break;case"XZX":e.set(o*h,l*m,l*p,o*c);break;case"YXY":e.set(l*p,o*h,l*m,o*c);break;case"ZYZ":e.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n);}}function denormalize(e,t){switch(t.constructor){case Float32Array:return e;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function normalize(e,t){switch(t.constructor){case Float32Array:return e;case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}var MathUtils=Object.freeze({__proto__:null,DEG2RAD:DEG2RAD,RAD2DEG:RAD2DEG,generateUUID:generateUUID,clamp:clamp,euclideanModulo:euclideanModulo,mapLinear:mapLinear,inverseLerp:inverseLerp,lerp:lerp,damp:damp,pingpong:pingpong,smoothstep:smoothstep,smootherstep:smootherstep,randInt:randInt,randFloat:randFloat,randFloatSpread:randFloatSpread,seededRandom:seededRandom,degToRad:degToRad,radToDeg:radToDeg,isPowerOfTwo:isPowerOfTwo,ceilPowerOfTwo:ceilPowerOfTwo,floorPowerOfTwo:floorPowerOfTwo,setQuaternionFromProperEuler:setQuaternionFromProperEuler,normalize:normalize,denormalize:denormalize});class Vector2{constructor(e=0,t=0){Vector2.prototype.isVector2=!0,this.x=e,this.y=t;}get width(){return this.x}set width(e){this.x=e;}get height(){return this.y}set height(e){this.y=e;}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,r=this.y,i=e.elements;return this.x=i[0]*t+i[3]*r+i[6],this.y=i[1]*t+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){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(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y;return t*t+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const r=Math.cos(t),i=Math.sin(t),n=this.x-e.x,a=this.y-e.y;return this.x=n*r-a*i+e.x,this.y=n*i+a*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y;}}class Matrix3{constructor(){Matrix3.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1];}set(e,t,r,i,n,a,s,o,l){const c=this.elements;return c[0]=e,c[1]=i,c[2]=s,c[3]=t,c[4]=n,c[5]=o,c[6]=r,c[7]=a,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],this}extractBasis(e,t,r){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,n=this.elements,a=r[0],s=r[3],o=r[6],l=r[1],c=r[4],h=r[7],u=r[2],d=r[5],p=r[8],m=i[0],f=i[3],g=i[6],_=i[1],v=i[4],x=i[7],y=i[2],b=i[5],M=i[8];return n[0]=a*m+s*_+o*y,n[3]=a*f+s*v+o*b,n[6]=a*g+s*x+o*M,n[1]=l*m+c*_+h*y,n[4]=l*f+c*v+h*b,n[7]=l*g+c*x+h*M,n[2]=u*m+d*_+p*y,n[5]=u*f+d*v+p*b,n[8]=u*g+d*x+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[1],i=e[2],n=e[3],a=e[4],s=e[5],o=e[6],l=e[7],c=e[8];return t*a*c-t*s*l-r*n*c+r*s*o+i*n*l-i*a*o}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],n=e[3],a=e[4],s=e[5],o=e[6],l=e[7],c=e[8],h=c*a-s*l,u=s*o-c*n,d=l*n-a*o,p=t*h+r*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=h*m,e[1]=(i*l-c*r)*m,e[2]=(s*r-i*a)*m,e[3]=u*m,e[4]=(c*t-i*o)*m,e[5]=(i*n-s*t)*m,e[6]=d*m,e[7]=(r*o-l*t)*m,e[8]=(a*t-r*n)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,r,i,n,a,s){const o=Math.cos(n),l=Math.sin(n);return this.set(r*o,r*l,-r*(o*a+l*s)+a+e,-i*l,i*o,-i*(-l*a+o*s)+s+t,0,0,1),this}scale(e,t){const r=this.elements;return r[0]*=e,r[3]*=e,r[6]*=e,r[1]*=t,r[4]*=t,r[7]*=t,this}rotate(e){const t=Math.cos(e),r=Math.sin(e),i=this.elements,n=i[0],a=i[3],s=i[6],o=i[1],l=i[4],c=i[7];return i[0]=t*n+r*o,i[3]=t*a+r*l,i[6]=t*s+r*c,i[1]=-r*n+t*o,i[4]=-r*a+t*l,i[7]=-r*s+t*c,this}translate(e,t){const r=this.elements;return r[0]+=e*r[2],r[3]+=e*r[5],r[6]+=e*r[8],r[1]+=t*r[2],r[4]+=t*r[5],r[7]+=t*r[8],this}equals(e){const t=this.elements,r=e.elements;for(let e=0;e<9;e++)if(t[e]!==r[e])return !1;return !0}fromArray(e,t=0){for(let r=0;r<9;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e}clone(){return (new this.constructor).fromArray(this.elements)}}function arrayNeedsUint32(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return !0;return !1}const TYPED_ARRAYS={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function getTypedArray(e,t){return new TYPED_ARRAYS[e](t)}function createElementNS(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function SRGBToLinear(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function LinearToSRGB(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}const FN={srgb:{"srgb-linear":SRGBToLinear},"srgb-linear":{srgb:LinearToSRGB}},ColorManagement={legacyMode:!0,get workingColorSpace(){return "srgb-linear"},set workingColorSpace(e){console.warn("THREE.ColorManagement: .workingColorSpace is readonly.");},convert:function(e,t,r){if(this.legacyMode||t===r||!t||!r)return e;if(FN[t]&&void 0!==FN[t][r]){const i=FN[t][r];return e.r=i(e.r),e.g=i(e.g),e.b=i(e.b),e}throw new Error("Unsupported color space conversion.")},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)}},_colorKeywords={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},_rgb={r:0,g:0,b:0},_hslA={h:0,s:0,l:0},_hslB={h:0,s:0,l:0};function hue2rgb(e,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?e+6*(t-e)*r:r<.5?t:r<2/3?e+6*(t-e)*(2/3-r):e}function toComponents(e,t){return t.r=e.r,t.g=e.g,t.b=e.b,t}class Color{constructor(e,t,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,void 0===t&&void 0===r?this.set(e):this.setRGB(e,t,r)}set(e){return e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e),this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t="srgb"){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,ColorManagement.toWorkingColorSpace(this,t),this}setRGB(e,t,r,i="srgb-linear"){return this.r=e,this.g=t,this.b=r,ColorManagement.toWorkingColorSpace(this,i),this}setHSL(e,t,r,i="srgb-linear"){if(e=euclideanModulo(e,1),t=clamp(t,0,1),r=clamp(r,0,1),0===t)this.r=this.g=this.b=r;else {const i=r<=.5?r*(1+t):r+t-r*t,n=2*r-i;this.r=hue2rgb(n,i,e+1/3),this.g=hue2rgb(n,i,e),this.b=hue2rgb(n,i,e-1/3);}return ColorManagement.toWorkingColorSpace(this,i),this}setStyle(e,t="srgb"){function r(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.");}let i;if(i=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(e)){let e;const n=i[1],a=i[2];switch(n){case"rgb":case"rgba":if(e=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return this.r=Math.min(255,parseInt(e[1],10))/255,this.g=Math.min(255,parseInt(e[2],10))/255,this.b=Math.min(255,parseInt(e[3],10))/255,ColorManagement.toWorkingColorSpace(this,t),r(e[4]),this;if(e=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return this.r=Math.min(100,parseInt(e[1],10))/100,this.g=Math.min(100,parseInt(e[2],10))/100,this.b=Math.min(100,parseInt(e[3],10))/100,ColorManagement.toWorkingColorSpace(this,t),r(e[4]),this;break;case"hsl":case"hsla":if(e=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a)){const i=parseFloat(e[1])/360,n=parseFloat(e[2])/100,a=parseFloat(e[3])/100;return r(e[4]),this.setHSL(i,n,a,t)}}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const e=i[1],r=e.length;if(3===r)return this.r=parseInt(e.charAt(0)+e.charAt(0),16)/255,this.g=parseInt(e.charAt(1)+e.charAt(1),16)/255,this.b=parseInt(e.charAt(2)+e.charAt(2),16)/255,ColorManagement.toWorkingColorSpace(this,t),this;if(6===r)return this.r=parseInt(e.charAt(0)+e.charAt(1),16)/255,this.g=parseInt(e.charAt(2)+e.charAt(3),16)/255,this.b=parseInt(e.charAt(4)+e.charAt(5),16)/255,ColorManagement.toWorkingColorSpace(this,t),this}return e&&e.length>0?this.setColorName(e,t):this}setColorName(e,t="srgb"){const r=_colorKeywords[e.toLowerCase()];return void 0!==r?this.setHex(r,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=SRGBToLinear(e.r),this.g=SRGBToLinear(e.g),this.b=SRGBToLinear(e.b),this}copyLinearToSRGB(e){return this.r=LinearToSRGB(e.r),this.g=LinearToSRGB(e.g),this.b=LinearToSRGB(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e="srgb"){return ColorManagement.fromWorkingColorSpace(toComponents(this,_rgb),e),clamp(255*_rgb.r,0,255)<<16^clamp(255*_rgb.g,0,255)<<8^clamp(255*_rgb.b,0,255)<<0}getHexString(e="srgb"){return ("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t="srgb-linear"){ColorManagement.fromWorkingColorSpace(toComponents(this,_rgb),t);const r=_rgb.r,i=_rgb.g,n=_rgb.b,a=Math.max(r,i,n),s=Math.min(r,i,n);let o,l;const c=(s+a)/2;if(s===a)o=0,l=0;else {const e=a-s;switch(l=c<=.5?e/(a+s):e/(2-a-s),a){case r:o=(i-n)/e+(i2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=createElementNS("canvas");t.width=e.width,t.height=e.height;const r=t.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),n=i.data;for(let e=0;e1)switch(this.wrapS){case 1e3:e.x=e.x-Math.floor(e.x);break;case 1001:e.x=e.x<0?0:1;break;case 1002:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);}if(e.y<0||e.y>1)switch(this.wrapT){case 1e3:e.y=e.y-Math.floor(e.y);break;case 1001:e.y=e.y<0?0:1;break;case 1002:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0);}}Texture.DEFAULT_IMAGE=null,Texture.DEFAULT_MAPPING=300;class Vector4{constructor(e=0,t=0,r=0,i=1){Vector4.prototype.isVector4=!0,this.x=e,this.y=t,this.z=r,this.w=i;}get width(){return this.z}set width(e){this.z=e;}get height(){return this.w}set height(e){this.w=e;}set(e,t,r,i){return this.x=e,this.y=t,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){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: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,n=this.w,a=e.elements;return this.x=a[0]*t+a[4]*r+a[8]*i+a[12]*n,this.y=a[1]*t+a[5]*r+a[9]*i+a[13]*n,this.z=a[2]*t+a[6]*r+a[10]*i+a[14]*n,this.w=a[3]*t+a[7]*r+a[11]*i+a[15]*n,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,r,i,n;const a=e.elements,s=a[0],o=a[4],l=a[8],c=a[1],h=a[5],u=a[9],d=a[2],p=a[6],m=a[10];if(Math.abs(o-c)<.01&&Math.abs(l-d)<.01&&Math.abs(u-p)<.01){if(Math.abs(o+c)<.1&&Math.abs(l+d)<.1&&Math.abs(u+p)<.1&&Math.abs(s+h+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const e=(s+1)/2,a=(h+1)/2,f=(m+1)/2,g=(o+c)/4,_=(l+d)/4,v=(u+p)/4;return e>a&&e>f?e<.01?(r=0,i=.707106781,n=.707106781):(r=Math.sqrt(e),i=g/r,n=_/r):a>f?a<.01?(r=.707106781,i=0,n=.707106781):(i=Math.sqrt(a),r=g/i,n=v/i):f<.01?(r=.707106781,i=.707106781,n=0):(n=Math.sqrt(f),r=_/n,i=v/n),this.set(r,i,n,t),this}let f=Math.sqrt((p-u)*(p-u)+(l-d)*(l-d)+(c-o)*(c-o));return Math.abs(f)<.001&&(f=1),this.x=(p-u)/f,this.y=(l-d)/f,this.z=(c-o)/f,this.w=Math.acos((s+h+m-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){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.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this.w=e.w+(t.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w;}}class WebGLRenderTarget extends EventDispatcher{constructor(e,t,r={}){super(),this.isWebGLRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Vector4(0,0,e,t),this.scissorTest=!1,this.viewport=new Vector4(0,0,e,t);const i={width:e,height:t,depth:1};this.texture=new Texture(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.encoding),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=void 0!==r.generateMipmaps&&r.generateMipmaps,this.texture.internalFormat=void 0!==r.internalFormat?r.internalFormat:null,this.texture.minFilter=void 0!==r.minFilter?r.minFilter:1006,this.depthBuffer=void 0===r.depthBuffer||r.depthBuffer,this.stencilBuffer=void 0!==r.stencilBuffer&&r.stencilBuffer,this.depthTexture=void 0!==r.depthTexture?r.depthTexture:null,this.samples=void 0!==r.samples?r.samples:0;}setSize(e,t,r=1){this.width===e&&this.height===t&&this.depth===r||(this.width=e,this.height=t,this.depth=r,this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=r,this.dispose()),this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t);}clone(){return (new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new Source(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"});}}class DataArrayTexture extends Texture{constructor(e=null,t=1,r=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:r,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1;}}class WebGLArrayRenderTarget extends WebGLRenderTarget{constructor(e,t,r){super(e,t),this.isWebGLArrayRenderTarget=!0,this.depth=r,this.texture=new DataArrayTexture(null,e,t,r),this.texture.isRenderTargetTexture=!0;}}class Data3DTexture extends Texture{constructor(e=null,t=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:r,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1;}}class WebGL3DRenderTarget extends WebGLRenderTarget{constructor(e,t,r){super(e,t),this.isWebGL3DRenderTarget=!0,this.depth=r,this.texture=new Data3DTexture(null,e,t,r),this.texture.isRenderTargetTexture=!0;}}class WebGLMultipleRenderTargets extends WebGLRenderTarget{constructor(e,t,r,i={}){super(e,t,i),this.isWebGLMultipleRenderTargets=!0;const n=this.texture;this.texture=[];for(let e=0;e=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const n=Math.sqrt(i),a=Math.atan2(n,t*r);e=Math.sin(e*a)/n,s=Math.sin(s*a)/n;}const n=s*r;if(o=o*e+u*n,l=l*e+d*n,c=c*e+p*n,h=h*e+m*n,e===1-s){const e=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=e,l*=e,c*=e,h*=e;}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=h;}static multiplyQuaternionsFlat(e,t,r,i,n,a){const s=r[i],o=r[i+1],l=r[i+2],c=r[i+3],h=n[a],u=n[a+1],d=n[a+2],p=n[a+3];return e[t]=s*p+c*h+o*d-l*u,e[t+1]=o*p+c*u+l*h-s*d,e[t+2]=l*p+c*d+s*u-o*h,e[t+3]=c*p-s*h-o*u-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback();}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback();}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback();}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback();}set(e,t,r,i){return this._x=e,this._y=t,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t){const r=e._x,i=e._y,n=e._z,a=e._order,s=Math.cos,o=Math.sin,l=s(r/2),c=s(i/2),h=s(n/2),u=o(r/2),d=o(i/2),p=o(n/2);switch(a){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a);}return !1!==t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,r=t[0],i=t[4],n=t[8],a=t[1],s=t[5],o=t[9],l=t[2],c=t[6],h=t[10],u=r+s+h;if(u>0){const e=.5/Math.sqrt(u+1);this._w=.25/e,this._x=(c-o)*e,this._y=(n-l)*e,this._z=(a-i)*e;}else if(r>s&&r>h){const e=2*Math.sqrt(1+r-s-h);this._w=(c-o)/e,this._x=.25*e,this._y=(i+a)/e,this._z=(n+l)/e;}else if(s>h){const e=2*Math.sqrt(1+s-r-h);this._w=(n-l)/e,this._x=(i+a)/e,this._y=.25*e,this._z=(o+c)/e;}else {const e=2*Math.sqrt(1+h-r-s);this._w=(a-i)/e,this._x=(n+l)/e,this._y=(o+c)/e,this._z=.25*e;}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let r=e.dot(t)+1;return rMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(clamp(this.dot(e),-1,1)))}rotateTowards(e,t){const r=this.angleTo(e);if(0===r)return this;const i=Math.min(1,t/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const r=e._x,i=e._y,n=e._z,a=e._w,s=t._x,o=t._y,l=t._z,c=t._w;return this._x=r*c+a*s+i*l-n*o,this._y=i*c+a*o+n*s-r*l,this._z=n*c+a*l+r*o-i*s,this._w=a*c-r*s-i*o-n*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const r=this._x,i=this._y,n=this._z,a=this._w;let s=a*e._w+r*e._x+i*e._y+n*e._z;if(s<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,s=-s):this.copy(e),s>=1)return this._w=a,this._x=r,this._y=i,this._z=n,this;const o=1-s*s;if(o<=Number.EPSILON){const e=1-t;return this._w=e*a+t*this._w,this._x=e*r+t*this._x,this._y=e*i+t*this._y,this._z=e*n+t*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(o),c=Math.atan2(l,s),h=Math.sin((1-t)*c)/l,u=Math.sin(t*c)/l;return this._w=a*h+this._w*u,this._x=r*h+this._x*u,this._y=i*h+this._y*u,this._z=n*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(e,t,r){return this.copy(e).slerp(t,r)}random(){const e=Math.random(),t=Math.sqrt(1-e),r=Math.sqrt(e),i=2*Math.PI*Math.random(),n=2*Math.PI*Math.random();return this.set(t*Math.cos(i),r*Math.sin(n),r*Math.cos(n),t*Math.sin(i))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w;}}class Vector3{constructor(e=0,t=0,r=0){Vector3.prototype.isVector3=!0,this.x=e,this.y=t,this.z=r;}set(e,t,r){return void 0===r&&(r=this.z),this.x=e,this.y=t,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(_quaternion$4.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(_quaternion$4.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,r=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[3]*r+n[6]*i,this.y=n[1]*t+n[4]*r+n[7]*i,this.z=n[2]*t+n[5]*r+n[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,n=e.elements,a=1/(n[3]*t+n[7]*r+n[11]*i+n[15]);return this.x=(n[0]*t+n[4]*r+n[8]*i+n[12])*a,this.y=(n[1]*t+n[5]*r+n[9]*i+n[13])*a,this.z=(n[2]*t+n[6]*r+n[10]*i+n[14])*a,this}applyQuaternion(e){const t=this.x,r=this.y,i=this.z,n=e.x,a=e.y,s=e.z,o=e.w,l=o*t+a*i-s*r,c=o*r+s*t-n*i,h=o*i+n*r-a*t,u=-n*t-a*r-s*i;return this.x=l*o+u*-n+c*-s-h*-a,this.y=c*o+u*-a+h*-n-l*-s,this.z=h*o+u*-s+l*-a-c*-n,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,r=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[4]*r+n[8]*i,this.y=n[1]*t+n[5]*r+n[9]*i,this.z=n[2]*t+n[6]*r+n[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){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(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const r=e.x,i=e.y,n=e.z,a=t.x,s=t.y,o=t.z;return this.x=i*o-n*s,this.y=n*a-r*o,this.z=r*s-i*a,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const r=e.dot(this)/t;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return _vector$c.copy(this).projectOnVector(e),this.sub(_vector$c)}reflect(e){return this.sub(_vector$c.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const r=this.dot(e)/t;return Math.acos(clamp(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return t*t+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,r){const i=Math.sin(t)*e;return this.x=i*Math.sin(r),this.y=Math.cos(t)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,r){return this.x=e*Math.sin(t),this.y=r,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=r,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=2*(Math.random()-.5),t=Math.random()*Math.PI*2,r=Math.sqrt(1-e**2);return this.x=r*Math.cos(t),this.y=r*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z;}}const _vector$c=new Vector3,_quaternion$4=new Quaternion;class Box3{constructor(e=new Vector3(1/0,1/0,1/0),t=new Vector3(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t;}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){let t=1/0,r=1/0,i=1/0,n=-1/0,a=-1/0,s=-1/0;for(let o=0,l=e.length;on&&(n=l),c>a&&(a=c),h>s&&(s=h);}return this.min.set(t,r,i),this.max.set(n,a,s),this}setFromBufferAttribute(e){let t=1/0,r=1/0,i=1/0,n=-1/0,a=-1/0,s=-1/0;for(let o=0,l=e.count;on&&(n=l),c>a&&(a=c),h>s&&(s=h);}return this.min.set(t,r,i),this.max.set(n,a,s),this}setFromPoints(e){this.makeEmpty();for(let t=0,r=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return !(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,_vector$b),_vector$b.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,r;return e.normal.x>0?(t=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),t<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return !1;this.getCenter(_center),_extents.subVectors(this.max,_center),_v0$2.subVectors(e.a,_center),_v1$7.subVectors(e.b,_center),_v2$3.subVectors(e.c,_center),_f0.subVectors(_v1$7,_v0$2),_f1.subVectors(_v2$3,_v1$7),_f2.subVectors(_v0$2,_v2$3);let t=[0,-_f0.z,_f0.y,0,-_f1.z,_f1.y,0,-_f2.z,_f2.y,_f0.z,0,-_f0.x,_f1.z,0,-_f1.x,_f2.z,0,-_f2.x,-_f0.y,_f0.x,0,-_f1.y,_f1.x,0,-_f2.y,_f2.x,0];return !!satForAxes(t,_v0$2,_v1$7,_v2$3,_extents)&&(t=[1,0,0,0,1,0,0,0,1],!!satForAxes(t,_v0$2,_v1$7,_v2$3,_extents)&&(_triangleNormal.crossVectors(_f0,_f1),t=[_triangleNormal.x,_triangleNormal.y,_triangleNormal.z],satForAxes(t,_v0$2,_v1$7,_v2$3,_extents)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return _vector$b.copy(e).clamp(this.min,this.max).sub(e).length()}getBoundingSphere(e){return this.getCenter(e.center),e.radius=.5*this.getSize(_vector$b).length(),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(_points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),_points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),_points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),_points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),_points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),_points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),_points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),_points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(_points)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const _points=[new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3],_vector$b=new Vector3,_box$3=new Box3,_v0$2=new Vector3,_v1$7=new Vector3,_v2$3=new Vector3,_f0=new Vector3,_f1=new Vector3,_f2=new Vector3,_center=new Vector3,_extents=new Vector3,_triangleNormal=new Vector3,_testAxis=new Vector3;function satForAxes(e,t,r,i,n){for(let a=0,s=e.length-3;a<=s;a+=3){_testAxis.fromArray(e,a);const s=n.x*Math.abs(_testAxis.x)+n.y*Math.abs(_testAxis.y)+n.z*Math.abs(_testAxis.z),o=t.dot(_testAxis),l=r.dot(_testAxis),c=i.dot(_testAxis);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>s)return !1}return !0}const _box$2=new Box3,_v1$6=new Vector3,_toFarthestPoint=new Vector3,_toPoint=new Vector3;class Sphere{constructor(e=new Vector3,t=-1){this.center=e,this.radius=t;}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const r=this.center;void 0!==t?r.copy(t):_box$2.setFromPoints(e).getCenter(r);let i=0;for(let t=0,n=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){_toPoint.subVectors(e,this.center);const t=_toPoint.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),r=.5*(e-this.radius);this.center.add(_toPoint.multiplyScalar(r/e)),this.radius+=r;}return this}union(e){return !0===this.center.equals(e.center)?_toFarthestPoint.set(0,0,1).multiplyScalar(e.radius):_toFarthestPoint.subVectors(e.center,this.center).normalize().multiplyScalar(e.radius),this.expandByPoint(_v1$6.copy(e.center).add(_toFarthestPoint)),this.expandByPoint(_v1$6.copy(e.center).sub(_toFarthestPoint)),this}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return (new this.constructor).copy(this)}}const _vector$a=new Vector3,_segCenter=new Vector3,_segDir=new Vector3,_diff=new Vector3,_edge1=new Vector3,_edge2=new Vector3,_normal$1=new Vector3;class Ray{constructor(e=new Vector3,t=new Vector3(0,0,-1)){this.origin=e,this.direction=t;}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.direction).multiplyScalar(e).add(this.origin)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,_vector$a)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const r=t.dot(this.direction);return r<0?t.copy(this.origin):t.copy(this.direction).multiplyScalar(r).add(this.origin)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=_vector$a.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(_vector$a.copy(this.direction).multiplyScalar(t).add(this.origin),_vector$a.distanceToSquared(e))}distanceSqToSegment(e,t,r,i){_segCenter.copy(e).add(t).multiplyScalar(.5),_segDir.copy(t).sub(e).normalize(),_diff.copy(this.origin).sub(_segCenter);const n=.5*e.distanceTo(t),a=-this.direction.dot(_segDir),s=_diff.dot(this.direction),o=-_diff.dot(_segDir),l=_diff.lengthSq(),c=Math.abs(1-a*a);let h,u,d,p;if(c>0)if(h=a*o-s,u=a*s-o,p=n*c,h>=0)if(u>=-p)if(u<=p){const e=1/c;h*=e,u*=e,d=h*(h+a*u+2*s)+u*(a*h+u+2*o)+l;}else u=n,h=Math.max(0,-(a*u+s)),d=-h*h+u*(u+2*o)+l;else u=-n,h=Math.max(0,-(a*u+s)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-a*n+s)),u=h>0?-n:Math.min(Math.max(-n,-o),n),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-n,-o),n),d=u*(u+2*o)+l):(h=Math.max(0,-(a*n+s)),u=h>0?n:Math.min(Math.max(-n,-o),n),d=-h*h+u*(u+2*o)+l);else u=a>0?-n:n,h=Math.max(0,-(a*u+s)),d=-h*h+u*(u+2*o)+l;return r&&r.copy(this.direction).multiplyScalar(h).add(this.origin),i&&i.copy(_segDir).multiplyScalar(u).add(_segCenter),d}intersectSphere(e,t){_vector$a.subVectors(e.center,this.origin);const r=_vector$a.dot(this.direction),i=_vector$a.dot(_vector$a)-r*r,n=e.radius*e.radius;if(i>n)return null;const a=Math.sqrt(n-i),s=r-a,o=r+a;return s<0&&o<0?null:s<0?this.at(o,t):this.at(s,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/t;return r>=0?r:null}intersectPlane(e,t){const r=this.distanceToPlane(e);return null===r?null:this.at(r,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return !0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let r,i,n,a,s,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(r=(e.min.x-u.x)*l,i=(e.max.x-u.x)*l):(r=(e.max.x-u.x)*l,i=(e.min.x-u.x)*l),c>=0?(n=(e.min.y-u.y)*c,a=(e.max.y-u.y)*c):(n=(e.max.y-u.y)*c,a=(e.min.y-u.y)*c),r>a||n>i?null:((n>r||r!=r)&&(r=n),(a=0?(s=(e.min.z-u.z)*h,o=(e.max.z-u.z)*h):(s=(e.max.z-u.z)*h,o=(e.min.z-u.z)*h),r>o||s>i?null:((s>r||r!=r)&&(r=s),(o=0?r:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,_vector$a)}intersectTriangle(e,t,r,i,n){_edge1.subVectors(t,e),_edge2.subVectors(r,e),_normal$1.crossVectors(_edge1,_edge2);let a,s=this.direction.dot(_normal$1);if(s>0){if(i)return null;a=1;}else {if(!(s<0))return null;a=-1,s=-s;}_diff.subVectors(this.origin,e);const o=a*this.direction.dot(_edge2.crossVectors(_diff,_edge2));if(o<0)return null;const l=a*this.direction.dot(_edge1.cross(_diff));if(l<0)return null;if(o+l>s)return null;const c=-a*_diff.dot(_normal$1);return c<0?null:this.at(c/s,n)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return (new this.constructor).copy(this)}}class Matrix4{constructor(){Matrix4.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];}set(e,t,r,i,n,a,s,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=e,g[4]=t,g[8]=r,g[12]=i,g[1]=n,g[5]=a,g[9]=s,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return (new Matrix4).fromArray(this.elements)}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],t[9]=r[9],t[10]=r[10],t[11]=r[11],t[12]=r[12],t[13]=r[13],t[14]=r[14],t[15]=r[15],this}copyPosition(e){const t=this.elements,r=e.elements;return t[12]=r[12],t[13]=r[13],t[14]=r[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,r){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,t,r){return this.set(e.x,t.x,r.x,0,e.y,t.y,r.y,0,e.z,t.z,r.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,r=e.elements,i=1/_v1$5.setFromMatrixColumn(e,0).length(),n=1/_v1$5.setFromMatrixColumn(e,1).length(),a=1/_v1$5.setFromMatrixColumn(e,2).length();return t[0]=r[0]*i,t[1]=r[1]*i,t[2]=r[2]*i,t[3]=0,t[4]=r[4]*n,t[5]=r[5]*n,t[6]=r[6]*n,t[7]=0,t[8]=r[8]*a,t[9]=r[9]*a,t[10]=r[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,r=e.x,i=e.y,n=e.z,a=Math.cos(r),s=Math.sin(r),o=Math.cos(i),l=Math.sin(i),c=Math.cos(n),h=Math.sin(n);if("XYZ"===e.order){const e=a*c,r=a*h,i=s*c,n=s*h;t[0]=o*c,t[4]=-o*h,t[8]=l,t[1]=r+i*l,t[5]=e-n*l,t[9]=-s*o,t[2]=n-e*l,t[6]=i+r*l,t[10]=a*o;}else if("YXZ"===e.order){const e=o*c,r=o*h,i=l*c,n=l*h;t[0]=e+n*s,t[4]=i*s-r,t[8]=a*l,t[1]=a*h,t[5]=a*c,t[9]=-s,t[2]=r*s-i,t[6]=n+e*s,t[10]=a*o;}else if("ZXY"===e.order){const e=o*c,r=o*h,i=l*c,n=l*h;t[0]=e-n*s,t[4]=-a*h,t[8]=i+r*s,t[1]=r+i*s,t[5]=a*c,t[9]=n-e*s,t[2]=-a*l,t[6]=s,t[10]=a*o;}else if("ZYX"===e.order){const e=a*c,r=a*h,i=s*c,n=s*h;t[0]=o*c,t[4]=i*l-r,t[8]=e*l+n,t[1]=o*h,t[5]=n*l+e,t[9]=r*l-i,t[2]=-l,t[6]=s*o,t[10]=a*o;}else if("YZX"===e.order){const e=a*o,r=a*l,i=s*o,n=s*l;t[0]=o*c,t[4]=n-e*h,t[8]=i*h+r,t[1]=h,t[5]=a*c,t[9]=-s*c,t[2]=-l*c,t[6]=r*h+i,t[10]=e-n*h;}else if("XZY"===e.order){const e=a*o,r=a*l,i=s*o,n=s*l;t[0]=o*c,t[4]=-h,t[8]=l*c,t[1]=e*h+n,t[5]=a*c,t[9]=r*h-i,t[2]=i*h-r,t[6]=s*c,t[10]=n*h+e;}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(_zero,e,_one)}lookAt(e,t,r){const i=this.elements;return _z.subVectors(e,t),0===_z.lengthSq()&&(_z.z=1),_z.normalize(),_x.crossVectors(r,_z),0===_x.lengthSq()&&(1===Math.abs(r.z)?_z.x+=1e-4:_z.z+=1e-4,_z.normalize(),_x.crossVectors(r,_z)),_x.normalize(),_y.crossVectors(_z,_x),i[0]=_x.x,i[4]=_y.x,i[8]=_z.x,i[1]=_x.y,i[5]=_y.y,i[9]=_z.y,i[2]=_x.z,i[6]=_y.z,i[10]=_z.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,n=this.elements,a=r[0],s=r[4],o=r[8],l=r[12],c=r[1],h=r[5],u=r[9],d=r[13],p=r[2],m=r[6],f=r[10],g=r[14],_=r[3],v=r[7],x=r[11],y=r[15],b=i[0],M=i[4],S=i[8],w=i[12],T=i[1],A=i[5],C=i[9],E=i[13],L=i[2],P=i[6],R=i[10],D=i[14],I=i[3],B=i[7],V=i[11],N=i[15];return n[0]=a*b+s*T+o*L+l*I,n[4]=a*M+s*A+o*P+l*B,n[8]=a*S+s*C+o*R+l*V,n[12]=a*w+s*E+o*D+l*N,n[1]=c*b+h*T+u*L+d*I,n[5]=c*M+h*A+u*P+d*B,n[9]=c*S+h*C+u*R+d*V,n[13]=c*w+h*E+u*D+d*N,n[2]=p*b+m*T+f*L+g*I,n[6]=p*M+m*A+f*P+g*B,n[10]=p*S+m*C+f*R+g*V,n[14]=p*w+m*E+f*D+g*N,n[3]=_*b+v*T+x*L+y*I,n[7]=_*M+v*A+x*P+y*B,n[11]=_*S+v*C+x*R+y*V,n[15]=_*w+v*E+x*D+y*N,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[4],i=e[8],n=e[12],a=e[1],s=e[5],o=e[9],l=e[13],c=e[2],h=e[6],u=e[10],d=e[14];return e[3]*(+n*o*h-i*l*h-n*s*u+r*l*u+i*s*d-r*o*d)+e[7]*(+t*o*d-t*l*u+n*a*u-i*a*d+i*l*c-n*o*c)+e[11]*(+t*l*h-t*s*d-n*a*h+r*a*d+n*s*c-r*l*c)+e[15]*(-i*s*c-t*o*h+t*s*u+i*a*h-r*a*u+r*o*c)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=r),this}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],n=e[3],a=e[4],s=e[5],o=e[6],l=e[7],c=e[8],h=e[9],u=e[10],d=e[11],p=e[12],m=e[13],f=e[14],g=e[15],_=h*f*l-m*u*l+m*o*d-s*f*d-h*o*g+s*u*g,v=p*u*l-c*f*l-p*o*d+a*f*d+c*o*g-a*u*g,x=c*m*l-p*h*l+p*s*d-a*m*d-c*s*g+a*h*g,y=p*h*o-c*m*o-p*s*u+a*m*u+c*s*f-a*h*f,b=t*_+r*v+i*x+n*y;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/b;return e[0]=_*M,e[1]=(m*u*n-h*f*n-m*i*d+r*f*d+h*i*g-r*u*g)*M,e[2]=(s*f*n-m*o*n+m*i*l-r*f*l-s*i*g+r*o*g)*M,e[3]=(h*o*n-s*u*n-h*i*l+r*u*l+s*i*d-r*o*d)*M,e[4]=v*M,e[5]=(c*f*n-p*u*n+p*i*d-t*f*d-c*i*g+t*u*g)*M,e[6]=(p*o*n-a*f*n-p*i*l+t*f*l+a*i*g-t*o*g)*M,e[7]=(a*u*n-c*o*n+c*i*l-t*u*l-a*i*d+t*o*d)*M,e[8]=x*M,e[9]=(p*h*n-c*m*n-p*r*d+t*m*d+c*r*g-t*h*g)*M,e[10]=(a*m*n-p*s*n+p*r*l-t*m*l-a*r*g+t*s*g)*M,e[11]=(c*s*n-a*h*n-c*r*l+t*h*l+a*r*d-t*s*d)*M,e[12]=y*M,e[13]=(c*m*i-p*h*i+p*r*u-t*m*u-c*r*f+t*h*f)*M,e[14]=(p*s*i-a*m*i-p*r*o+t*m*o+a*r*f-t*s*f)*M,e[15]=(a*h*i-c*s*i+c*r*o-t*h*o-a*r*u+t*s*u)*M,this}scale(e){const t=this.elements,r=e.x,i=e.y,n=e.z;return t[0]*=r,t[4]*=i,t[8]*=n,t[1]*=r,t[5]*=i,t[9]*=n,t[2]*=r,t[6]*=i,t[10]*=n,t[3]*=r,t[7]*=i,t[11]*=n,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,r,i))}makeTranslation(e,t,r){return this.set(1,0,0,e,0,1,0,t,0,0,1,r,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,t,-r,0,0,r,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,0,r,0,0,1,0,0,-r,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,-r,0,0,r,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const r=Math.cos(t),i=Math.sin(t),n=1-r,a=e.x,s=e.y,o=e.z,l=n*a,c=n*s;return this.set(l*a+r,l*s-i*o,l*o+i*s,0,l*s+i*o,c*s+r,c*o-i*a,0,l*o-i*s,c*o+i*a,n*o*o+r,0,0,0,0,1),this}makeScale(e,t,r){return this.set(e,0,0,0,0,t,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,t,r,i,n,a){return this.set(1,r,n,0,e,1,a,0,t,i,1,0,0,0,0,1),this}compose(e,t,r){const i=this.elements,n=t._x,a=t._y,s=t._z,o=t._w,l=n+n,c=a+a,h=s+s,u=n*l,d=n*c,p=n*h,m=a*c,f=a*h,g=s*h,_=o*l,v=o*c,x=o*h,y=r.x,b=r.y,M=r.z;return i[0]=(1-(m+g))*y,i[1]=(d+x)*y,i[2]=(p-v)*y,i[3]=0,i[4]=(d-x)*b,i[5]=(1-(u+g))*b,i[6]=(f+_)*b,i[7]=0,i[8]=(p+v)*M,i[9]=(f-_)*M,i[10]=(1-(u+m))*M,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,r){const i=this.elements;let n=_v1$5.set(i[0],i[1],i[2]).length();const a=_v1$5.set(i[4],i[5],i[6]).length(),s=_v1$5.set(i[8],i[9],i[10]).length();this.determinant()<0&&(n=-n),e.x=i[12],e.y=i[13],e.z=i[14],_m1$2.copy(this);const o=1/n,l=1/a,c=1/s;return _m1$2.elements[0]*=o,_m1$2.elements[1]*=o,_m1$2.elements[2]*=o,_m1$2.elements[4]*=l,_m1$2.elements[5]*=l,_m1$2.elements[6]*=l,_m1$2.elements[8]*=c,_m1$2.elements[9]*=c,_m1$2.elements[10]*=c,t.setFromRotationMatrix(_m1$2),r.x=n,r.y=a,r.z=s,this}makePerspective(e,t,r,i,n,a){const s=this.elements,o=2*n/(t-e),l=2*n/(r-i),c=(t+e)/(t-e),h=(r+i)/(r-i),u=-(a+n)/(a-n),d=-2*a*n/(a-n);return s[0]=o,s[4]=0,s[8]=c,s[12]=0,s[1]=0,s[5]=l,s[9]=h,s[13]=0,s[2]=0,s[6]=0,s[10]=u,s[14]=d,s[3]=0,s[7]=0,s[11]=-1,s[15]=0,this}makeOrthographic(e,t,r,i,n,a){const s=this.elements,o=1/(t-e),l=1/(r-i),c=1/(a-n),h=(t+e)*o,u=(r+i)*l,d=(a+n)*c;return s[0]=2*o,s[4]=0,s[8]=0,s[12]=-h,s[1]=0,s[5]=2*l,s[9]=0,s[13]=-u,s[2]=0,s[6]=0,s[10]=-2*c,s[14]=-d,s[3]=0,s[7]=0,s[11]=0,s[15]=1,this}equals(e){const t=this.elements,r=e.elements;for(let e=0;e<16;e++)if(t[e]!==r[e])return !1;return !0}fromArray(e,t=0){for(let r=0;r<16;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e[t+9]=r[9],e[t+10]=r[10],e[t+11]=r[11],e[t+12]=r[12],e[t+13]=r[13],e[t+14]=r[14],e[t+15]=r[15],e}}const _v1$5=new Vector3,_m1$2=new Matrix4,_zero=new Vector3(0,0,0),_one=new Vector3(1,1,1),_x=new Vector3,_y=new Vector3,_z=new Vector3,_matrix$1=new Matrix4,_quaternion$3=new Quaternion;class Euler{constructor(e=0,t=0,r=0,i=Euler.DefaultOrder){this.isEuler=!0,this._x=e,this._y=t,this._z=r,this._order=i;}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback();}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback();}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback();}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback();}set(e,t,r,i=this._order){return this._x=e,this._y=t,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,r=!0){const i=e.elements,n=i[0],a=i[4],s=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(clamp(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-a,n)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-clamp(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(s,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,n),this._z=0);break;case"ZXY":this._x=Math.asin(clamp(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-a,l)):(this._y=0,this._z=Math.atan2(o,n));break;case"ZYX":this._y=Math.asin(-clamp(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,n)):(this._x=0,this._z=Math.atan2(-a,l));break;case"YZX":this._z=Math.asin(clamp(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,n)):(this._x=0,this._y=Math.atan2(s,d));break;case"XZY":this._z=Math.asin(-clamp(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(s,n)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t);}return this._order=t,!0===r&&this._onChangeCallback(),this}setFromQuaternion(e,t,r){return _matrix$1.makeRotationFromQuaternion(e),this.setFromRotationMatrix(_matrix$1,t,r)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return _quaternion$3.setFromEuler(this),this.setFromQuaternion(_quaternion$3,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order;}toVector3(){console.error("THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead");}}Euler.DefaultOrder="XYZ",Euler.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];class Layers{constructor(){this.mask=1;}set(e){this.mask=(1<>>0;}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(r.geometries=t),i.length>0&&(r.materials=i),n.length>0&&(r.textures=n),s.length>0&&(r.images=s),o.length>0&&(r.shapes=o),l.length>0&&(r.skeletons=l),c.length>0&&(r.animations=c),h.length>0&&(r.nodes=h);}return r.object=i,r;function a(e){const t=[];for(const r in e){const i=e[r];delete i.metadata,t.push(i);}return t}}clone(e){return (new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(n)):i.set(0,0,0)}static getBarycoord(e,t,r,i,n){_v0$1.subVectors(i,t),_v1$3.subVectors(r,t),_v2$2.subVectors(e,t);const a=_v0$1.dot(_v0$1),s=_v0$1.dot(_v1$3),o=_v0$1.dot(_v2$2),l=_v1$3.dot(_v1$3),c=_v1$3.dot(_v2$2),h=a*l-s*s;if(0===h)return n.set(-2,-1,-1);const u=1/h,d=(l*o-s*c)*u,p=(a*c-s*o)*u;return n.set(1-d-p,p,d)}static containsPoint(e,t,r,i){return this.getBarycoord(e,t,r,i,_v3$1),_v3$1.x>=0&&_v3$1.y>=0&&_v3$1.x+_v3$1.y<=1}static getUV(e,t,r,i,n,a,s,o){return this.getBarycoord(e,t,r,i,_v3$1),o.set(0,0),o.addScaledVector(n,_v3$1.x),o.addScaledVector(a,_v3$1.y),o.addScaledVector(s,_v3$1.z),o}static isFrontFacing(e,t,r,i){return _v0$1.subVectors(r,t),_v1$3.subVectors(e,t),_v0$1.cross(_v1$3).dot(i)<0}set(e,t,r){return this.a.copy(e),this.b.copy(t),this.c.copy(r),this}setFromPointsAndIndices(e,t,r,i){return this.a.copy(e[t]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,r,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return (new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return _v0$1.subVectors(this.c,this.b),_v1$3.subVectors(this.a,this.b),.5*_v0$1.cross(_v1$3).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Triangle.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Triangle.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,r,i,n){return Triangle.getUV(e,this.a,this.b,this.c,t,r,i,n)}containsPoint(e){return Triangle.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Triangle.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const r=this.a,i=this.b,n=this.c;let a,s;_vab.subVectors(i,r),_vac.subVectors(n,r),_vap.subVectors(e,r);const o=_vab.dot(_vap),l=_vac.dot(_vap);if(o<=0&&l<=0)return t.copy(r);_vbp.subVectors(e,i);const c=_vab.dot(_vbp),h=_vac.dot(_vbp);if(c>=0&&h<=c)return t.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return a=o/(o-c),t.copy(r).addScaledVector(_vab,a);_vcp.subVectors(e,n);const d=_vab.dot(_vcp),p=_vac.dot(_vcp);if(p>=0&&d<=p)return t.copy(n);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return s=l/(l-p),t.copy(r).addScaledVector(_vac,s);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return _vbc.subVectors(n,i),s=(h-c)/(h-c+(d-p)),t.copy(i).addScaledVector(_vbc,s);const g=1/(f+m+u);return a=m*g,s=u*g,t.copy(r).addScaledVector(_vab,a).addScaledVector(_vac,s)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}let materialId=0;class Material extends EventDispatcher{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:materialId++}),this.uuid=generateUUID(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0;}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e;}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const r=e[t];if(void 0===r){console.warn("THREE.Material: '"+t+"' parameter is undefined.");continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[t]=r:console.warn("THREE."+this.type+": '"+t+"' is not a property of this material.");}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const r={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const r in e){const i=e[r];delete i.metadata,t.push(i);}return t}if(r.uuid=this.uuid,r.type=this.type,""!==this.name&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),void 0!==this.roughness&&(r.roughness=this.roughness),void 0!==this.metalness&&(r.metalness=this.metalness),void 0!==this.sheen&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(r.shininess=this.shininess),void 0!==this.clearcoat&&(r.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.iridescence&&(r.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(r.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(r.combine=this.combine)),void 0!==this.envMapIntensity&&(r.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(r.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&(r.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(r.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(r.size=this.size),null!==this.shadowSide&&(r.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(r.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(r.blending=this.blending),0!==this.side&&(r.side=this.side),this.vertexColors&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),!0===this.transparent&&(r.transparent=this.transparent),r.depthFunc=this.depthFunc,r.depthTest=this.depthTest,r.depthWrite=this.depthWrite,r.colorWrite=this.colorWrite,r.stencilWrite=this.stencilWrite,r.stencilWriteMask=this.stencilWriteMask,r.stencilFunc=this.stencilFunc,r.stencilRef=this.stencilRef,r.stencilFuncMask=this.stencilFuncMask,r.stencilFail=this.stencilFail,r.stencilZFail=this.stencilZFail,r.stencilZPass=this.stencilZPass,void 0!==this.rotation&&0!==this.rotation&&(r.rotation=this.rotation),!0===this.polygonOffset&&(r.polygonOffset=!0),0!==this.polygonOffsetFactor&&(r.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(r.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(r.linewidth=this.linewidth),void 0!==this.dashSize&&(r.dashSize=this.dashSize),void 0!==this.gapSize&&(r.gapSize=this.gapSize),void 0!==this.scale&&(r.scale=this.scale),!0===this.dithering&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),!0===this.alphaToCoverage&&(r.alphaToCoverage=this.alphaToCoverage),!0===this.premultipliedAlpha&&(r.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(r.wireframe=this.wireframe),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(r.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(r.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(r.flatShading=this.flatShading),!1===this.visible&&(r.visible=!1),!1===this.toneMapped&&(r.toneMapped=!1),!1===this.fog&&(r.fog=!1),"{}"!==JSON.stringify(this.userData)&&(r.userData=this.userData),t){const t=i(e.textures),n=i(e.images);t.length>0&&(r.textures=t),n.length>0&&(r.images=n);}return r}clone(){return (new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let r=null;if(null!==t){const e=t.length;r=new Array(e);for(let i=0;i!==e;++i)r[i]=t[i].clone();}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"});}set needsUpdate(e){!0===e&&this.version++;}}class MeshBasicMaterial extends Material{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Color(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e);}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const _vector$9=new Vector3,_vector2$1=new Vector2;class BufferAttribute{constructor(e,t,r){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=!0===r,this.usage=35044,this.updateRange={offset:0,count:-1},this.version=0;}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++;}setUsage(e){return this.usage=e,this}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this}copyAt(e,t,r){e*=this.itemSize,r*=t.itemSize;for(let i=0,n=this.itemSize;i0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const r in t)void 0!==t[r]&&(e[r]=t[r]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const r=this.attributes;for(const t in r){const i=r[t];e.data.attributes[t]=i.toJSON(e.data);}const i={};let n=!1;for(const t in this.morphAttributes){const r=this.morphAttributes[t],a=[];for(let t=0,i=r.length;t0&&(i[t]=a,n=!0);}n&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const s=this.boundingSphere;return null!==s&&(e.data.boundingSphere={center:s.center.toArray(),radius:s.radius}),e}clone(){return (new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const r=e.index;null!==r&&this.setIndex(r.clone(t));const i=e.attributes;for(const e in i){const r=i[e];this.setAttribute(e,r.clone(t));}const n=e.morphAttributes;for(const e in n){const r=[],i=n[e];for(let e=0,n=i.length;e0){const r=e[t[0]];if(void 0!==r){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=r.length;er.far?null:{distance:c,point:_intersectionPointWorld.clone(),object:e}}function checkBufferGeometryIntersection(e,t,r,i,n,a,s,o,l,c,h,u){_vA$1.fromBufferAttribute(n,c),_vB$1.fromBufferAttribute(n,h),_vC$1.fromBufferAttribute(n,u);const d=e.morphTargetInfluences;if(a&&d){_morphA.set(0,0,0),_morphB.set(0,0,0),_morphC.set(0,0,0);for(let e=0,t=a.length;e0?1:-1,c.push(C.x,C.y,C.z),h.push(o/f),h.push(1-a/g),T+=1;}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader;const r={};for(const e in this.extensions)!0===this.extensions[e]&&(r[e]=!0);return Object.keys(r).length>0&&(t.extensions=r),t}}class Camera extends Object3D{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Matrix4,this.projectionMatrix=new Matrix4,this.projectionMatrixInverse=new Matrix4;}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(-t[8],-t[9],-t[10]).normalize()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert();}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert();}clone(){return (new this.constructor).copy(this)}}class PerspectiveCamera extends Camera{constructor(e=50,t=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix();}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*RAD2DEG*Math.atan(t),this.updateProjectionMatrix();}getFocalLength(){const e=Math.tan(.5*DEG2RAD*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*RAD2DEG*Math.atan(Math.tan(.5*DEG2RAD*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,t,r,i,n,a){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=n,this.view.height=a,this.updateProjectionMatrix();}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix();}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*DEG2RAD*this.fov)/this.zoom,r=2*t,i=this.aspect*r,n=-.5*i;const a=this.view;if(null!==this.view&&this.view.enabled){const e=a.fullWidth,s=a.fullHeight;n+=a.offsetX*i/e,t-=a.offsetY*r/s,i*=a.width/e,r*=a.height/s;}const s=this.filmOffset;0!==s&&(n+=e*s/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+i,t,t-r,e,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert();}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const fov=90,aspect=1;class CubeCamera extends Object3D{constructor(e,t,r){super(),this.type="CubeCamera",this.renderTarget=r;const i=new PerspectiveCamera(90,1,e,t);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new Vector3(1,0,0)),this.add(i);const n=new PerspectiveCamera(90,1,e,t);n.layers=this.layers,n.up.set(0,-1,0),n.lookAt(new Vector3(-1,0,0)),this.add(n);const a=new PerspectiveCamera(90,1,e,t);a.layers=this.layers,a.up.set(0,0,1),a.lookAt(new Vector3(0,1,0)),this.add(a);const s=new PerspectiveCamera(90,1,e,t);s.layers=this.layers,s.up.set(0,0,-1),s.lookAt(new Vector3(0,-1,0)),this.add(s);const o=new PerspectiveCamera(90,1,e,t);o.layers=this.layers,o.up.set(0,-1,0),o.lookAt(new Vector3(0,0,1)),this.add(o);const l=new PerspectiveCamera(90,1,e,t);l.layers=this.layers,l.up.set(0,-1,0),l.lookAt(new Vector3(0,0,-1)),this.add(l);}update(e,t){null===this.parent&&this.updateMatrixWorld();const r=this.renderTarget,[i,n,a,s,o,l]=this.children,c=e.getRenderTarget(),h=e.toneMapping,u=e.xr.enabled;e.toneMapping=0,e.xr.enabled=!1;const d=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0),e.render(t,i),e.setRenderTarget(r,1),e.render(t,n),e.setRenderTarget(r,2),e.render(t,a),e.setRenderTarget(r,3),e.render(t,s),e.setRenderTarget(r,4),e.render(t,o),r.texture.generateMipmaps=d,e.setRenderTarget(r,5),e.render(t,l),e.setRenderTarget(c),e.toneMapping=h,e.xr.enabled=u,r.texture.needsPMREMUpdate=!0;}}class CubeTexture extends Texture{constructor(e,t,r,i,n,a,s,o,l,c){super(e=void 0!==e?e:[],t=void 0!==t?t:301,r,i,n,a,s,o,l,c),this.isCubeTexture=!0,this.flipY=!1;}get images(){return this.image}set images(e){this.image=e;}}class WebGLCubeRenderTarget extends WebGLRenderTarget{constructor(e,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new CubeTexture(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.encoding),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:1006;}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.encoding=t.encoding,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new BoxGeometry(5,5,5),n=new ShaderMaterial({name:"CubemapFromEquirect",uniforms:cloneUniforms(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:1,blending:0});n.uniforms.tEquirect.value=t;const a=new Mesh(i,n),s=t.minFilter;1008===t.minFilter&&(t.minFilter=1006);return new CubeCamera(1,10,this).update(e,a),t.minFilter=s,a.geometry.dispose(),a.material.dispose(),this}clear(e,t,r,i){const n=e.getRenderTarget();for(let n=0;n<6;n++)e.setRenderTarget(this,n),e.clear(t,r,i);e.setRenderTarget(n);}}const _vector1=new Vector3,_vector2=new Vector3,_normalMatrix=new Matrix3;class Plane{constructor(e=new Vector3(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t;}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,r,i){return this.normal.set(e,t,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,r){const i=_vector1.subVectors(r,t).cross(_vector2.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(this.normal).multiplyScalar(-this.distanceToPoint(e)).add(e)}intersectLine(e,t){const r=e.delta(_vector1),i=this.normal.dot(r);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const n=-(e.start.dot(this.normal)+this.constant)/i;return n<0||n>1?null:t.copy(r).multiplyScalar(n).add(e.start)}intersectsLine(e){const t=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return t<0&&r>0||r<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const r=t||_normalMatrix.getNormalMatrix(e),i=this.coplanarPoint(_vector1).applyMatrix4(e),n=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(n),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return (new this.constructor).copy(this)}}const _sphere$2=new Sphere,_vector$7=new Vector3;class Frustum{constructor(e=new Plane,t=new Plane,r=new Plane,i=new Plane,n=new Plane,a=new Plane){this.planes=[e,t,r,i,n,a];}set(e,t,r,i,n,a){const s=this.planes;return s[0].copy(e),s[1].copy(t),s[2].copy(r),s[3].copy(i),s[4].copy(n),s[5].copy(a),this}copy(e){const t=this.planes;for(let r=0;r<6;r++)t[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e){const t=this.planes,r=e.elements,i=r[0],n=r[1],a=r[2],s=r[3],o=r[4],l=r[5],c=r[6],h=r[7],u=r[8],d=r[9],p=r[10],m=r[11],f=r[12],g=r[13],_=r[14],v=r[15];return t[0].setComponents(s-i,h-o,m-u,v-f).normalize(),t[1].setComponents(s+i,h+o,m+u,v+f).normalize(),t[2].setComponents(s+n,h+l,m+d,v+g).normalize(),t[3].setComponents(s-n,h-l,m-d,v-g).normalize(),t[4].setComponents(s-a,h-c,m-p,v-_).normalize(),t[5].setComponents(s+a,h+c,m+p,v+_).normalize(),this}intersectsObject(e){const t=e.geometry;return null===t.boundingSphere&&t.computeBoundingSphere(),_sphere$2.copy(t.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(_sphere$2)}intersectsSprite(e){return _sphere$2.center.set(0,0,0),_sphere$2.radius=.7071067811865476,_sphere$2.applyMatrix4(e.matrixWorld),this.intersectsSphere(_sphere$2)}intersectsSphere(e){const t=this.planes,r=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(r)0?e.max.x:e.min.x,_vector$7.y=i.normal.y>0?e.max.y:e.min.y,_vector$7.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(_vector$7)<0)return !1}return !0}containsPoint(e){const t=this.planes;for(let r=0;r<6;r++)if(t[r].distanceToPoint(e)<0)return !1;return !0}clone(){return (new this.constructor).copy(this)}}function WebGLAnimation(){let e=null,t=!1,r=null,i=null;function n(t,a){r(t,a),i=e.requestAnimationFrame(n);}return {start:function(){!0!==t&&null!==r&&(i=e.requestAnimationFrame(n),t=!0);},stop:function(){e.cancelAnimationFrame(i),t=!1;},setAnimationLoop:function(e){r=e;},setContext:function(t){e=t;}}}function WebGLAttributes(e,t){const r=t.isWebGL2,i=new WeakMap;return {get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),i.get(e)},remove:function(t){t.isInterleavedBufferAttribute&&(t=t.data);const r=i.get(t);r&&(e.deleteBuffer(r.buffer),i.delete(t));},update:function(t,n){if(t.isGLBufferAttribute){const e=i.get(t);return void((!e||e.version=0){const r=n[t];let i=a[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===r)return !0;if(r.attribute!==i)return !0;if(i&&r.data!==i.data)return !0;s++;}}return c.attributesNum!==s||c.index!==i}(n,x,d,y),b&&function(e,t,r,i){const n={},a=t.attributes;let s=0;const o=r.getAttributes();for(const t in o){if(o[t].location>=0){let r=a[t];void 0===r&&("instanceMatrix"===t&&e.instanceMatrix&&(r=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(r=e.instanceColor));const i={};i.attribute=r,r&&r.data&&(i.data=r.data),n[t]=i,s++;}}c.attributes=n,c.attributesNum=s,c.index=i;}(n,x,d,y);}else {const e=!0===l.wireframe;c.geometry===x.id&&c.program===d.id&&c.wireframe===e||(c.geometry=x.id,c.program=d.id,c.wireframe=e,b=!0);}null!==y&&r.update(y,34963),(b||h)&&(h=!1,function(n,a,s,o){if(!1===i.isWebGL2&&(n.isInstancedMesh||o.isInstancedBufferGeometry)&&null===t.get("ANGLE_instanced_arrays"))return;m();const l=o.attributes,c=s.getAttributes(),h=a.defaultAttributeValues;for(const t in c){const i=c[t];if(i.location>=0){let a=l[t];if(void 0===a&&("instanceMatrix"===t&&n.instanceMatrix&&(a=n.instanceMatrix),"instanceColor"===t&&n.instanceColor&&(a=n.instanceColor)),void 0!==a){const t=a.normalized,s=a.itemSize,l=r.get(a);if(void 0===l)continue;const c=l.buffer,h=l.type,u=l.bytesPerElement;if(a.isInterleavedBufferAttribute){const r=a.data,l=r.stride,d=a.offset;if(r.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(35632,36338).precision>0)return "highp";t="mediump";}return "mediump"===t&&e.getShaderPrecisionFormat(35633,36337).precision>0&&e.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}const a="undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext||"undefined"!=typeof WebGL2ComputeRenderingContext&&e instanceof WebGL2ComputeRenderingContext;let s=void 0!==r.precision?r.precision:"highp";const o=n(s);o!==s&&(console.warn("THREE.WebGLRenderer:",s,"not supported, using",o,"instead."),s=o);const l=a||t.has("WEBGL_draw_buffers"),c=!0===r.logarithmicDepthBuffer,h=e.getParameter(34930),u=e.getParameter(35660),d=e.getParameter(3379),p=e.getParameter(34076),m=e.getParameter(34921),f=e.getParameter(36347),g=e.getParameter(36348),_=e.getParameter(36349),v=u>0,x=a||t.has("OES_texture_float");return {isWebGL2:a,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");i=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT);}else i=0;return i},getMaxPrecision:n,precision:s,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:d,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:f,maxVaryings:g,maxFragmentUniforms:_,vertexTextures:v,floatFragmentTextures:x,floatVertexTextures:v&&x,maxSamples:a?e.getParameter(36183):0}}function WebGLClipping(e){const t=this;let r=null,i=0,n=!1,a=!1;const s=new Plane,o=new Matrix3,l={value:null,needsUpdate:!1};function c(){l.value!==r&&(l.value=r,l.needsUpdate=i>0),t.numPlanes=i,t.numIntersection=0;}function h(e,r,i,n){const a=null!==e?e.length:0;let c=null;if(0!==a){if(c=l.value,!0!==n||null===c){const t=i+4*a,n=r.matrixWorldInverse;o.getNormalMatrix(n),(null===c||c.length0){const s=new WebGLCubeRenderTarget(a.height/2);return s.fromEquirectangularTexture(e,n),t.set(n,s),n.addEventListener("dispose",i),r(s.texture,n.mapping)}return null}}}return n},dispose:function(){t=new WeakMap;}}}ShaderLib.physical={uniforms:mergeUniforms([ShaderLib.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatNormalScale:{value:new Vector2(1,1)},clearcoatNormalMap:{value:null},iridescence:{value:0},iridescenceMap:{value:null},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},sheen:{value:0},sheenColor:{value:new Color(0)},sheenColorMap:{value:null},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},transmission:{value:0},transmissionMap:{value:null},transmissionSamplerSize:{value:new Vector2},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:0},attenuationColor:{value:new Color(0)},specularIntensity:{value:1},specularIntensityMap:{value:null},specularColor:{value:new Color(1,1,1)},specularColorMap:{value:null}}]),vertexShader:ShaderChunk.meshphysical_vert,fragmentShader:ShaderChunk.meshphysical_frag};class OrthographicCamera extends Camera{constructor(e=-1,t=1,r=1,i=-1,n=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=r,this.bottom=i,this.near=n,this.far=a,this.updateProjectionMatrix();}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,r,i,n,a){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=n,this.view.height=a,this.updateProjectionMatrix();}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix();}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let n=r-e,a=r+e,s=i+t,o=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=e*this.view.offsetX,a=n+e*this.view.width,s-=t*this.view.offsetY,o=s-t*this.view.height;}this.projectionMatrix.makeOrthographic(n,a,s,o,this.near,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert();}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}const LOD_MIN=4,EXTRA_LOD_SIGMA=[.125,.215,.35,.446,.526,.582],MAX_SAMPLES=20,_flatCamera=new OrthographicCamera,_clearColor=new Color;let _oldTarget=null;const PHI=(1+Math.sqrt(5))/2,INV_PHI=1/PHI,_axisDirections=[new Vector3(1,1,1),new Vector3(-1,1,1),new Vector3(1,1,-1),new Vector3(-1,1,-1),new Vector3(0,PHI,INV_PHI),new Vector3(0,PHI,-INV_PHI),new Vector3(INV_PHI,0,PHI),new Vector3(-INV_PHI,0,PHI),new Vector3(PHI,INV_PHI,0),new Vector3(-PHI,INV_PHI,0)];class PMREMGenerator{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial);}fromScene(e,t=0,r=.1,i=100){_oldTarget=this._renderer.getRenderTarget(),this._setSize(256);const n=this._allocateTargets();return n.depthBuffer=!0,this._sceneToCubeUV(e,r,i,n),t>0&&this._blur(n,0,0,t),this._applyPMREM(n),this._cleanup(n),n}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=_getCubemapMaterial(),this._compileMaterial(this._cubemapMaterial));}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=_getEquirectMaterial(),this._compileMaterial(this._equirectMaterial));}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose();}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax);}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e2?l:0,l,l),o.setRenderTarget(i),d&&o.render(u,n),o.render(e,n);}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,e.background=p;}_textureToCubeUV(e,t){const r=this._renderer,i=301===e.mapping||302===e.mapping;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=_getCubemapMaterial()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=_getEquirectMaterial());const n=i?this._cubemapMaterial:this._equirectMaterial,a=new Mesh(this._lodPlanes[0],n);n.uniforms.envMap.value=e;const s=this._cubeSize;_setViewport(t,0,0,3*s,2*s),r.setRenderTarget(t),r.render(a,_flatCamera);}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;for(let t=1;t20&&console.warn(`sigmaRadians, ${n}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let e=0;e<20;++e){const t=e/p,r=Math.exp(-t*t/2);f.push(r),0===e?g+=r:e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(c,_flatCamera);}}function _createPlanes(e){const t=[],r=[],i=[];let n=e;const a=e-4+1+EXTRA_LOD_SIGMA.length;for(let s=0;se-4?o=EXTRA_LOD_SIGMA[s-e+4-1]:0===s&&(o=0),i.push(o);const l=1/(a-2),c=-l,h=1+l,u=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,p=6,m=3,f=2,g=1,_=new Float32Array(m*p*d),v=new Float32Array(f*p*d),x=new Float32Array(g*p*d);for(let e=0;e2?0:-1,i=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0];_.set(i,m*p*e),v.set(u,f*p*e);const n=[e,e,e,e,e,e];x.set(n,g*p*e);}const y=new BufferGeometry;y.setAttribute("position",new BufferAttribute(_,m)),y.setAttribute("uv",new BufferAttribute(v,f)),y.setAttribute("faceIndex",new BufferAttribute(x,g)),t.push(y),n>4&&n--;}return {lodPlanes:t,sizeLods:r,sigmas:i}}function _createRenderTarget(e,t,r){const i=new WebGLRenderTarget(e,t,r);return i.texture.mapping=306,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function _setViewport(e,t,r,i,n){e.viewport.set(t,r,i,n),e.scissor.set(t,r,i,n);}function _getBlurShader(e,t,r){const i=new Float32Array(20),n=new Vector3(0,1,0);return new ShaderMaterial({name:"SphericalGaussianBlur",defines:{n:20,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/r,CUBEUV_MAX_MIP:e+".0"},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:_getCommonVertexShader(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function _getEquirectMaterial(){return new ShaderMaterial({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:_getCommonVertexShader(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function _getCubemapMaterial(){return new ShaderMaterial({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:_getCommonVertexShader(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function _getCommonVertexShader(){return "\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function WebGLCubeUVMaps(e){let t=new WeakMap,r=null;function i(e){const r=e.target;r.removeEventListener("dispose",i);const n=t.get(r);void 0!==n&&(t.delete(r),n.dispose());}return {get:function(n){if(n&&n.isTexture){const a=n.mapping,s=303===a||304===a,o=301===a||302===a;if(s||o){if(n.isRenderTargetTexture&&!0===n.needsPMREMUpdate){n.needsPMREMUpdate=!1;let i=t.get(n);return null===r&&(r=new PMREMGenerator(e)),i=s?r.fromEquirectangular(n,i):r.fromCubemap(n,i),t.set(n,i),i.texture}if(t.has(n))return t.get(n).texture;{const a=n.image;if(s&&a&&a.height>0||o&&a&&function(e){let t=0;for(let r=0;r<6;r++)void 0!==e[r]&&t++;return 6===t}(a)){null===r&&(r=new PMREMGenerator(e));const a=s?r.fromEquirectangular(n):r.fromCubemap(n);return t.set(n,a),n.addEventListener("dispose",i),a.texture}return null}}}return n},dispose:function(){t=new WeakMap,null!==r&&(r.dispose(),r=null);}}}function WebGLExtensions(e){const t={};function r(r){if(void 0!==t[r])return t[r];let i;switch(r){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(r);}return t[r]=i,i}return {has:function(e){return null!==r(e)},init:function(e){e.isWebGL2?r("EXT_color_buffer_float"):(r("WEBGL_depth_texture"),r("OES_texture_float"),r("OES_texture_half_float"),r("OES_texture_half_float_linear"),r("OES_standard_derivatives"),r("OES_element_index_uint"),r("OES_vertex_array_object"),r("ANGLE_instanced_arrays")),r("OES_texture_float_linear"),r("EXT_color_buffer_half_float"),r("WEBGL_multisampled_render_to_texture");},get:function(e){const t=r(e);return null===t&&console.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function WebGLGeometries(e,t,r,i){const n={},a=new WeakMap;function s(e){const o=e.target;null!==o.index&&t.remove(o.index);for(const e in o.attributes)t.remove(o.attributes[e]);o.removeEventListener("dispose",s),delete n[o.id];const l=a.get(o);l&&(t.remove(l),a.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,r.memory.geometries--;}function o(e){const r=[],i=e.index,n=e.attributes.position;let s=0;if(null!==i){const e=i.array;s=i.version;for(let t=0,i=e.length;tt.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);const f=new Float32Array(p*m*4*n),g=new DataArrayTexture(f,p,m,n);g.type=1015,g.needsUpdate=!0;const _=4*d;for(let t=0;t0)return e;const n=t*r;let a=arrayCacheF32[n];if(void 0===a&&(a=new Float32Array(n),arrayCacheF32[n]=a),0!==t){i.toArray(a,0);for(let i=1,n=0;i!==t;++i)n+=r,e[i].toArray(a,n);}return a}function arraysEqual(e,t){if(e.length!==t.length)return !1;for(let r=0,i=e.length;r":" "} ${n}: ${r[e]}`);}return i.join("\n")}function getEncodingComponents(e){switch(e){case 3e3:return ["Linear","( value )"];case 3001:return ["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",e),["Linear","( value )"]}}function getShaderErrors(e,t,r){const i=e.getShaderParameter(t,35713),n=e.getShaderInfoLog(t).trim();if(i&&""===n)return "";const a=/ERROR: 0:(\d+)/.exec(n);if(a){const i=parseInt(a[1]);return r.toUpperCase()+"\n\n"+n+"\n\n"+handleSource(e.getShaderSource(t),i)}return n}function getTexelEncodingFunction(e,t){const r=getEncodingComponents(t);return "vec4 "+e+"( vec4 value ) { return LinearTo"+r[0]+r[1]+"; }"}function getToneMappingFunction(e,t){let r;switch(t){case 1:r="Linear";break;case 2:r="Reinhard";break;case 3:r="OptimizedCineon";break;case 4:r="ACESFilmic";break;case 5:r="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),r="Linear";}return "vec3 "+e+"( vec3 color ) { return "+r+"ToneMapping( color ); }"}function generateExtensions(e){return [e.extensionDerivatives||e.envMapCubeUVHeight||e.bumpMap||e.tangentSpaceNormalMap||e.clearcoatNormalMap||e.flatShading||"physical"===e.shaderID?"#extension GL_OES_standard_derivatives : enable":"",(e.extensionFragDepth||e.logarithmicDepthBuffer)&&e.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",e.extensionDrawBuffers&&e.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(e.extensionShaderTextureLOD||e.envMap||e.transmission)&&e.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(filterEmptyLine).join("\n")}function generateDefines(e){const t=[];for(const r in e){const i=e[r];!1!==i&&t.push("#define "+r+" "+i);}return t.join("\n")}function fetchAttributeLocations(e,t){const r={},i=e.getProgramParameter(t,35721);for(let n=0;n/gm;function resolveIncludes(e){return e.replace(includePattern,includeReplacer)}function includeReplacer(e,t){const r=ShaderChunk[t];if(void 0===r)throw new Error("Can not resolve #include <"+t+">");return resolveIncludes(r)}const unrollLoopPattern=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function unrollLoops(e){return e.replace(unrollLoopPattern,loopReplacer)}function loopReplacer(e,t,r,i){let n="";for(let e=parseInt(t);e0&&(g+="\n"),_=[p,m].filter(filterEmptyLine).join("\n"),_.length>0&&(_+="\n")):(g=[generatePrecision(r),"#define SHADER_NAME "+r.shaderName,m,r.instancing?"#define USE_INSTANCING":"",r.instancingColor?"#define USE_INSTANCING_COLOR":"",r.supportsVertexTextures?"#define VERTEX_TEXTURES":"",r.useFog&&r.fog?"#define USE_FOG":"",r.useFog&&r.fogExp2?"#define FOG_EXP2":"",r.map?"#define USE_MAP":"",r.envMap?"#define USE_ENVMAP":"",r.envMap?"#define "+h:"",r.lightMap?"#define USE_LIGHTMAP":"",r.aoMap?"#define USE_AOMAP":"",r.emissiveMap?"#define USE_EMISSIVEMAP":"",r.bumpMap?"#define USE_BUMPMAP":"",r.normalMap?"#define USE_NORMALMAP":"",r.normalMap&&r.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",r.normalMap&&r.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",r.clearcoatMap?"#define USE_CLEARCOATMAP":"",r.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",r.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",r.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",r.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",r.displacementMap&&r.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",r.specularMap?"#define USE_SPECULARMAP":"",r.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",r.specularColorMap?"#define USE_SPECULARCOLORMAP":"",r.roughnessMap?"#define USE_ROUGHNESSMAP":"",r.metalnessMap?"#define USE_METALNESSMAP":"",r.alphaMap?"#define USE_ALPHAMAP":"",r.transmission?"#define USE_TRANSMISSION":"",r.transmissionMap?"#define USE_TRANSMISSIONMAP":"",r.thicknessMap?"#define USE_THICKNESSMAP":"",r.sheenColorMap?"#define USE_SHEENCOLORMAP":"",r.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",r.vertexTangents?"#define USE_TANGENT":"",r.vertexColors?"#define USE_COLOR":"",r.vertexAlphas?"#define USE_COLOR_ALPHA":"",r.vertexUvs?"#define USE_UV":"",r.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",r.flatShading?"#define FLAT_SHADED":"",r.skinning?"#define USE_SKINNING":"",r.morphTargets?"#define USE_MORPHTARGETS":"",r.morphNormals&&!1===r.flatShading?"#define USE_MORPHNORMALS":"",r.morphColors&&r.isWebGL2?"#define USE_MORPHCOLORS":"",r.morphTargetsCount>0&&r.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",r.morphTargetsCount>0&&r.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+r.morphTextureStride:"",r.morphTargetsCount>0&&r.isWebGL2?"#define MORPHTARGETS_COUNT "+r.morphTargetsCount:"",r.doubleSided?"#define DOUBLE_SIDED":"",r.flipSided?"#define FLIP_SIDED":"",r.shadowMapEnabled?"#define USE_SHADOWMAP":"",r.shadowMapEnabled?"#define "+l:"",r.sizeAttenuation?"#define USE_SIZEATTENUATION":"",r.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",r.logarithmicDepthBuffer&&r.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\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(filterEmptyLine).join("\n"),_=[p,generatePrecision(r),"#define SHADER_NAME "+r.shaderName,m,r.useFog&&r.fog?"#define USE_FOG":"",r.useFog&&r.fogExp2?"#define FOG_EXP2":"",r.map?"#define USE_MAP":"",r.matcap?"#define USE_MATCAP":"",r.envMap?"#define USE_ENVMAP":"",r.envMap?"#define "+c:"",r.envMap?"#define "+h:"",r.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",r.lightMap?"#define USE_LIGHTMAP":"",r.aoMap?"#define USE_AOMAP":"",r.emissiveMap?"#define USE_EMISSIVEMAP":"",r.bumpMap?"#define USE_BUMPMAP":"",r.normalMap?"#define USE_NORMALMAP":"",r.normalMap&&r.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",r.normalMap&&r.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",r.clearcoat?"#define USE_CLEARCOAT":"",r.clearcoatMap?"#define USE_CLEARCOATMAP":"",r.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",r.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",r.iridescence?"#define USE_IRIDESCENCE":"",r.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",r.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",r.specularMap?"#define USE_SPECULARMAP":"",r.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",r.specularColorMap?"#define USE_SPECULARCOLORMAP":"",r.roughnessMap?"#define USE_ROUGHNESSMAP":"",r.metalnessMap?"#define USE_METALNESSMAP":"",r.alphaMap?"#define USE_ALPHAMAP":"",r.alphaTest?"#define USE_ALPHATEST":"",r.sheen?"#define USE_SHEEN":"",r.sheenColorMap?"#define USE_SHEENCOLORMAP":"",r.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",r.transmission?"#define USE_TRANSMISSION":"",r.transmissionMap?"#define USE_TRANSMISSIONMAP":"",r.thicknessMap?"#define USE_THICKNESSMAP":"",r.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",r.vertexTangents?"#define USE_TANGENT":"",r.vertexColors||r.instancingColor?"#define USE_COLOR":"",r.vertexAlphas?"#define USE_COLOR_ALPHA":"",r.vertexUvs?"#define USE_UV":"",r.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",r.gradientMap?"#define USE_GRADIENTMAP":"",r.flatShading?"#define FLAT_SHADED":"",r.doubleSided?"#define DOUBLE_SIDED":"",r.flipSided?"#define FLIP_SIDED":"",r.shadowMapEnabled?"#define USE_SHADOWMAP":"",r.shadowMapEnabled?"#define "+l:"",r.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",r.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",r.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",r.logarithmicDepthBuffer&&r.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==r.toneMapping?"#define TONE_MAPPING":"",0!==r.toneMapping?ShaderChunk.tonemapping_pars_fragment:"",0!==r.toneMapping?getToneMappingFunction("toneMapping",r.toneMapping):"",r.dithering?"#define DITHERING":"",r.opaque?"#define OPAQUE":"",ShaderChunk.encodings_pars_fragment,getTexelEncodingFunction("linearToOutputTexel",r.outputEncoding),r.useDepthPacking?"#define DEPTH_PACKING "+r.depthPacking:"","\n"].filter(filterEmptyLine).join("\n")),s=resolveIncludes(s),s=replaceLightNums(s,r),s=replaceClippingPlaneNums(s,r),o=resolveIncludes(o),o=replaceLightNums(o,r),o=replaceClippingPlaneNums(o,r),s=unrollLoops(s),o=unrollLoops(o),r.isWebGL2&&!0!==r.isRawShaderMaterial&&(v="#version 300 es\n",g=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,_=["#define varying in",r.glslVersion===GLSL3?"":"layout(location = 0) out highp vec4 pc_fragColor;",r.glslVersion===GLSL3?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+_);const x=v+_+o,y=WebGLShader(n,35633,v+g+s),b=WebGLShader(n,35632,x);if(n.attachShader(f,y),n.attachShader(f,b),void 0!==r.index0AttributeName?n.bindAttribLocation(f,0,r.index0AttributeName):!0===r.morphTargets&&n.bindAttribLocation(f,0,"position"),n.linkProgram(f),e.debug.checkShaderErrors){const e=n.getProgramInfoLog(f).trim(),t=n.getShaderInfoLog(y).trim(),r=n.getShaderInfoLog(b).trim();let i=!0,a=!0;if(!1===n.getProgramParameter(f,35714)){i=!1;const t=getShaderErrors(n,y,"vertex"),r=getShaderErrors(n,b,"fragment");console.error("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(f,35715)+"\n\nProgram Info Log: "+e+"\n"+t+"\n"+r);}else ""!==e?console.warn("THREE.WebGLProgram: Program Info Log:",e):""!==t&&""!==r||(a=!1);a&&(this.diagnostics={runnable:i,programLog:e,vertexShader:{log:t,prefix:g},fragmentShader:{log:r,prefix:_}});}let M,S;return n.deleteShader(y),n.deleteShader(b),this.getUniforms=function(){return void 0===M&&(M=new WebGLUniforms(n,f)),M},this.getAttributes=function(){return void 0===S&&(S=fetchAttributeLocations(n,f)),S},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(f),this.program=void 0;},this.name=r.shaderName,this.id=programIdCount++,this.cacheKey=t,this.usedTimes=1,this.program=f,this.vertexShader=y,this.fragmentShader=b,this}let _id=0;class WebGLShaderCache{constructor(){this.shaderCache=new Map,this.materialCache=new Map;}update(e){const t=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(t),n=this._getShaderStage(r),a=this._getShaderCacheForMaterial(e);return !1===a.has(i)&&(a.add(i),i.usedTimes++),!1===a.has(n)&&(a.add(n),n.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const e of t)e.usedTimes--,0===e.usedTimes&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear();}_getShaderCacheForMaterial(e){const t=this.materialCache;let r=t.get(e);return void 0===r&&(r=new Set,t.set(e,r)),r}_getShaderStage(e){const t=this.shaderCache;let r=t.get(e);return void 0===r&&(r=new WebGLShaderStage(e),t.set(e,r)),r}}class WebGLShaderStage{constructor(e){this.id=_id++,this.code=e,this.usedTimes=0;}}function WebGLPrograms(e,t,r,i,n,a,s){const o=new Layers,l=new WebGLShaderCache,c=[],h=n.isWebGL2,u=n.logarithmicDepthBuffer,d=n.vertexTextures;let p=n.precision;const m={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};return {getParameters:function(a,o,c,f,g){const _=f.fog,v=g.geometry,x=a.isMeshStandardMaterial?f.environment:null,y=(a.isMeshStandardMaterial?r:t).get(a.envMap||x),b=y&&306===y.mapping?y.image.height:null,M=m[a.type];null!==a.precision&&(p=n.getMaxPrecision(a.precision),p!==a.precision&&console.warn("THREE.WebGLProgram.getParameters:",a.precision,"not supported, using",p,"instead."));const S=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,w=void 0!==S?S.length:0;let T,A,C,E,L=0;if(void 0!==v.morphAttributes.position&&(L=1),void 0!==v.morphAttributes.normal&&(L=2),void 0!==v.morphAttributes.color&&(L=3),M){const e=ShaderLib[M];T=e.vertexShader,A=e.fragmentShader;}else T=a.vertexShader,A=a.fragmentShader,l.update(a),C=l.getVertexShaderID(a),E=l.getFragmentShaderID(a);const P=e.getRenderTarget(),R=a.alphaTest>0,D=a.clearcoat>0,I=a.iridescence>0;return {isWebGL2:h,shaderID:M,shaderName:a.type,vertexShader:T,fragmentShader:A,defines:a.defines,customVertexShaderID:C,customFragmentShaderID:E,isRawShaderMaterial:!0===a.isRawShaderMaterial,glslVersion:a.glslVersion,precision:p,instancing:!0===g.isInstancedMesh,instancingColor:!0===g.isInstancedMesh&&null!==g.instanceColor,supportsVertexTextures:d,outputEncoding:null===P?e.outputEncoding:!0===P.isXRRenderTarget?P.texture.encoding:3e3,map:!!a.map,matcap:!!a.matcap,envMap:!!y,envMapMode:y&&y.mapping,envMapCubeUVHeight:b,lightMap:!!a.lightMap,aoMap:!!a.aoMap,emissiveMap:!!a.emissiveMap,bumpMap:!!a.bumpMap,normalMap:!!a.normalMap,objectSpaceNormalMap:1===a.normalMapType,tangentSpaceNormalMap:0===a.normalMapType,decodeVideoTexture:!!a.map&&!0===a.map.isVideoTexture&&3001===a.map.encoding,clearcoat:D,clearcoatMap:D&&!!a.clearcoatMap,clearcoatRoughnessMap:D&&!!a.clearcoatRoughnessMap,clearcoatNormalMap:D&&!!a.clearcoatNormalMap,iridescence:I,iridescenceMap:I&&!!a.iridescenceMap,iridescenceThicknessMap:I&&!!a.iridescenceThicknessMap,displacementMap:!!a.displacementMap,roughnessMap:!!a.roughnessMap,metalnessMap:!!a.metalnessMap,specularMap:!!a.specularMap,specularIntensityMap:!!a.specularIntensityMap,specularColorMap:!!a.specularColorMap,opaque:!1===a.transparent&&1===a.blending,alphaMap:!!a.alphaMap,alphaTest:R,gradientMap:!!a.gradientMap,sheen:a.sheen>0,sheenColorMap:!!a.sheenColorMap,sheenRoughnessMap:!!a.sheenRoughnessMap,transmission:a.transmission>0,transmissionMap:!!a.transmissionMap,thicknessMap:!!a.thicknessMap,combine:a.combine,vertexTangents:!!a.normalMap&&!!v.attributes.tangent,vertexColors:a.vertexColors,vertexAlphas:!0===a.vertexColors&&!!v.attributes.color&&4===v.attributes.color.itemSize,vertexUvs:!!(a.map||a.bumpMap||a.normalMap||a.specularMap||a.alphaMap||a.emissiveMap||a.roughnessMap||a.metalnessMap||a.clearcoatMap||a.clearcoatRoughnessMap||a.clearcoatNormalMap||a.iridescenceMap||a.iridescenceThicknessMap||a.displacementMap||a.transmissionMap||a.thicknessMap||a.specularIntensityMap||a.specularColorMap||a.sheenColorMap||a.sheenRoughnessMap),uvsVertexOnly:!(a.map||a.bumpMap||a.normalMap||a.specularMap||a.alphaMap||a.emissiveMap||a.roughnessMap||a.metalnessMap||a.clearcoatNormalMap||a.iridescenceMap||a.iridescenceThicknessMap||a.transmission>0||a.transmissionMap||a.thicknessMap||a.specularIntensityMap||a.specularColorMap||a.sheen>0||a.sheenColorMap||a.sheenRoughnessMap||!a.displacementMap),fog:!!_,useFog:!0===a.fog,fogExp2:_&&_.isFogExp2,flatShading:!!a.flatShading,sizeAttenuation:a.sizeAttenuation,logarithmicDepthBuffer:u,skinning:!0===g.isSkinnedMesh,morphTargets:void 0!==v.morphAttributes.position,morphNormals:void 0!==v.morphAttributes.normal,morphColors:void 0!==v.morphAttributes.color,morphTargetsCount:w,morphTextureStride:L,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:a.dithering,shadowMapEnabled:e.shadowMap.enabled&&c.length>0,shadowMapType:e.shadowMap.type,toneMapping:a.toneMapped?e.toneMapping:0,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:a.premultipliedAlpha,doubleSided:2===a.side,flipSided:1===a.side,useDepthPacking:!!a.depthPacking,depthPacking:a.depthPacking||0,index0AttributeName:a.index0AttributeName,extensionDerivatives:a.extensions&&a.extensions.derivatives,extensionFragDepth:a.extensions&&a.extensions.fragDepth,extensionDrawBuffers:a.extensions&&a.extensions.drawBuffers,extensionShaderTextureLOD:a.extensions&&a.extensions.shaderTextureLOD,rendererExtensionFragDepth:h||i.has("EXT_frag_depth"),rendererExtensionDrawBuffers:h||i.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:h||i.has("EXT_shader_texture_lod"),customProgramCacheKey:a.customProgramCacheKey()}},getProgramCacheKey:function(t){const r=[];if(t.shaderID?r.push(t.shaderID):(r.push(t.customVertexShaderID),r.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)r.push(e),r.push(t.defines[e]);return !1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputEncoding),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.combine),e.push(t.vertexUvs),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking);}(r,t),function(e,t){o.disableAll(),t.isWebGL2&&o.enable(0);t.supportsVertexTextures&&o.enable(1);t.instancing&&o.enable(2);t.instancingColor&&o.enable(3);t.map&&o.enable(4);t.matcap&&o.enable(5);t.envMap&&o.enable(6);t.lightMap&&o.enable(7);t.aoMap&&o.enable(8);t.emissiveMap&&o.enable(9);t.bumpMap&&o.enable(10);t.normalMap&&o.enable(11);t.objectSpaceNormalMap&&o.enable(12);t.tangentSpaceNormalMap&&o.enable(13);t.clearcoat&&o.enable(14);t.clearcoatMap&&o.enable(15);t.clearcoatRoughnessMap&&o.enable(16);t.clearcoatNormalMap&&o.enable(17);t.iridescence&&o.enable(18);t.iridescenceMap&&o.enable(19);t.iridescenceThicknessMap&&o.enable(20);t.displacementMap&&o.enable(21);t.specularMap&&o.enable(22);t.roughnessMap&&o.enable(23);t.metalnessMap&&o.enable(24);t.gradientMap&&o.enable(25);t.alphaMap&&o.enable(26);t.alphaTest&&o.enable(27);t.vertexColors&&o.enable(28);t.vertexAlphas&&o.enable(29);t.vertexUvs&&o.enable(30);t.vertexTangents&&o.enable(31);t.uvsVertexOnly&&o.enable(32);e.push(o.mask),o.disableAll(),t.fog&&o.enable(0);t.useFog&&o.enable(1);t.flatShading&&o.enable(2);t.logarithmicDepthBuffer&&o.enable(3);t.skinning&&o.enable(4);t.morphTargets&&o.enable(5);t.morphNormals&&o.enable(6);t.morphColors&&o.enable(7);t.premultipliedAlpha&&o.enable(8);t.shadowMapEnabled&&o.enable(9);t.physicallyCorrectLights&&o.enable(10);t.doubleSided&&o.enable(11);t.flipSided&&o.enable(12);t.useDepthPacking&&o.enable(13);t.dithering&&o.enable(14);t.specularIntensityMap&&o.enable(15);t.specularColorMap&&o.enable(16);t.transmission&&o.enable(17);t.transmissionMap&&o.enable(18);t.thicknessMap&&o.enable(19);t.sheen&&o.enable(20);t.sheenColorMap&&o.enable(21);t.sheenRoughnessMap&&o.enable(22);t.decodeVideoTexture&&o.enable(23);t.opaque&&o.enable(24);e.push(o.mask);}(r,t),r.push(e.outputEncoding)),r.push(t.customProgramCacheKey),r.join()},getUniforms:function(e){const t=m[e.type];let r;if(t){const e=ShaderLib[t];r=UniformsUtils.clone(e.uniforms);}else r=e.uniforms;return r},acquireProgram:function(t,r){let i;for(let e=0,t=c.length;e0?i.push(h):!0===s.transparent?n.push(h):r.push(h);},unshift:function(e,t,s,o,l,c){const h=a(e,t,s,o,l,c);s.transmission>0?i.unshift(h):!0===s.transparent?n.unshift(h):r.unshift(h);},finish:function(){for(let r=t,i=e.length;r1&&r.sort(e||painterSortStable),i.length>1&&i.sort(t||reversePainterSortStable),n.length>1&&n.sort(t||reversePainterSortStable);}}}function WebGLRenderLists(){let e=new WeakMap;return {get:function(t,r){const i=e.get(t);let n;return void 0===i?(n=new WebGLRenderList,e.set(t,[n])):r>=i.length?(n=new WebGLRenderList,i.push(n)):n=i[r],n},dispose:function(){e=new WeakMap;}}}function UniformsCache(){const e={};return {get:function(t){if(void 0!==e[t.id])return e[t.id];let r;switch(t.type){case"DirectionalLight":r={direction:new Vector3,color:new Color};break;case"SpotLight":r={position:new Vector3,direction:new Vector3,color:new Color,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":r={position:new Vector3,color:new Color,distance:0,decay:0};break;case"HemisphereLight":r={direction:new Vector3,skyColor:new Color,groundColor:new Color};break;case"RectAreaLight":r={color:new Color,position:new Vector3,halfWidth:new Vector3,halfHeight:new Vector3};}return e[t.id]=r,r}}}function ShadowUniformsCache(){const e={};return {get:function(t){if(void 0!==e[t.id])return e[t.id];let r;switch(t.type){case"DirectionalLight":case"SpotLight":r={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"PointLight":r={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2,shadowCameraNear:1,shadowCameraFar:1e3};}return e[t.id]=r,r}}}let nextVersion=0;function shadowCastingAndTexturingLightsFirst(e,t){return (t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function WebGLLights(e,t){const r=new UniformsCache,i=ShadowUniformsCache(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0};for(let e=0;e<9;e++)n.probe.push(new Vector3);const a=new Vector3,s=new Matrix4,o=new Matrix4;return {setup:function(a,s){let o=0,l=0,c=0;for(let e=0;e<9;e++)n.probe[e].set(0,0,0);let h=0,u=0,d=0,p=0,m=0,f=0,g=0,_=0,v=0,x=0;a.sort(shadowCastingAndTexturingLightsFirst);const y=!0!==s?Math.PI:1;for(let e=0,t=a.length;e0&&(t.isWebGL2||!0===e.has("OES_texture_float_linear")?(n.rectAreaLTC1=UniformsLib.LTC_FLOAT_1,n.rectAreaLTC2=UniformsLib.LTC_FLOAT_2):!0===e.has("OES_texture_half_float_linear")?(n.rectAreaLTC1=UniformsLib.LTC_HALF_1,n.rectAreaLTC2=UniformsLib.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),n.ambient[0]=o,n.ambient[1]=l,n.ambient[2]=c;const b=n.hash;b.directionalLength===h&&b.pointLength===u&&b.spotLength===d&&b.rectAreaLength===p&&b.hemiLength===m&&b.numDirectionalShadows===f&&b.numPointShadows===g&&b.numSpotShadows===_&&b.numSpotMaps===v||(n.directional.length=h,n.spot.length=d,n.rectArea.length=p,n.point.length=u,n.hemi.length=m,n.directionalShadow.length=f,n.directionalShadowMap.length=f,n.pointShadow.length=g,n.pointShadowMap.length=g,n.spotShadow.length=_,n.spotShadowMap.length=_,n.directionalShadowMatrix.length=f,n.pointShadowMatrix.length=g,n.spotLightMatrix.length=_+v-x,n.spotLightMap.length=v,n.numSpotLightShadowsWithMaps=x,b.directionalLength=h,b.pointLength=u,b.spotLength=d,b.rectAreaLength=p,b.hemiLength=m,b.numDirectionalShadows=f,b.numPointShadows=g,b.numSpotShadows=_,b.numSpotMaps=v,n.version=nextVersion++);},setupView:function(e,t){let r=0,i=0,l=0,c=0,h=0;const u=t.matrixWorldInverse;for(let t=0,d=e.length;t=a.length?(s=new WebGLRenderState(e,t),a.push(s)):s=a[n],s},dispose:function(){r=new WeakMap;}}}class MeshDepthMaterial extends Material{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e);}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class MeshDistanceMaterial extends Material{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.referencePosition=new Vector3,this.nearDistance=1,this.farDistance=1e3,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e);}copy(e){return super.copy(e),this.referencePosition.copy(e.referencePosition),this.nearDistance=e.nearDistance,this.farDistance=e.farDistance,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const vertex="void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragment="uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";function WebGLShadowMap(e,t,r){let i=new Frustum;const n=new Vector2,a=new Vector2,s=new Vector4,o=new MeshDepthMaterial({depthPacking:3201}),l=new MeshDistanceMaterial,c={},h=r.maxTextureSize,u={0:1,1:0,2:2},d=new ShaderMaterial({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2},radius:{value:4}},vertexShader:vertex,fragmentShader:fragment}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const m=new BufferGeometry;m.setAttribute("position",new BufferAttribute(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const f=new Mesh(m,d),g=this;function _(r,i){const a=t.update(f);d.defines.VSM_SAMPLES!==r.blurSamples&&(d.defines.VSM_SAMPLES=r.blurSamples,p.defines.VSM_SAMPLES=r.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===r.mapPass&&(r.mapPass=new WebGLRenderTarget(n.x,n.y)),d.uniforms.shadow_pass.value=r.map.texture,d.uniforms.resolution.value=r.mapSize,d.uniforms.radius.value=r.radius,e.setRenderTarget(r.mapPass),e.clear(),e.renderBufferDirect(i,null,a,d,f,null),p.uniforms.shadow_pass.value=r.mapPass.texture,p.uniforms.resolution.value=r.mapSize,p.uniforms.radius.value=r.radius,e.setRenderTarget(r.map),e.clear(),e.renderBufferDirect(i,null,a,p,f,null);}function v(t,r,i,n,a,s){let h=null;const d=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(h=void 0!==d?d:!0===i.isPointLight?l:o,e.localClippingEnabled&&!0===r.clipShadows&&Array.isArray(r.clippingPlanes)&&0!==r.clippingPlanes.length||r.displacementMap&&0!==r.displacementScale||r.alphaMap&&r.alphaTest>0){const e=h.uuid,t=r.uuid;let i=c[e];void 0===i&&(i={},c[e]=i);let n=i[t];void 0===n&&(n=h.clone(),i[t]=n),h=n;}return h.visible=r.visible,h.wireframe=r.wireframe,h.side=3===s?null!==r.shadowSide?r.shadowSide:r.side:null!==r.shadowSide?r.shadowSide:u[r.side],h.alphaMap=r.alphaMap,h.alphaTest=r.alphaTest,h.clipShadows=r.clipShadows,h.clippingPlanes=r.clippingPlanes,h.clipIntersection=r.clipIntersection,h.displacementMap=r.displacementMap,h.displacementScale=r.displacementScale,h.displacementBias=r.displacementBias,h.wireframeLinewidth=r.wireframeLinewidth,h.linewidth=r.linewidth,!0===i.isPointLight&&!0===h.isMeshDistanceMaterial&&(h.referencePosition.setFromMatrixPosition(i.matrixWorld),h.nearDistance=n,h.farDistance=a),h}function x(r,n,a,s,o){if(!1===r.visible)return;if(r.layers.test(n.layers)&&(r.isMesh||r.isLine||r.isPoints)&&(r.castShadow||r.receiveShadow&&3===o)&&(!r.frustumCulled||i.intersectsObject(r))){r.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,r.matrixWorld);const i=t.update(r),n=r.material;if(Array.isArray(n)){const t=i.groups;for(let l=0,c=t.length;lh||n.y>h)&&(n.x>h&&(a.x=Math.floor(h/p.x),n.x=a.x*p.x,u.mapSize.x=a.x),n.y>h&&(a.y=Math.floor(h/p.y),n.y=a.y*p.y,u.mapSize.y=a.y)),null===u.map){const e=3!==this.type?{minFilter:1003,magFilter:1003}:{};u.map=new WebGLRenderTarget(n.x,n.y,e),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix();}e.setRenderTarget(u.map),e.clear();const m=u.getViewportCount();for(let e=0;e=1):-1!==R.indexOf("OpenGL ES")&&(P=parseFloat(/^OpenGL ES (\d)/.exec(R)[1]),L=P>=2);let D=null,I={};const B=e.getParameter(3088),V=e.getParameter(2978),N=(new Vector4).fromArray(B),O=(new Vector4).fromArray(V);function U(t,r,i){const n=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,10241,9728),e.texParameteri(t,10240,9728);for(let t=0;ti||e.height>i)&&(n=i/Math.max(e.width,e.height)),n<1||!0===t){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const i=t?floorPowerOfTwo:Math.floor,a=i(n*e.width),s=i(n*e.height);void 0===f&&(f=v(a,s));const o=r?v(a,s):f;o.width=a,o.height=s;return o.getContext("2d").drawImage(e,0,0,a,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+e.width+"x"+e.height+") to ("+a+"x"+s+")."),o}return "data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+e.width+"x"+e.height+")."),e}return e}function y(e){return isPowerOfTwo(e.width)&&isPowerOfTwo(e.height)}function b(e,t){return e.generateMipmaps&&t&&1003!==e.minFilter&&1006!==e.minFilter}function M(t){e.generateMipmap(t);}function S(r,i,n,a,s=!1){if(!1===o)return i;if(null!==r){if(void 0!==e[r])return e[r];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+r+"'");}let l=i;return 6403===i&&(5126===n&&(l=33326),5131===n&&(l=33325),5121===n&&(l=33321)),33319===i&&(5126===n&&(l=33328),5131===n&&(l=33327),5121===n&&(l=33323)),6408===i&&(5126===n&&(l=34836),5131===n&&(l=34842),5121===n&&(l=3001===a&&!1===s?35907:32856),32819===n&&(l=32854),32820===n&&(l=32855)),33325!==l&&33326!==l&&33327!==l&&33328!==l&&34842!==l&&34836!==l||t.get("EXT_color_buffer_float"),l}function w(e,t,r){return !0===b(e,r)||e.isFramebufferTexture&&1003!==e.minFilter&&1006!==e.minFilter?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function T(e){return 1003===e||1004===e||1005===e?9728:9729}function A(e){const t=e.target;t.removeEventListener("dispose",A),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const r=e.source,n=g.get(r);if(n){const i=n[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&E(e),0===Object.keys(n).length&&g.delete(r);}i.remove(e);}(t),t.isVideoTexture&&m.delete(t);}function C(t){const r=t.target;r.removeEventListener("dispose",C),function(t){const r=t.texture,n=i.get(t),a=i.get(r);void 0!==a.__webglTexture&&(e.deleteTexture(a.__webglTexture),s.memory.textures--);t.depthTexture&&t.depthTexture.dispose();if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]),n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t]);else {if(e.deleteFramebuffer(n.__webglFramebuffer),n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t0&&n.__version!==e.version){const r=e.image;if(null===r)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else {if(!1!==r.complete)return void V(n,e,t);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");}}r.activeTexture(33984+t),r.bindTexture(3553,n.__webglTexture);}const R={1e3:10497,1001:33071,1002:33648},D={1003:9728,1004:9984,1005:9986,1006:9729,1007:9985,1008:9987};function I(r,a,s){if(s?(e.texParameteri(r,10242,R[a.wrapS]),e.texParameteri(r,10243,R[a.wrapT]),32879!==r&&35866!==r||e.texParameteri(r,32882,R[a.wrapR]),e.texParameteri(r,10240,D[a.magFilter]),e.texParameteri(r,10241,D[a.minFilter])):(e.texParameteri(r,10242,33071),e.texParameteri(r,10243,33071),32879!==r&&35866!==r||e.texParameteri(r,32882,33071),1001===a.wrapS&&1001===a.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),e.texParameteri(r,10240,T(a.magFilter)),e.texParameteri(r,10241,T(a.minFilter)),1003!==a.minFilter&&1006!==a.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");if(1015===a.type&&!1===t.has("OES_texture_float_linear"))return;if(!1===o&&1016===a.type&&!1===t.has("OES_texture_half_float_linear"))return;(a.anisotropy>1||i.get(a).__currentAnisotropy)&&(e.texParameterf(r,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,n.getMaxAnisotropy())),i.get(a).__currentAnisotropy=a.anisotropy);}}function B(t,r){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,r.addEventListener("dispose",A));const n=r.source;let a=g.get(n);void 0===a&&(a={},g.set(n,a));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.encoding),t.join()}(r);if(o!==t.__cacheKey){void 0===a[o]&&(a[o]={texture:e.createTexture(),usedTimes:0},s.memory.textures++,i=!0),a[o].usedTimes++;const n=a[t.__cacheKey];void 0!==n&&(a[t.__cacheKey].usedTimes--,0===n.usedTimes&&E(r)),t.__cacheKey=o,t.__webglTexture=a[o].texture;}return i}function V(t,i,n){let s=3553;i.isDataArrayTexture&&(s=35866),i.isData3DTexture&&(s=32879);const l=B(t,i),c=i.source;if(r.activeTexture(33984+n),r.bindTexture(s,t.__webglTexture),c.version!==c.__currentVersion||!0===l){e.pixelStorei(37440,i.flipY),e.pixelStorei(37441,i.premultiplyAlpha),e.pixelStorei(3317,i.unpackAlignment),e.pixelStorei(37443,0);const t=function(e){return !o&&(1001!==e.wrapS||1001!==e.wrapT||1003!==e.minFilter&&1006!==e.minFilter)}(i)&&!1===y(i.image);let n=x(i.image,t,!1,h);n=F(i,n);const u=y(n)||o,d=a.convert(i.format,i.encoding);let p,m=a.convert(i.type),f=S(i.internalFormat,d,m,i.encoding,i.isVideoTexture);I(s,i,u);const g=i.mipmaps,_=o&&!0!==i.isVideoTexture,v=void 0===c.__currentVersion||!0===l,T=w(i,n,u);if(i.isDepthTexture)f=6402,o?f=1015===i.type?36012:1014===i.type?33190:1020===i.type?35056:33189:1015===i.type&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),1026===i.format&&6402===f&&1012!==i.type&&1014!==i.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),i.type=1014,m=a.convert(i.type)),1027===i.format&&6402===f&&(f=34041,1020!==i.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),i.type=1020,m=a.convert(i.type))),v&&(_?r.texStorage2D(3553,1,f,n.width,n.height):r.texImage2D(3553,0,f,n.width,n.height,0,d,m,null));else if(i.isDataTexture)if(g.length>0&&u){_&&v&&r.texStorage2D(3553,T,f,g[0].width,g[0].height);for(let e=0,t=g.length;e>=1,t>>=1;}}else if(g.length>0&&u){_&&v&&r.texStorage2D(3553,T,f,g[0].width,g[0].height);for(let e=0,t=g.length;e0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==r.__useRenderToTexture}function F(e,r){const i=e.encoding,n=e.format,a=e.type;return !0===e.isCompressedTexture||!0===e.isVideoTexture||1035===e.format||3e3!==i&&(3001===i?!1===o?!0===t.has("EXT_sRGB")&&1023===n?(e.format=1035,e.minFilter=1006,e.generateMipmaps=!1):r=ImageUtils.sRGBToLinear(r):1023===n&&1009===a||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture encoding:",i)),r}this.allocateTextureUnit=function(){const e=L;return e>=l&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+l),L+=1,e},this.resetTextureUnits=function(){L=0;},this.setTexture2D=P,this.setTexture2DArray=function(e,t){const n=i.get(e);e.version>0&&n.__version!==e.version?V(n,e,t):(r.activeTexture(33984+t),r.bindTexture(35866,n.__webglTexture));},this.setTexture3D=function(e,t){const n=i.get(e);e.version>0&&n.__version!==e.version?V(n,e,t):(r.activeTexture(33984+t),r.bindTexture(32879,n.__webglTexture));},this.setTextureCube=function(t,n){const s=i.get(t);t.version>0&&s.__version!==t.version?function(t,i,n){if(6!==i.image.length)return;const s=B(t,i),l=i.source;if(r.activeTexture(33984+n),r.bindTexture(34067,t.__webglTexture),l.version!==l.__currentVersion||!0===s){e.pixelStorei(37440,i.flipY),e.pixelStorei(37441,i.premultiplyAlpha),e.pixelStorei(3317,i.unpackAlignment),e.pixelStorei(37443,0);const t=i.isCompressedTexture||i.image[0].isCompressedTexture,n=i.image[0]&&i.image[0].isDataTexture,h=[];for(let e=0;e<6;e++)h[e]=t||n?n?i.image[e].image:i.image[e]:x(i.image[e],!1,!0,c),h[e]=F(i,h[e]);const u=h[0],d=y(u)||o,p=a.convert(i.format,i.encoding),m=a.convert(i.type),f=S(i.internalFormat,p,m,i.encoding),g=o&&!0!==i.isVideoTexture,_=void 0===l.__currentVersion||!0===s;let v,T=w(i,u,d);if(I(34067,i,d),t){g&&_&&r.texStorage2D(34067,T,f,u.width,u.height);for(let e=0;e<6;e++){v=h[e].mipmaps;for(let t=0;t0&&T++,r.texStorage2D(34067,T,f,h[0].width,h[0].height));for(let e=0;e<6;e++)if(n){g?r.texSubImage2D(34069+e,0,0,0,h[e].width,h[e].height,p,m,h[e].data):r.texImage2D(34069+e,0,f,h[e].width,h[e].height,0,p,m,h[e].data);for(let t=0;t0&&!1===G(t)){const i=d?l:[l];c.__webglMultisampledFramebuffer=e.createFramebuffer(),c.__webglColorRenderbuffer=[],r.bindFramebuffer(36160,c.__webglMultisampledFramebuffer);for(let r=0;r0&&!1===G(t)){const n=t.isWebGLMultipleRenderTargets?t.texture:[t.texture],a=t.width,s=t.height;let o=16384;const l=[],c=t.stencilBuffer?33306:36096,h=i.get(t),u=!0===t.isWebGLMultipleRenderTargets;if(u)for(let t=0;to+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&s<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}));}else null!==o&&e.gripSpace&&(n=t.getPose(e.gripSpace,r),null!==n&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1));null!==s&&(i=t.getPose(e.targetRaySpace,r),null===i&&null!==n&&(i=n),null!==i&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,this.dispatchEvent(_moveEvent)));}return null!==s&&(s.visible=null!==i),null!==o&&(o.visible=null!==n),null!==l&&(l.visible=null!==a),this}}class DepthTexture extends Texture{constructor(e,t,r,i,n,a,s,o,l,c){if(1026!==(c=void 0!==c?c:1026)&&1027!==c)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===r&&1026===c&&(r=1014),void 0===r&&1027===c&&(r=1020),super(null,i,n,a,s,o,c,r,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==s?s:1003,this.minFilter=void 0!==o?o:1003,this.flipY=!1,this.generateMipmaps=!1;}}class WebXRManager extends EventDispatcher{constructor(e,t){super();const r=this;let i=null,n=1,a=null,s="local-floor",o=null,l=null,c=null,h=null,u=null,d=null;const p=t.getContextAttributes();let m=null,f=null;const g=[],_=[],v=new PerspectiveCamera;v.layers.enable(1),v.viewport=new Vector4;const x=new PerspectiveCamera;x.layers.enable(2),x.viewport=new Vector4;const y=[v,x],b=new ArrayCamera;b.layers.enable(1),b.layers.enable(2);let M=null,S=null;function w(e){const t=_.indexOf(e.inputSource);if(-1===t)return;const r=g[t];void 0!==r&&r.dispatchEvent({type:e.type,data:e.inputSource});}function T(){i.removeEventListener("select",w),i.removeEventListener("selectstart",w),i.removeEventListener("selectend",w),i.removeEventListener("squeeze",w),i.removeEventListener("squeezestart",w),i.removeEventListener("squeezeend",w),i.removeEventListener("end",T),i.removeEventListener("inputsourceschange",A);for(let e=0;e=0&&(_[i]=null,g[i].dispatchEvent({type:"disconnected",data:r}));}for(let t=0;t=_.length){_.push(r),i=e;break}if(null===_[e]){_[e]=r,i=e;break}}if(-1===i)break}const n=g[i];n&&n.dispatchEvent({type:"connected",data:r});}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=g[e];return void 0===t&&(t=new WebXRController,g[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=g[e];return void 0===t&&(t=new WebXRController,g[e]=t),t.getGripSpace()},this.getHand=function(e){let t=g[e];return void 0===t&&(t=new WebXRController,g[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){n=e,!0===r.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.");},this.setReferenceSpaceType=function(e){s=e,!0===r.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.");},this.getReferenceSpace=function(){return o||a},this.setReferenceSpace=function(e){o=e;},this.getBaseLayer=function(){return null!==h?h:u},this.getBinding=function(){return c},this.getFrame=function(){return d},this.getSession=function(){return i},this.setSession=async function(l){if(i=l,null!==i){if(m=e.getRenderTarget(),i.addEventListener("select",w),i.addEventListener("selectstart",w),i.addEventListener("selectend",w),i.addEventListener("squeeze",w),i.addEventListener("squeezestart",w),i.addEventListener("squeezeend",w),i.addEventListener("end",T),i.addEventListener("inputsourceschange",A),!0!==p.xrCompatible&&await t.makeXRCompatible(),void 0===i.renderState.layers||!1===e.capabilities.isWebGL2){const r={antialias:void 0!==i.renderState.layers||p.antialias,alpha:p.alpha,depth:p.depth,stencil:p.stencil,framebufferScaleFactor:n};u=new XRWebGLLayer(i,t,r),i.updateRenderState({baseLayer:u}),f=new WebGLRenderTarget(u.framebufferWidth,u.framebufferHeight,{format:1023,type:1009,encoding:e.outputEncoding,stencilBuffer:p.stencil});}else {let r=null,a=null,s=null;p.depth&&(s=p.stencil?35056:33190,r=p.stencil?1027:1026,a=p.stencil?1020:1014);const o={colorFormat:32856,depthFormat:s,scaleFactor:n};c=new XRWebGLBinding(i,t),h=c.createProjectionLayer(o),i.updateRenderState({layers:[h]}),f=new WebGLRenderTarget(h.textureWidth,h.textureHeight,{format:1023,type:1009,depthTexture:new DepthTexture(h.textureWidth,h.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,r),stencilBuffer:p.stencil,encoding:e.outputEncoding,samples:p.antialias?4:0});e.properties.get(f).__ignoreDepthValues=h.ignoreDepthValues;}f.isXRRenderTarget=!0,this.setFoveation(1),o=null,a=await i.requestReferenceSpace(s),R.setContext(i),R.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"});}};const C=new Vector3,E=new Vector3;function L(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert();}this.updateCamera=function(e){if(null===i)return;b.near=x.near=v.near=e.near,b.far=x.far=v.far=e.far,M===b.near&&S===b.far||(i.updateRenderState({depthNear:b.near,depthFar:b.far}),M=b.near,S=b.far);const t=e.parent,r=b.cameras;L(b,t);for(let e=0;e0&&(r.alphaTest.value=i.alphaTest);const n=t.get(i).envMap;if(n&&(r.envMap.value=n,r.flipEnvMap.value=n.isCubeTexture&&!1===n.isRenderTargetTexture?-1:1,r.reflectivity.value=i.reflectivity,r.ior.value=i.ior,r.refractionRatio.value=i.refractionRatio),i.lightMap){r.lightMap.value=i.lightMap;const t=!0!==e.physicallyCorrectLights?Math.PI:1;r.lightMapIntensity.value=i.lightMapIntensity*t;}let a,s;i.aoMap&&(r.aoMap.value=i.aoMap,r.aoMapIntensity.value=i.aoMapIntensity),i.map?a=i.map:i.specularMap?a=i.specularMap:i.displacementMap?a=i.displacementMap:i.normalMap?a=i.normalMap:i.bumpMap?a=i.bumpMap:i.roughnessMap?a=i.roughnessMap:i.metalnessMap?a=i.metalnessMap:i.alphaMap?a=i.alphaMap:i.emissiveMap?a=i.emissiveMap:i.clearcoatMap?a=i.clearcoatMap:i.clearcoatNormalMap?a=i.clearcoatNormalMap:i.clearcoatRoughnessMap?a=i.clearcoatRoughnessMap:i.iridescenceMap?a=i.iridescenceMap:i.iridescenceThicknessMap?a=i.iridescenceThicknessMap:i.specularIntensityMap?a=i.specularIntensityMap:i.specularColorMap?a=i.specularColorMap:i.transmissionMap?a=i.transmissionMap:i.thicknessMap?a=i.thicknessMap:i.sheenColorMap?a=i.sheenColorMap:i.sheenRoughnessMap&&(a=i.sheenRoughnessMap),void 0!==a&&(a.isWebGLRenderTarget&&(a=a.texture),!0===a.matrixAutoUpdate&&a.updateMatrix(),r.uvTransform.value.copy(a.matrix)),i.aoMap?s=i.aoMap:i.lightMap&&(s=i.lightMap),void 0!==s&&(s.isWebGLRenderTarget&&(s=s.texture),!0===s.matrixAutoUpdate&&s.updateMatrix(),r.uv2Transform.value.copy(s.matrix));}return {refreshFogUniforms:function(e,t){e.fogColor.value.copy(t.color),t.isFog?(e.fogNear.value=t.near,e.fogFar.value=t.far):t.isFogExp2&&(e.fogDensity.value=t.density);},refreshMaterialUniforms:function(e,i,n,a,s){i.isMeshBasicMaterial||i.isMeshLambertMaterial?r(e,i):i.isMeshToonMaterial?(r(e,i),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap);}(e,i)):i.isMeshPhongMaterial?(r(e,i),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4);}(e,i)):i.isMeshStandardMaterial?(r(e,i),function(e,r){e.roughness.value=r.roughness,e.metalness.value=r.metalness,r.roughnessMap&&(e.roughnessMap.value=r.roughnessMap);r.metalnessMap&&(e.metalnessMap.value=r.metalnessMap);t.get(r).envMap&&(e.envMapIntensity.value=r.envMapIntensity);}(e,i),i.isMeshPhysicalMaterial&&function(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap),t.clearcoatNormalMap&&(e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),e.clearcoatNormalMap.value=t.clearcoatNormalMap,1===t.side&&e.clearcoatNormalScale.value.negate()));t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap);t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap);}(e,i,s)):i.isMeshMatcapMaterial?(r(e,i),function(e,t){t.matcap&&(e.matcap.value=t.matcap);}(e,i)):i.isMeshDepthMaterial?r(e,i):i.isMeshDistanceMaterial?(r(e,i),function(e,t){e.referencePosition.value.copy(t.referencePosition),e.nearDistance.value=t.nearDistance,e.farDistance.value=t.farDistance;}(e,i)):i.isMeshNormalMaterial?r(e,i):i.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity;}(e,i),i.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale;}(e,i)):i.isPointsMaterial?function(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=.5*i,t.map&&(e.map.value=t.map);t.alphaMap&&(e.alphaMap.value=t.alphaMap);t.alphaTest>0&&(e.alphaTest.value=t.alphaTest);let n;t.map?n=t.map:t.alphaMap&&(n=t.alphaMap);void 0!==n&&(!0===n.matrixAutoUpdate&&n.updateMatrix(),e.uvTransform.value.copy(n.matrix));}(e,i,n,a):i.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map);t.alphaMap&&(e.alphaMap.value=t.alphaMap);t.alphaTest>0&&(e.alphaTest.value=t.alphaTest);let r;t.map?r=t.map:t.alphaMap&&(r=t.alphaMap);void 0!==r&&(!0===r.matrixAutoUpdate&&r.updateMatrix(),e.uvTransform.value.copy(r.matrix));}(e,i):i.isShadowMaterial?(e.color.value.copy(i.color),e.opacity.value=i.opacity):i.isShaderMaterial&&(i.uniformsNeedUpdate=!1);}}}function WebGLUniformsGroups(e,t,r,i){let n={},a={},s=[];const o=r.isWebGL2?e.getParameter(35375):0;function l(e,t,r){const i=e.value;if(void 0===r[t])return r[t]="number"==typeof i?i:i.clone(),!0;if("number"==typeof i){if(r[t]!==i)return r[t]=i,!0}else {const e=r[t];if(!1===e.equals(i))return e.copy(i),!0}return !1}function c(e){const t=e.value,r={boundary:0,storage:0};return "number"==typeof t?(r.boundary=4,r.storage=4):t.isVector2?(r.boundary=8,r.storage=8):t.isVector3||t.isColor?(r.boundary=16,r.storage=12):t.isVector4?(r.boundary=16,r.storage=16):t.isMatrix3?(r.boundary=48,r.storage=48):t.isMatrix4?(r.boundary=64,r.storage=64):t.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",t),r}function h(t){const r=t.target;r.removeEventListener("dispose",h);const i=s.indexOf(r.__bindingPointIndex);s.splice(i,1),e.deleteBuffer(n[r.id]),delete n[r.id],delete a[r.id];}return {bind:function(e,t){const r=t.program;i.uniformBlockBinding(e,r);},update:function(r,u){let d=n[r.id];void 0===d&&(!function(e){const t=e.uniforms;let r=0;let i=0;for(let e=0,n=t.length;e0){i=r%16;const e=16-i;0!==i&&e-a.boundary<0&&(r+=16-i,n.__offset=r);}r+=a.storage;}i=r%16,i>0&&(r+=16-i);e.__size=r,e.__cache={};}(r),d=function(t){const r=function(){for(let e=0;e0&&function(e,t,r){const i=W.isWebGL2;null===N&&(N=new WebGLRenderTarget(1,1,{generateMipmaps:!0,type:k.has("EXT_color_buffer_half_float")?1016:1009,minFilter:1008,samples:i&&!0===a?4:0}));f.getDrawingBufferSize(U),i?N.setSize(U.x,U.y):N.setSize(floorPowerOfTwo(U.x),floorPowerOfTwo(U.y));const n=f.getRenderTarget();f.setRenderTarget(N),f.clear();const s=f.toneMapping;f.toneMapping=0,Te(e,t,r),f.toneMapping=s,q.updateMultisampleRenderTarget(N),q.updateRenderTargetMipmap(N),f.setRenderTarget(n);}(n,t,r),i&&H.viewport(M.copy(i)),n.length>0&&Te(n,t,r),s.length>0&&Te(s,t,r),o.length>0&&Te(o,t,r),H.buffers.depth.setTest(!0),H.buffers.depth.setMask(!0),H.buffers.color.setMask(!0),H.setPolygonOffset(!1);}function Te(e,t,r){const i=!0===t.isScene?t.overrideMaterial:null;for(let n=0,a=e.length;n0?m[m.length-1]:null,p.pop(),u=p.length>0?p[p.length-1]:null;},this.getActiveCubeFace=function(){return _},this.getActiveMipmapLevel=function(){return v},this.getRenderTarget=function(){return x},this.setRenderTargetTextures=function(e,t,r){j.get(e.texture).__webglTexture=t,j.get(e.depthTexture).__webglTexture=r;const i=j.get(e);i.__hasExternalTextures=!0,i.__hasExternalTextures&&(i.__autoAllocateDepthBuffer=void 0===r,i.__autoAllocateDepthBuffer||!0===k.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1));},this.setRenderTargetFramebuffer=function(e,t){const r=j.get(e);r.__webglFramebuffer=t,r.__useDefaultFramebuffer=void 0===t;},this.setRenderTarget=function(e,t=0,r=0){x=e,_=t,v=r;let i=!0;if(e){const t=j.get(e);void 0!==t.__useDefaultFramebuffer?(H.bindFramebuffer(36160,null),i=!1):void 0===t.__webglFramebuffer?q.setupRenderTarget(e):t.__hasExternalTextures&&q.rebindTextures(e,j.get(e.texture).__webglTexture,j.get(e.depthTexture).__webglTexture);}let n=null,a=!1,s=!1;if(e){const r=e.texture;(r.isData3DTexture||r.isDataArrayTexture)&&(s=!0);const i=j.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(n=i[t],a=!0):n=W.isWebGL2&&e.samples>0&&!1===q.useMultisampledRTT(e)?j.get(e).__webglMultisampledFramebuffer:i,M.copy(e.viewport),S.copy(e.scissor),w=e.scissorTest;}else M.copy(P).multiplyScalar(C).floor(),S.copy(R).multiplyScalar(C).floor(),w=D;if(H.bindFramebuffer(36160,n)&&W.drawBuffers&&i&&H.drawBuffers(e,n),H.viewport(M),H.scissor(S),H.setScissorTest(w),a){const i=j.get(e.texture);de.framebufferTexture2D(36160,36064,34069+t,i.__webglTexture,r);}else if(s){const i=j.get(e.texture),n=t||0;de.framebufferTextureLayer(36160,36064,i.__webglTexture,r||0,n);}y=-1;},this.readRenderTargetPixels=function(e,t,r,i,n,a,s){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=j.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==s&&(o=o[s]),o){H.bindFramebuffer(36160,o);try{const s=e.texture,o=s.format,l=s.type;if(1023!==o&&ce.convert(o)!==de.getParameter(35739))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const c=1016===l&&(k.has("EXT_color_buffer_half_float")||W.isWebGL2&&k.has("EXT_color_buffer_float"));if(!(1009===l||ce.convert(l)===de.getParameter(35738)||1015===l&&(W.isWebGL2||k.has("OES_texture_float")||k.has("WEBGL_color_buffer_float"))||c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&r>=0&&r<=e.height-n&&de.readPixels(t,r,i,n,ce.convert(o),ce.convert(l),a);}finally{const e=null!==x?j.get(x).__webglFramebuffer:null;H.bindFramebuffer(36160,e);}}},this.copyFramebufferToTexture=function(e,t,r=0){const i=Math.pow(2,-r),n=Math.floor(t.image.width*i),a=Math.floor(t.image.height*i);q.setTexture2D(t,0),de.copyTexSubImage2D(3553,r,0,0,e.x,e.y,n,a),H.unbindTexture();},this.copyTextureToTexture=function(e,t,r,i=0){const n=t.image.width,a=t.image.height,s=ce.convert(r.format),o=ce.convert(r.type);q.setTexture2D(r,0),de.pixelStorei(37440,r.flipY),de.pixelStorei(37441,r.premultiplyAlpha),de.pixelStorei(3317,r.unpackAlignment),t.isDataTexture?de.texSubImage2D(3553,i,e.x,e.y,n,a,s,o,t.image.data):t.isCompressedTexture?de.compressedTexSubImage2D(3553,i,e.x,e.y,t.mipmaps[0].width,t.mipmaps[0].height,s,t.mipmaps[0].data):de.texSubImage2D(3553,i,e.x,e.y,s,o,t.image),0===i&&r.generateMipmaps&&de.generateMipmap(3553),H.unbindTexture();},this.copyTextureToTexture3D=function(e,t,r,i,n=0){if(f.isWebGL1Renderer)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");const a=e.max.x-e.min.x+1,s=e.max.y-e.min.y+1,o=e.max.z-e.min.z+1,l=ce.convert(i.format),c=ce.convert(i.type);let h;if(i.isData3DTexture)q.setTexture3D(i,0),h=32879;else {if(!i.isDataArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");q.setTexture2DArray(i,0),h=35866;}de.pixelStorei(37440,i.flipY),de.pixelStorei(37441,i.premultiplyAlpha),de.pixelStorei(3317,i.unpackAlignment);const u=de.getParameter(3314),d=de.getParameter(32878),p=de.getParameter(3316),m=de.getParameter(3315),g=de.getParameter(32877),_=r.isCompressedTexture?r.mipmaps[0]:r.image;de.pixelStorei(3314,_.width),de.pixelStorei(32878,_.height),de.pixelStorei(3316,e.min.x),de.pixelStorei(3315,e.min.y),de.pixelStorei(32877,e.min.z),r.isDataTexture||r.isData3DTexture?de.texSubImage3D(h,n,t.x,t.y,t.z,a,s,o,l,c,_.data):r.isCompressedTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),de.compressedTexSubImage3D(h,n,t.x,t.y,t.z,a,s,o,l,_.data)):de.texSubImage3D(h,n,t.x,t.y,t.z,a,s,o,l,c,_),de.pixelStorei(3314,u),de.pixelStorei(32878,d),de.pixelStorei(3316,p),de.pixelStorei(3315,m),de.pixelStorei(32877,g),0===n&&i.generateMipmaps&&de.generateMipmap(h),H.unbindTexture();},this.initTexture=function(e){e.isCubeTexture?q.setTextureCube(e,0):e.isData3DTexture?q.setTexture3D(e,0):e.isDataArrayTexture?q.setTexture2DArray(e,0):q.setTexture2D(e,0),H.unbindTexture();},this.resetState=function(){_=0,v=0,x=null,H.reset(),he.reset();},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}));}class WebGL1Renderer extends WebGLRenderer{}WebGL1Renderer.prototype.isWebGL1Renderer=!0;class FogExp2{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Color(e),this.density=t;}clone(){return new FogExp2(this.color,this.density)}toJSON(){return {type:"FogExp2",color:this.color.getHex(),density:this.density}}}class Fog{constructor(e,t=1,r=1e3){this.isFog=!0,this.name="",this.color=new Color(e),this.near=t,this.far=r;}clone(){return new Fog(this.color,this.near,this.far)}toJSON(){return {type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}}class Scene extends Object3D{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}));}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),t}get autoUpdate(){return console.warn("THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144."),this.matrixWorldAutoUpdate}set autoUpdate(e){console.warn("THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144."),this.matrixWorldAutoUpdate=e;}}class InterleavedBuffer{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=35044,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=generateUUID();}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++;}setUsage(e){return this.usage=e,this}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,r){e*=this.stride,r*=t.stride;for(let i=0,n=this.stride;ie.far||t.push({distance:o,point:_intersectPoint.clone(),uv:Triangle.getUV(_intersectPoint,_vA,_vB,_vC,_uvA,_uvB,_uvC,new Vector2),face:null,object:this});}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function transformVertex(e,t,r,i,n,a){_alignedPosition.subVectors(e,r).addScalar(.5).multiply(i),void 0!==n?(_rotatedPosition.x=a*_alignedPosition.x-n*_alignedPosition.y,_rotatedPosition.y=n*_alignedPosition.x+a*_alignedPosition.y):_rotatedPosition.copy(_alignedPosition),e.copy(t),e.x+=_rotatedPosition.x,e.y+=_rotatedPosition.y,e.applyMatrix4(_viewWorldMatrix);}const _v1$2=new Vector3,_v2$1=new Vector3;class LOD extends Object3D{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0;}copy(e){super.copy(e,!1);const t=e.levels;for(let e=0,r=t.length;e0){let r,i;for(r=1,i=t.length;r0){_v1$2.setFromMatrixPosition(this.matrixWorld);const r=e.ray.origin.distanceTo(_v1$2);this.getObjectForDistance(r).raycast(e,t);}}update(e){const t=this.levels;if(t.length>1){_v1$2.setFromMatrixPosition(e.matrixWorld),_v2$1.setFromMatrixPosition(this.matrixWorld);const r=_v1$2.distanceTo(_v2$1)/e.zoom;let i,n;for(t[0].object.visible=!0,i=1,n=t.length;i=t[i].distance;i++)t[i-1].object.visible=!1,t[i].object.visible=!0;for(this._currentLevel=i-1;io)continue;u.applyMatrix4(this.matrixWorld);const a=e.ray.origin.distanceTo(u);ae.far||t.push({distance:a,point:h.clone().applyMatrix4(this.matrixWorld),index:r,face:null,faceIndex:null,object:this});}}else {for(let r=Math.max(0,a.start),i=Math.min(m.count,a.start+a.count)-1;ro)continue;u.applyMatrix4(this.matrixWorld);const i=e.ray.origin.distanceTo(u);ie.far||t.push({distance:i,point:h.clone().applyMatrix4(this.matrixWorld),index:r,face:null,faceIndex:null,object:this});}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const r=e[t[0]];if(void 0!==r){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=r.length;e0){const r=e[t[0]];if(void 0!==r){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=r.length;en.far)return;a.push({distance:l,distanceToRay:Math.sqrt(o),point:r,index:t,face:null,object:s});}}class VideoTexture extends Texture{constructor(e,t,r,i,n,a,s,o,l){super(e,t,r,i,n,a,s,o,l),this.isVideoTexture=!0,this.minFilter=void 0!==a?a:1006,this.magFilter=void 0!==n?n:1006,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback((function t(){c.needsUpdate=!0,e.requestVideoFrameCallback(t);}));}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;!1==="requestVideoFrameCallback"in e&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0);}}class FramebufferTexture extends Texture{constructor(e,t,r){super({width:e,height:t}),this.isFramebufferTexture=!0,this.format=r,this.magFilter=1003,this.minFilter=1003,this.generateMipmaps=!1,this.needsUpdate=!0;}}class CompressedTexture extends Texture{constructor(e,t,r,i,n,a,s,o,l,c,h,u){super(null,a,s,o,l,c,i,n,h,u),this.isCompressedTexture=!0,this.image={width:t,height:r},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1;}}class CanvasTexture extends Texture{constructor(e,t,r,i,n,a,s,o,l){super(e,t,r,i,n,a,s,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0;}}class Curve{constructor(){this.type="Curve",this.arcLengthDivisions=200;}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const r=this.getUtoTmapping(e);return this.getPoint(r,t)}getPoints(e=5){const t=[];for(let r=0;r<=e;r++)t.push(this.getPoint(r/e));return t}getSpacedPoints(e=5){const t=[];for(let r=0;r<=e;r++)t.push(this.getPointAt(r/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let r,i=this.getPoint(0),n=0;t.push(0);for(let a=1;a<=e;a++)r=this.getPoint(a/e),n+=r.distanceTo(i),t.push(n),i=r;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths();}getUtoTmapping(e,t){const r=this.getLengths();let i=0;const n=r.length;let a;a=t||e*r[n-1];let s,o=0,l=n-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),s=r[i]-a,s<0)o=i+1;else {if(!(s>0)){l=i;break}l=i-1;}if(i=l,r[i]===a)return i/(n-1);const c=r[i];return (i+(a-c)/(r[i+1]-c))/(n-1)}getTangent(e,t){let r=e-1e-4,i=e+1e-4;r<0&&(r=0),i>1&&(i=1);const n=this.getPoint(r),a=this.getPoint(i),s=t||(n.isVector2?new Vector2:new Vector3);return s.copy(a).sub(n).normalize(),s}getTangentAt(e,t){const r=this.getUtoTmapping(e);return this.getTangent(r,t)}computeFrenetFrames(e,t){const r=new Vector3,i=[],n=[],a=[],s=new Vector3,o=new Matrix4;for(let t=0;t<=e;t++){const r=t/e;i[t]=this.getTangentAt(r,new Vector3);}n[0]=new Vector3,a[0]=new Vector3;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),h=Math.abs(i[0].y),u=Math.abs(i[0].z);c<=l&&(l=c,r.set(1,0,0)),h<=l&&(l=h,r.set(0,1,0)),u<=l&&r.set(0,0,1),s.crossVectors(i[0],r).normalize(),n[0].crossVectors(i[0],s),a[0].crossVectors(i[0],n[0]);for(let t=1;t<=e;t++){if(n[t]=n[t-1].clone(),a[t]=a[t-1].clone(),s.crossVectors(i[t-1],i[t]),s.length()>Number.EPSILON){s.normalize();const e=Math.acos(clamp(i[t-1].dot(i[t]),-1,1));n[t].applyMatrix4(o.makeRotationAxis(s,e));}a[t].crossVectors(i[t],n[t]);}if(!0===t){let t=Math.acos(clamp(n[0].dot(n[e]),-1,1));t/=e,i[0].dot(s.crossVectors(n[0],n[e]))>0&&(t=-t);for(let r=1;r<=e;r++)n[r].applyMatrix4(o.makeRotationAxis(i[r],t*r)),a[r].crossVectors(i[r],n[r]);}return {tangents:i,normals:n,binormals:a}}clone(){return (new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class EllipseCurve extends Curve{constructor(e=0,t=0,r=1,i=1,n=0,a=2*Math.PI,s=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=r,this.yRadius=i,this.aStartAngle=n,this.aEndAngle=a,this.aClockwise=s,this.aRotation=o;}getPoint(e,t){const r=t||new Vector2,i=2*Math.PI;let n=this.aEndAngle-this.aStartAngle;const a=Math.abs(n)i;)n-=i;n0?0:(Math.floor(Math.abs(l)/n)+1)*n:0===c&&l===n-1&&(l=n-2,c=1),this.closed||l>0?s=i[(l-1)%n]:(tmp.subVectors(i[0],i[1]).add(i[0]),s=tmp);const h=i[l%n],u=i[(l+1)%n];if(this.closed||l+2i.length-2?i.length-1:a+1],h=i[a>i.length-3?i.length-1:a+2];return r.set(CatmullRom(s,o.x,l.x,c.x,h.x),CatmullRom(s,o.y,l.y,c.y,h.y)),r}copy(e){super.copy(e),this.points=[];for(let t=0,r=e.points.length;t=r){const e=i[n]-r,a=this.curves[n],s=a.getLength(),o=0===s?0:1-e/s;return a.getPointAt(o,t)}n++;}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths();}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let r=0,i=this.curves.length;r1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,r=e.curves.length;t0){const e=l.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y);}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class LatheGeometry extends BufferGeometry{constructor(e=[new Vector2(0,-.5),new Vector2(.5,0),new Vector2(0,.5)],t=12,r=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:r,phiLength:i},t=Math.floor(t),i=clamp(i,0,2*Math.PI);const n=[],a=[],s=[],o=[],l=[],c=1/t,h=new Vector3,u=new Vector2,d=new Vector3,p=new Vector3,m=new Vector3;let f=0,g=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:f=e[t+1].x-e[t].x,g=e[t+1].y-e[t].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case e.length-1:o.push(m.x,m.y,m.z);break;default:f=e[t+1].x-e[t].x,g=e[t+1].y-e[t].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p);}for(let n=0;n<=t;n++){const d=r+n*c*i,p=Math.sin(d),m=Math.cos(d);for(let r=0;r<=e.length-1;r++){h.x=e[r].x*p,h.y=e[r].y,h.z=e[r].x*m,a.push(h.x,h.y,h.z),u.x=n/t,u.y=r/(e.length-1),s.push(u.x,u.y);const i=o[3*r+0]*p,c=o[3*r+1],d=o[3*r+0]*m;l.push(i,c,d);}}for(let r=0;r0&&_(!0),t>0&&_(!1)),this.setIndex(c),this.setAttribute("position",new Float32BufferAttribute(h,3)),this.setAttribute("normal",new Float32BufferAttribute(u,3)),this.setAttribute("uv",new Float32BufferAttribute(d,2));}static fromJSON(e){return new CylinderGeometry(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class ConeGeometry extends CylinderGeometry{constructor(e=1,t=1,r=8,i=1,n=!1,a=0,s=2*Math.PI){super(0,e,t,r,i,n,a,s),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:r,heightSegments:i,openEnded:n,thetaStart:a,thetaLength:s};}static fromJSON(e){return new ConeGeometry(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class PolyhedronGeometry extends BufferGeometry{constructor(e=[],t=[],r=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:r,detail:i};const n=[],a=[];function s(e,t,r,i){const n=i+1,a=[];for(let i=0;i<=n;i++){a[i]=[];const s=e.clone().lerp(r,i/n),o=t.clone().lerp(r,i/n),l=n-i;for(let e=0;e<=l;e++)a[i][e]=0===e&&i===n?s:s.clone().lerp(o,e/l);}for(let e=0;e.9&&s<.1&&(t<.2&&(a[e+0]+=1),r<.2&&(a[e+2]+=1),i<.2&&(a[e+4]+=1));}}();}(),this.setAttribute("position",new Float32BufferAttribute(n,3)),this.setAttribute("normal",new Float32BufferAttribute(n.slice(),3)),this.setAttribute("uv",new Float32BufferAttribute(a,2)),0===i?this.computeVertexNormals():this.normalizeNormals();}static fromJSON(e){return new PolyhedronGeometry(e.vertices,e.indices,e.radius,e.details)}}class DodecahedronGeometry extends PolyhedronGeometry{constructor(e=1,t=0){const r=(1+Math.sqrt(5))/2,i=1/r;super([-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,-i,-r,0,-i,r,0,i,-r,0,i,r,-i,-r,0,-i,r,0,i,-r,0,i,r,0,-r,0,-i,r,0,-i,-r,0,i,r,0,i],[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],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t};}static fromJSON(e){return new DodecahedronGeometry(e.radius,e.detail)}}const _v0=new Vector3,_v1$1=new Vector3,_normal=new Vector3,_triangle=new Triangle;class EdgesGeometry extends BufferGeometry{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const r=4,i=Math.pow(10,r),n=Math.cos(DEG2RAD*t),a=e.getIndex(),s=e.getAttribute("position"),o=a?a.count:s.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let e=0;e80*r){o=c=e[0],l=h=e[1];for(let t=r;tc&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?1/p:0;}return earcutLinked(a,s,r,o,l,p),s}};function linkedList(e,t,r,i,n){let a,s;if(n===signedArea(e,t,r,i)>0)for(a=t;a=t;a-=i)s=insertNode(a,e[a],e[a+1],s);return s&&equals(s,s.next)&&(removeNode(s),s=s.next),s}function filterPoints(e,t){if(!e)return e;t||(t=e);let r,i=e;do{if(r=!1,i.steiner||!equals(i,i.next)&&0!==area(i.prev,i,i.next))i=i.next;else {if(removeNode(i),i=t=i.prev,i===i.next)break;r=!0;}}while(r||i!==t);return t}function earcutLinked(e,t,r,i,n,a,s){if(!e)return;!s&&a&&indexCurve(e,i,n,a);let o,l,c=e;for(;e.prev!==e.next;)if(o=e.prev,l=e.next,a?isEarHashed(e,i,n,a):isEar(e))t.push(o.i/r),t.push(e.i/r),t.push(l.i/r),removeNode(e),e=l.next,c=l.next;else if((e=l)===c){s?1===s?earcutLinked(e=cureLocalIntersections(filterPoints(e),t,r),t,r,i,n,a,2):2===s&&splitEarcut(e,t,r,i,n,a):earcutLinked(filterPoints(e),t,r,i,n,a,1);break}}function isEar(e){const t=e.prev,r=e,i=e.next;if(area(t,r,i)>=0)return !1;let n=e.next.next;for(;n!==e.prev;){if(pointInTriangle(t.x,t.y,r.x,r.y,i.x,i.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return !1;n=n.next;}return !0}function isEarHashed(e,t,r,i){const n=e.prev,a=e,s=e.next;if(area(n,a,s)>=0)return !1;const o=n.xa.x?n.x>s.x?n.x:s.x:a.x>s.x?a.x:s.x,h=n.y>a.y?n.y>s.y?n.y:s.y:a.y>s.y?a.y:s.y,u=zOrder(o,l,t,r,i),d=zOrder(c,h,t,r,i);let p=e.prevZ,m=e.nextZ;for(;p&&p.z>=u&&m&&m.z<=d;){if(p!==e.prev&&p!==e.next&&pointInTriangle(n.x,n.y,a.x,a.y,s.x,s.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return !1;if(p=p.prevZ,m!==e.prev&&m!==e.next&&pointInTriangle(n.x,n.y,a.x,a.y,s.x,s.y,m.x,m.y)&&area(m.prev,m,m.next)>=0)return !1;m=m.nextZ;}for(;p&&p.z>=u;){if(p!==e.prev&&p!==e.next&&pointInTriangle(n.x,n.y,a.x,a.y,s.x,s.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return !1;p=p.prevZ;}for(;m&&m.z<=d;){if(m!==e.prev&&m!==e.next&&pointInTriangle(n.x,n.y,a.x,a.y,s.x,s.y,m.x,m.y)&&area(m.prev,m,m.next)>=0)return !1;m=m.nextZ;}return !0}function cureLocalIntersections(e,t,r){let i=e;do{const n=i.prev,a=i.next.next;!equals(n,a)&&intersects(n,i,i.next,a)&&locallyInside(n,a)&&locallyInside(a,n)&&(t.push(n.i/r),t.push(i.i/r),t.push(a.i/r),removeNode(i),removeNode(i.next),i=e=a),i=i.next;}while(i!==e);return filterPoints(i)}function splitEarcut(e,t,r,i,n,a){let s=e;do{let e=s.next.next;for(;e!==s.prev;){if(s.i!==e.i&&isValidDiagonal(s,e)){let o=splitPolygon(s,e);return s=filterPoints(s,s.next),o=filterPoints(o,o.next),earcutLinked(s,t,r,i,n,a),void earcutLinked(o,t,r,i,n,a)}e=e.next;}s=s.next;}while(s!==e)}function eliminateHoles(e,t,r,i){const n=[];let a,s,o,l,c;for(a=0,s=t.length;a=r.next.y&&r.next.y!==r.y){const e=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(e<=i&&e>s){if(s=e,e===i){if(n===r.y)return r;if(n===r.next.y)return r.next}a=r.x=r.x&&r.x>=l&&i!==r.x&&pointInTriangle(na.x||r.x===a.x&§orContainsSector(a,r)))&&(a=r,u=h)),r=r.next;}while(r!==o);return a}function sectorContainsSector(e,t){return area(e.prev,e,t.prev)<0&&area(t.next,e,e.next)<0}function indexCurve(e,t,r,i){let n=e;do{null===n.z&&(n.z=zOrder(n.x,n.y,t,r,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;}while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,sortLinked(n);}function sortLinked(e){let t,r,i,n,a,s,o,l,c=1;do{for(r=e,e=null,a=null,s=0;r;){for(s++,i=r,o=0,t=0;t0||l>0&&i;)0!==o&&(0===l||!i||r.z<=i.z)?(n=r,r=r.nextZ,o--):(n=i,i=i.nextZ,l--),a?a.nextZ=n:e=n,n.prevZ=a,a=n;r=i;}a.nextZ=null,c*=2;}while(s>1);return e}function zOrder(e,t,r,i,n){return (e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-r)*n)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-i)*n)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function getLeftmost(e){let t=e,r=e;do{(t.x=0&&(e-s)*(i-o)-(r-s)*(t-o)>=0&&(r-s)*(a-o)-(n-s)*(i-o)>=0}function isValidDiagonal(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!intersectsPolygon(e,t)&&(locallyInside(e,t)&&locallyInside(t,e)&&middleInside(e,t)&&(area(e.prev,e,t.prev)||area(e,t.prev,t))||equals(e,t)&&area(e.prev,e,e.next)>0&&area(t.prev,t,t.next)>0)}function area(e,t,r){return (t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function equals(e,t){return e.x===t.x&&e.y===t.y}function intersects(e,t,r,i){const n=sign(area(e,t,r)),a=sign(area(e,t,i)),s=sign(area(r,i,e)),o=sign(area(r,i,t));return n!==a&&s!==o||(!(0!==n||!onSegment(e,r,t))||(!(0!==a||!onSegment(e,i,t))||(!(0!==s||!onSegment(r,e,i))||!(0!==o||!onSegment(r,t,i)))))}function onSegment(e,t,r){return t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function sign(e){return e>0?1:e<0?-1:0}function intersectsPolygon(e,t){let r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&intersects(r,r.next,e,t))return !0;r=r.next;}while(r!==e);return !1}function locallyInside(e,t){return area(e.prev,e,e.next)<0?area(e,t,e.next)>=0&&area(e,e.prev,t)>=0:area(e,t,e.prev)<0||area(e,e.next,t)<0}function middleInside(e,t){let r=e,i=!1;const n=(e.x+t.x)/2,a=(e.y+t.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&n<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;}while(r!==e);return i}function splitPolygon(e,t){const r=new Node(e.i,e.x,e.y),i=new Node(t.i,t.x,t.y),n=e.next,a=t.prev;return e.next=t,t.prev=e,r.next=n,n.prev=r,i.next=r,r.prev=i,a.next=i,i.prev=a,i}function insertNode(e,t,r,i){const n=new Node(e,t,r);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function removeNode(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ);}function Node(e,t,r){this.i=e,this.x=t,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function signedArea(e,t,r,i){let n=0;for(let a=t,s=r-i;a2&&e[t-1].equals(e[0])&&e.pop();}function addContour(e,t){for(let r=0;rNumber.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=t.x-o/u,m=t.y+s/u,f=((r.x-c/d-p)*c-(r.y+l/d-m)*l)/(s*c-o*l);i=p+s*f-e.x,n=m+o*f-e.y;const g=i*i+n*n;if(g<=2)return new Vector2(i,n);a=Math.sqrt(g/2);}else {let e=!1;s>Number.EPSILON?l>Number.EPSILON&&(e=!0):s<-Number.EPSILON?l<-Number.EPSILON&&(e=!0):Math.sign(o)===Math.sign(c)&&(e=!0),e?(i=-o,n=s,a=Math.sqrt(h)):(i=s,n=o,a=Math.sqrt(h/2));}return new Vector2(i/a,n/a)}const R=[];for(let e=0,t=A.length,r=t-1,i=e+1;e=0;e--){const t=e/p,r=h*Math.cos(t*Math.PI/2),i=u*Math.sin(t*Math.PI/2)+d;for(let e=0,t=A.length;e=0;){const i=r;let n=r-1;n<0&&(n=e.length-1);for(let e=0,r=o+2*p;e0)&&d.push(t,n,l),(e!==r-1||o0!=e>0&&this.version++,this._sheen=e;}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e;}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e;}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e;}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class MeshPhongMaterial extends Material{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Color(16777215),this.specular=new Color(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Color(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vector2(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e);}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class MeshToonMaterial extends Material{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Color(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Color(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vector2(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e);}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class MeshNormalMaterial extends Material{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vector2(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e);}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class MeshLambertMaterial extends Material{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Color(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Color(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vector2(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e);}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class MeshMatcapMaterial extends Material{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Color(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Vector2(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e);}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class LineDashedMaterial extends LineBasicMaterial{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e);}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function arraySlice(e,t,r){return isTypedArray(e)?new e.constructor(e.subarray(t,void 0!==r?r:e.length)):e.slice(t,r)}function convertArray(e,t,r){return !e||!r&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function getKeyframeOrder(e){const t=e.length,r=new Array(t);for(let e=0;e!==t;++e)r[e]=e;return r.sort((function(t,r){return e[t]-e[r]})),r}function sortedArray(e,t,r){const i=e.length,n=new e.constructor(i);for(let a=0,s=0;s!==i;++a){const i=r[a]*t;for(let r=0;r!==t;++r)n[s++]=e[i+r];}return n}function flattenJSON(e,t,r,i){let n=1,a=e[0];for(;void 0!==a&&void 0===a[i];)a=e[n++];if(void 0===a)return;let s=a[i];if(void 0!==s)if(Array.isArray(s))do{s=a[i],void 0!==s&&(t.push(a.time),r.push.apply(r,s)),a=e[n++];}while(void 0!==a);else if(void 0!==s.toArray)do{s=a[i],void 0!==s&&(t.push(a.time),s.toArray(r,r.length)),a=e[n++];}while(void 0!==a);else do{s=a[i],void 0!==s&&(t.push(a.time),r.push(s)),a=e[n++];}while(void 0!==a)}function subclip(e,t,r,i,n=30){const a=e.clone();a.name=t;const s=[];for(let e=0;e=i)){l.push(t.times[e]);for(let r=0;ra.tracks[e].times[0]&&(o=a.tracks[e].times[0]);for(let e=0;e=i.times[u]){const e=u*l+o,t=e+l-o;d=arraySlice(i.values,e,t);}else {const e=i.createInterpolant(),t=o,r=l-o;e.evaluate(a),d=arraySlice(e.resultBuffer,t,r);}if("quaternion"===n){(new Quaternion).fromArray(d).normalize().conjugate().toArray(d);}const p=s.times.length;for(let e=0;e=n)break e;{const s=t[1];e=n)break t}a=r,r=0;}}for(;r>>1;et;)--a;if(++a,0!==n||a!==i){n>=a&&(a=Math.max(a,1),n=a-1);const e=this.getValueSize();this.times=arraySlice(r,n,a),this.values=arraySlice(this.values,n*e,a*e);}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const r=this.times,i=this.values,n=r.length;0===n&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let t=0;t!==n;t++){const i=r[t];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,i),e=!1;break}if(null!==a&&a>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,i,a),e=!1;break}a=i;}if(void 0!==i&&isTypedArray(i))for(let t=0,r=i.length;t!==r;++t){const r=i[t];if(isNaN(r)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,r),e=!1;break}}return e}optimize(){const e=arraySlice(this.times),t=arraySlice(this.values),r=this.getValueSize(),i=2302===this.getInterpolation(),n=e.length-1;let a=1;for(let s=1;s0){e[a]=e[n];for(let e=n*r,i=a*r,s=0;s!==r;++s)t[i+s]=t[e+s];++a;}return a!==e.length?(this.times=arraySlice(e,0,a),this.values=arraySlice(t,0,a*r)):(this.times=e,this.values=t),this}clone(){const e=arraySlice(this.times,0),t=arraySlice(this.values,0),r=new(0,this.constructor)(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}}KeyframeTrack.prototype.TimeBufferType=Float32Array,KeyframeTrack.prototype.ValueBufferType=Float32Array,KeyframeTrack.prototype.DefaultInterpolation=2301;class BooleanKeyframeTrack extends KeyframeTrack{}BooleanKeyframeTrack.prototype.ValueTypeName="bool",BooleanKeyframeTrack.prototype.ValueBufferType=Array,BooleanKeyframeTrack.prototype.DefaultInterpolation=2300,BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0,BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;class ColorKeyframeTrack extends KeyframeTrack{}ColorKeyframeTrack.prototype.ValueTypeName="color";class NumberKeyframeTrack extends KeyframeTrack{}NumberKeyframeTrack.prototype.ValueTypeName="number";class QuaternionLinearInterpolant extends Interpolant{constructor(e,t,r,i){super(e,t,r,i);}interpolate_(e,t,r,i){const n=this.resultBuffer,a=this.sampleValues,s=this.valueSize,o=(r-t)/(i-t);let l=e*s;for(let e=l+s;l!==e;l+=4)Quaternion.slerpFlat(n,0,a,l-s,a,l,o);return n}}class QuaternionKeyframeTrack extends KeyframeTrack{InterpolantFactoryMethodLinear(e){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),e)}}QuaternionKeyframeTrack.prototype.ValueTypeName="quaternion",QuaternionKeyframeTrack.prototype.DefaultInterpolation=2301,QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;class StringKeyframeTrack extends KeyframeTrack{}StringKeyframeTrack.prototype.ValueTypeName="string",StringKeyframeTrack.prototype.ValueBufferType=Array,StringKeyframeTrack.prototype.DefaultInterpolation=2300,StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0,StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;class VectorKeyframeTrack extends KeyframeTrack{}VectorKeyframeTrack.prototype.ValueTypeName="vector";class AnimationClip{constructor(e,t=-1,r,i=2500){this.name=e,this.tracks=r,this.duration=t,this.blendMode=i,this.uuid=generateUUID(),this.duration<0&&this.resetDuration();}static parse(e){const t=[],r=e.tracks,i=1/(e.fps||1);for(let e=0,n=r.length;e!==n;++e)t.push(parseKeyframeTrack(r[e]).scale(i));const n=new this(e.name,e.duration,t,e.blendMode);return n.uuid=e.uuid,n}static toJSON(e){const t=[],r=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,i=r.length;e!==i;++e)t.push(KeyframeTrack.toJSON(r[e]));return i}static CreateFromMorphTargetSequence(e,t,r,i){const n=t.length,a=[];for(let e=0;e1){const e=a[1];let t=i[e];t||(i[e]=t=[]),t.push(r);}}const a=[];for(const e in i)a.push(this.CreateFromMorphTargetSequence(e,i[e],t,r));return a}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const r=function(e,t,r,i,n){if(0!==r.length){const a=[],s=[];flattenJSON(r,a,s,i),0!==a.length&&n.push(new e(t,a,s));}},i=[],n=e.name||"default",a=e.fps||30,s=e.blendMode;let o=e.length||-1;const l=e.hierarchy||[];for(let e=0;e{t&&t(n),this.manager.itemEnd(e);},0),n;if(void 0!==loading[e])return void loading[e].push({onLoad:t,onProgress:r,onError:i});loading[e]=[],loading[e].push({onLoad:t,onProgress:r,onError:i});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),s=this.mimeType,o=this.responseType;fetch(a).then(t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const r=loading[e],i=t.body.getReader(),n=t.headers.get("Content-Length"),a=n?parseInt(n):0,s=0!==a;let o=0;const l=new ReadableStream({start(e){!function t(){i.read().then(({done:i,value:n})=>{if(i)e.close();else {o+=n.byteLength;const i=new ProgressEvent("progress",{lengthComputable:s,loaded:o,total:a});for(let e=0,t=r.length;e{switch(o){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then(e=>(new DOMParser).parseFromString(e,s));case"json":return e.json();default:if(void 0===s)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(s),r=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(r);return e.arrayBuffer().then(e=>i.decode(e))}}}).then(t=>{Cache.add(e,t);const r=loading[e];delete loading[e];for(let e=0,i=r.length;e{const r=loading[e];if(void 0===r)throw this.manager.itemError(e),t;delete loading[e];for(let e=0,i=r.length;e{this.manager.itemEnd(e);}),this.manager.itemStart(e);}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class AnimationLoader extends Loader{constructor(e){super(e);}load(e,t,r,i){const n=this,a=new FileLoader(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,(function(r){try{t(n.parse(JSON.parse(r)));}catch(t){i?i(t):console.error(t),n.manager.itemError(e);}}),r,i);}parse(e){const t=[];for(let r=0;r0:i.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const n=e.uniforms[t];switch(i.uniforms[t]={},n.type){case"t":i.uniforms[t].value=r(n.value);break;case"c":i.uniforms[t].value=(new Color).setHex(n.value);break;case"v2":i.uniforms[t].value=(new Vector2).fromArray(n.value);break;case"v3":i.uniforms[t].value=(new Vector3).fromArray(n.value);break;case"v4":i.uniforms[t].value=(new Vector4).fromArray(n.value);break;case"m3":i.uniforms[t].value=(new Matrix3).fromArray(n.value);break;case"m4":i.uniforms[t].value=(new Matrix4).fromArray(n.value);break;default:i.uniforms[t].value=n.value;}}if(void 0!==e.defines&&(i.defines=e.defines),void 0!==e.vertexShader&&(i.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(i.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(i.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)i.extensions[t]=e.extensions[t];if(void 0!==e.size&&(i.size=e.size),void 0!==e.sizeAttenuation&&(i.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(i.map=r(e.map)),void 0!==e.matcap&&(i.matcap=r(e.matcap)),void 0!==e.alphaMap&&(i.alphaMap=r(e.alphaMap)),void 0!==e.bumpMap&&(i.bumpMap=r(e.bumpMap)),void 0!==e.bumpScale&&(i.bumpScale=e.bumpScale),void 0!==e.normalMap&&(i.normalMap=r(e.normalMap)),void 0!==e.normalMapType&&(i.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),i.normalScale=(new Vector2).fromArray(t);}return void 0!==e.displacementMap&&(i.displacementMap=r(e.displacementMap)),void 0!==e.displacementScale&&(i.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(i.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(i.roughnessMap=r(e.roughnessMap)),void 0!==e.metalnessMap&&(i.metalnessMap=r(e.metalnessMap)),void 0!==e.emissiveMap&&(i.emissiveMap=r(e.emissiveMap)),void 0!==e.emissiveIntensity&&(i.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(i.specularMap=r(e.specularMap)),void 0!==e.specularIntensityMap&&(i.specularIntensityMap=r(e.specularIntensityMap)),void 0!==e.specularColorMap&&(i.specularColorMap=r(e.specularColorMap)),void 0!==e.envMap&&(i.envMap=r(e.envMap)),void 0!==e.envMapIntensity&&(i.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(i.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(i.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(i.lightMap=r(e.lightMap)),void 0!==e.lightMapIntensity&&(i.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(i.aoMap=r(e.aoMap)),void 0!==e.aoMapIntensity&&(i.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(i.gradientMap=r(e.gradientMap)),void 0!==e.clearcoatMap&&(i.clearcoatMap=r(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=r(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(i.clearcoatNormalMap=r(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(i.clearcoatNormalScale=(new Vector2).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(i.iridescenceMap=r(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(i.iridescenceThicknessMap=r(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(i.transmissionMap=r(e.transmissionMap)),void 0!==e.thicknessMap&&(i.thicknessMap=r(e.thicknessMap)),void 0!==e.sheenColorMap&&(i.sheenColorMap=r(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(i.sheenRoughnessMap=r(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}static createMaterialFromType(e){return new{ShadowMaterial:ShadowMaterial,SpriteMaterial:SpriteMaterial,RawShaderMaterial:RawShaderMaterial,ShaderMaterial:ShaderMaterial,PointsMaterial:PointsMaterial,MeshPhysicalMaterial:MeshPhysicalMaterial,MeshStandardMaterial:MeshStandardMaterial,MeshPhongMaterial:MeshPhongMaterial,MeshToonMaterial:MeshToonMaterial,MeshNormalMaterial:MeshNormalMaterial,MeshLambertMaterial:MeshLambertMaterial,MeshDepthMaterial:MeshDepthMaterial,MeshDistanceMaterial:MeshDistanceMaterial,MeshBasicMaterial:MeshBasicMaterial,MeshMatcapMaterial:MeshMatcapMaterial,LineDashedMaterial:LineDashedMaterial,LineBasicMaterial:LineBasicMaterial,Material:Material}[e]}}class LoaderUtils{static decodeText(e){if("undefined"!=typeof TextDecoder)return (new TextDecoder).decode(e);let t="";for(let r=0,i=e.length;r0){const r=new LoadingManager(t);n=new ImageLoader(r),n.setCrossOrigin(this.crossOrigin);for(let t=0,r=e.length;t0){i=new ImageLoader(this.manager),i.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(r,i,this._addIndex*t,1,t);for(let e=t,n=t+t;e!==n;++e)if(r[e]!==r[e+t]){s.setValue(r,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,r=this.valueSize,i=r*this._origIndex;e.getValue(t,i);for(let e=r,n=i;e!==n;++e)t[e]=t[i+e%r];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0;}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e);}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let r=e;r=.5)for(let i=0;i!==n;++i)e[t+i]=e[r+i];}_slerp(e,t,r,i){Quaternion.slerpFlat(e,t,e,t,e,r,i);}_slerpAdditive(e,t,r,i,n){const a=this._workIndex*n;Quaternion.multiplyQuaternionsFlat(e,a,e,t,e,r),Quaternion.slerpFlat(e,t,e,t,e,a,i);}_lerp(e,t,r,i,n){const a=1-i;for(let s=0;s!==n;++s){const n=t+s;e[n]=e[n]*a+e[r+s]*i;}}_lerpAdditive(e,t,r,i,n){for(let a=0;a!==n;++a){const n=t+a;e[n]=e[n]+e[r+a]*i;}}}const _RESERVED_CHARS_RE="\\[\\]\\.:\\/",_reservedRe=new RegExp("[\\[\\]\\.:\\/]","g"),_wordChar="[^\\[\\]\\.:\\/]",_wordCharOrDot="[^"+"\\[\\]\\.:\\/".replace("\\.","")+"]",_directoryRe=/((?:WC+[\/:])*)/.source.replace("WC",_wordChar),_nodeRe=/(WCOD+)?/.source.replace("WCOD",_wordCharOrDot),_objectRe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",_wordChar),_propertyRe=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",_wordChar),_trackRe=new RegExp("^"+_directoryRe+_nodeRe+_objectRe+_propertyRe+"$"),_supportedObjectNames=["material","materials","bones","map"];class Composite{constructor(e,t,r){const i=r||PropertyBinding.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i);}getValue(e,t){this.bind();const r=this._targetGroup.nCachedObjects_,i=this._bindings[r];void 0!==i&&i.getValue(e,t);}setValue(e,t){const r=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=r.length;i!==n;++i)r[i].setValue(e,t);}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,r=e.length;t!==r;++t)e[t].bind();}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,r=e.length;t!==r;++t)e[t].unbind();}}class PropertyBinding{constructor(e,t,r){this.path=t,this.parsedPath=r||PropertyBinding.parseTrackName(t),this.node=PropertyBinding.findNode(e,this.parsedPath.nodeName)||e,this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound;}static create(e,t,r){return e&&e.isAnimationObjectGroup?new PropertyBinding.Composite(e,t,r):new PropertyBinding(e,t,r)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(_reservedRe,"")}static parseTrackName(e){const t=_trackRe.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const r={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=r.nodeName&&r.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=r.nodeName.substring(i+1);-1!==_supportedObjectNames.indexOf(e)&&(r.nodeName=r.nodeName.substring(0,i),r.objectName=e);}if(null===r.propertyName||0===r.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return r}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const r=e.skeleton.getBoneByName(t);if(void 0!==r)return r}if(e.children){const r=function(e){for(let i=0;i=n){const a=n++,c=e[a];t[c.uuid]=l,e[l]=c,t[o]=a,e[a]=s;for(let e=0,t=i;e!==t;++e){const t=r[e],i=t[a],n=t[l];t[l]=i,t[a]=n;}}}this.nCachedObjects_=n;}uncache(){const e=this._objects,t=this._indicesByUUID,r=this._bindings,i=r.length;let n=this.nCachedObjects_,a=e.length;for(let s=0,o=arguments.length;s!==o;++s){const o=arguments[s].uuid,l=t[o];if(void 0!==l)if(delete t[o],l0&&(t[s.uuid]=l),e[l]=s,e.pop();for(let e=0,t=i;e!==t;++e){const t=r[e];t[l]=t[n],t.pop();}}}this.nCachedObjects_=n;}subscribe_(e,t){const r=this._bindingsIndicesByPath;let i=r[e];const n=this._bindings;if(void 0!==i)return n[i];const a=this._paths,s=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);i=n.length,r[e]=i,a.push(e),s.push(t),n.push(h);for(let r=c,i=o.length;r!==i;++r){const i=o[r];h[r]=new PropertyBinding(i,e,t);}return h}unsubscribe_(e){const t=this._bindingsIndicesByPath,r=t[e];if(void 0!==r){const i=this._paths,n=this._parsedPaths,a=this._bindings,s=a.length-1,o=a[s];t[e[s]]=r,a[r]=o,a.pop(),n[r]=n[s],n.pop(),i[r]=i[s],i.pop();}}}class AnimationAction{constructor(e,t,r=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=r,this.blendMode=i;const n=t.tracks,a=n.length,s=new Array(a),o={endingStart:2400,endingEnd:2400};for(let e=0;e!==a;++e){const t=n[e].createInterpolant(null);s[e]=t,t.settings=o;}this._interpolantSettings=o,this._interpolants=s,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0;}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,r){if(e.fadeOut(t),this.fadeIn(t),r){const r=this._clip.duration,i=e._clip.duration,n=i/r,a=r/i;e.warp(1,n,t),this.warp(a,1,t);}return this}crossFadeTo(e,t,r){return e.crossFadeFrom(this,t,r)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,r){const i=this._mixer,n=i.time,a=this.timeScale;let s=this._timeScaleInterpolant;null===s&&(s=i._lendControlInterpolant(),this._timeScaleInterpolant=s);const o=s.parameterPositions,l=s.sampleValues;return o[0]=n,o[1]=n+r,l[0]=e/a,l[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,r,i){if(!this.enabled)return void this._updateWeight(e);const n=this._startTime;if(null!==n){const i=(e-n)*r;i<0||0===r?t=0:(this._startTime=null,t=r*i);}t*=this._updateTimeScale(e);const a=this._updateTime(t),s=this._updateWeight(e);if(s>0){const e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case 2501:for(let r=0,i=e.length;r!==i;++r)e[r].evaluate(a),t[r].accumulateAdditive(s);break;case 2500:default:for(let r=0,n=e.length;r!==n;++r)e[r].evaluate(a),t[r].accumulate(i,s);}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const r=this._weightInterpolant;if(null!==r){const i=r.evaluate(e)[0];t*=i,e>r.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1));}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const r=this._timeScaleInterpolant;if(null!==r){t*=r.evaluate(e)[0],e>r.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t);}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,r=this.loop;let i=this.time+e,n=this._loopCount;const a=2202===r;if(0===e)return -1===n?i:a&&1==(1&n)?t-i:i;if(2200===r){-1===n&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else {if(!(i<0)){this.time=i;break e}i=0;}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1});}}else {if(-1===n&&(e>=0?(n=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),i>=t||i<0){const r=Math.floor(i/t);i-=t*r,n+=Math.abs(r);const s=this.repetitions-n;if(s<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else {if(1===s){const t=e<0;this._setEndings(t,!t,a);}else this._setEndings(!1,!1,a);this._loopCount=n,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:r});}}else this.time=i;if(a&&1==(1&n))return t-i}return i}_setEndings(e,t,r){const i=this._interpolantSettings;r?(i.endingStart=2401,i.endingEnd=2401):(i.endingStart=e?this.zeroSlopeAtStart?2401:2400:2402,i.endingEnd=t?this.zeroSlopeAtEnd?2401:2400:2402);}_scheduleFading(e,t,r){const i=this._mixer,n=i.time;let a=this._weightInterpolant;null===a&&(a=i._lendControlInterpolant(),this._weightInterpolant=a);const s=a.parameterPositions,o=a.sampleValues;return s[0]=n,o[0]=t,s[1]=n+e,o[1]=r,this}}const _controlInterpolantsResultBuffer=new Float32Array(1);class AnimationMixer extends EventDispatcher{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1;}_bindAction(e,t){const r=e._localRoot||this._root,i=e._clip.tracks,n=i.length,a=e._propertyBindings,s=e._interpolants,o=r.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let e=0;e!==n;++e){const n=i[e],l=n.name;let h=c[l];if(void 0!==h)++h.referenceCount,a[e]=h;else {if(h=a[e],void 0!==h){null===h._cacheIndex&&(++h.referenceCount,this._addInactiveBinding(h,o,l));continue}const i=t&&t._propertyBindings[e].binding.parsedPath;h=new PropertyMixer(PropertyBinding.create(r,l,i),n.ValueTypeName,n.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,l),a[e]=h;}s[e].resultBuffer=h.buffer;}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,r=e._clip.uuid,i=this._actionsByClip[r];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,r,t);}const t=e._propertyBindings;for(let e=0,r=t.length;e!==r;++e){const r=t[e];0==r.useCount++&&(this._lendBinding(r),r.saveOriginalState());}this._lendAction(e);}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,r=t.length;e!==r;++e){const r=t[e];0==--r.useCount&&(r.restoreOriginalState(),this._takeBackBinding(r));}this._takeBackAction(e);}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}};}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,r=this._nActiveActions,i=this.time+=e,n=Math.sign(e),a=this._accuIndex^=1;for(let s=0;s!==r;++s){t[s]._update(i,e,n,a);}const s=this._bindings,o=this._nActiveBindings;for(let e=0;e!==o;++e)s[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;ethis.max.x||e.ythis.max.y)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return !(e.max.xthis.max.x||e.max.ythis.max.y)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return _vector$4.copy(e).clamp(this.min,this.max).sub(e).length()}intersect(e){return this.min.max(e.min),this.max.min(e.max),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const _startP=new Vector3,_startEnd=new Vector3;class Line3{constructor(e=new Vector3,t=new Vector3){this.start=e,this.end=t;}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){_startP.subVectors(e,this.start),_startEnd.subVectors(this.end,this.start);const r=_startEnd.dot(_startEnd);let i=_startEnd.dot(_startP)/r;return t&&(i=clamp(i,0,1)),i}closestPointToPoint(e,t,r){const i=this.closestPointToPointParameter(e,t);return this.delta(r).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return (new this.constructor).copy(this)}}const _vector$3=new Vector3;class SpotLightHelper extends Object3D{constructor(e,t){super(),this.light=e,this.light.updateMatrixWorld(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=t;const r=new BufferGeometry,i=[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(let e=0,t=1,r=32;e1)for(let r=0;r.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else {_axis.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(_axis,t);}}setLength(e,t=.2*e,r=.2*t){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(r,t,r),this.cone.position.y=e,this.cone.updateMatrix();}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e);}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}}class AxesHelper extends LineSegments{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],r=new BufferGeometry;r.setAttribute("position",new Float32BufferAttribute(t,3)),r.setAttribute("color",new Float32BufferAttribute([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(r,new LineBasicMaterial({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper";}setColors(e,t,r){const i=new Color,n=this.geometry.attributes.color.array;return i.set(e),i.toArray(n,0),i.toArray(n,3),i.set(t),i.toArray(n,6),i.toArray(n,9),i.set(r),i.toArray(n,12),i.toArray(n,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose();}}class ShapePath{constructor(){this.type="ShapePath",this.color=new Color,this.subPaths=[],this.currentPath=null;}moveTo(e,t){return this.currentPath=new Path,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,r,i){return this.currentPath.quadraticCurveTo(e,t,r,i),this}bezierCurveTo(e,t,r,i,n,a){return this.currentPath.bezierCurveTo(e,t,r,i,n,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const r=t.length;let i=!1;for(let n=r-1,a=0;aNumber.EPSILON){if(l<0&&(r=t[a],o=-o,s=t[n],l=-l),e.ys.y)continue;if(e.y===r.y){if(e.x===r.x)return !0}else {const t=l*(e.x-r.x)-o*(e.y-r.y);if(0===t)return !0;if(t<0)continue;i=!i;}}else {if(e.y!==r.y)continue;if(s.x<=e.x&&e.x<=r.x||r.x<=e.x&&e.x<=s.x)return !0}}return i}const r=ShapeUtils.isClockWise,i=this.subPaths;if(0===i.length)return [];let n,a,s;const o=[];if(1===i.length)return a=i[0],s=new Shape,s.curves=a.curves,o.push(s),o;let l=!r(i[0].getPoints());l=e?!l:l;const c=[],h=[];let u,d,p=[],m=0;h[m]=void 0,p[m]=[];for(let t=0,s=i.length;t1){let e=!1,r=0;for(let e=0,t=h.length;e0&&!1===e&&(p=c);}for(let e=0,t=h.length;e>-t-14,i[256|e]=1024>>-t-14|32768,n[e]=-t-1,n[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,n[e]=13,n[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,n[e]=24,n[256|e]=24):(i[e]=31744,i[256|e]=64512,n[e]=13,n[256|e]=13);}const a=new Uint32Array(2048),s=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,r=0;for(;0==(8388608&t);)t<<=1,r-=8388608;t&=-8388609,r+=947912704,a[e]=t|r;}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)s[e]=e<<23;s[31]=1199570944,s[32]=2147483648;for(let e=33;e<63;++e)s[e]=2147483648+(e-32<<23);s[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return {floatView:t,uint32View:r,baseTable:i,shiftTable:n,mantissaTable:a,exponentTable:s,offsetTable:o}}function toHalfFloat(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=clamp(e,-65504,65504),_tables.floatView[0]=e;const t=_tables.uint32View[0],r=t>>23&511;return _tables.baseTable[r]+((8388607&t)>>_tables.shiftTable[r])}function fromHalfFloat(e){const t=e>>10;return _tables.uint32View[0]=_tables.mantissaTable[_tables.offsetTable[t]+(1023&e)]+_tables.exponentTable[t],_tables.floatView[0]}var DataUtils=Object.freeze({__proto__:null,toHalfFloat:toHalfFloat,fromHalfFloat:fromHalfFloat});function ImmediateRenderObject(){console.error("THREE.ImmediateRenderObject has been removed.");}class WebGLMultisampleRenderTarget extends WebGLRenderTarget{constructor(e,t,r){console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.'),super(e,t,r),this.samples=4;}}class DataTexture2DArray extends DataArrayTexture{constructor(e,t,r,i){console.warn("THREE.DataTexture2DArray has been renamed to DataArrayTexture."),super(e,t,r,i);}}class DataTexture3D extends Data3DTexture{constructor(e,t,r,i){console.warn("THREE.DataTexture3D has been renamed to Data3DTexture."),super(e,t,r,i);}}class BoxBufferGeometry extends BoxGeometry{constructor(e,t,r,i,n,a){console.warn("THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry."),super(e,t,r,i,n,a);}}class CapsuleBufferGeometry extends CapsuleGeometry{constructor(e,t,r,i){console.warn("THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry."),super(e,t,r,i);}}class CircleBufferGeometry extends CircleGeometry{constructor(e,t,r,i){console.warn("THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry."),super(e,t,r,i);}}class ConeBufferGeometry extends ConeGeometry{constructor(e,t,r,i,n,a,s){console.warn("THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry."),super(e,t,r,i,n,a,s);}}class CylinderBufferGeometry extends CylinderGeometry{constructor(e,t,r,i,n,a,s,o){console.warn("THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry."),super(e,t,r,i,n,a,s,o);}}class DodecahedronBufferGeometry extends DodecahedronGeometry{constructor(e,t){console.warn("THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry."),super(e,t);}}class ExtrudeBufferGeometry extends ExtrudeGeometry{constructor(e,t){console.warn("THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry."),super(e,t);}}class IcosahedronBufferGeometry extends IcosahedronGeometry{constructor(e,t){console.warn("THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry."),super(e,t);}}class LatheBufferGeometry extends LatheGeometry{constructor(e,t,r,i){console.warn("THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry."),super(e,t,r,i);}}class OctahedronBufferGeometry extends OctahedronGeometry{constructor(e,t){console.warn("THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry."),super(e,t);}}class PlaneBufferGeometry extends PlaneGeometry{constructor(e,t,r,i){console.warn("THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry."),super(e,t,r,i);}}class PolyhedronBufferGeometry extends PolyhedronGeometry{constructor(e,t,r,i){console.warn("THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry."),super(e,t,r,i);}}class RingBufferGeometry extends RingGeometry{constructor(e,t,r,i,n,a){console.warn("THREE.RingBufferGeometry has been renamed to THREE.RingGeometry."),super(e,t,r,i,n,a);}}class ShapeBufferGeometry extends ShapeGeometry{constructor(e,t){console.warn("THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry."),super(e,t);}}class SphereBufferGeometry extends SphereGeometry{constructor(e,t,r,i,n,a,s){console.warn("THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry."),super(e,t,r,i,n,a,s);}}class TetrahedronBufferGeometry extends TetrahedronGeometry{constructor(e,t){console.warn("THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry."),super(e,t);}}class TorusBufferGeometry extends TorusGeometry{constructor(e,t,r,i,n){console.warn("THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry."),super(e,t,r,i,n);}}class TorusKnotBufferGeometry extends TorusKnotGeometry{constructor(e,t,r,i,n,a){console.warn("THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry."),super(e,t,r,i,n,a);}}class TubeBufferGeometry extends TubeGeometry{constructor(e,t,r,i,n){console.warn("THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry."),super(e,t,r,i,n);}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"144"}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="144"); +var THREE=/*#__PURE__*/Object.freeze({__proto__:null,ACESFilmicToneMapping:ACESFilmicToneMapping,AddEquation:AddEquation,AddOperation:AddOperation,AdditiveAnimationBlendMode:AdditiveAnimationBlendMode,AdditiveBlending:AdditiveBlending,AlphaFormat:AlphaFormat,AlwaysDepth:AlwaysDepth,AlwaysStencilFunc:AlwaysStencilFunc,AmbientLight:AmbientLight,AmbientLightProbe:AmbientLightProbe,AnimationClip:AnimationClip,AnimationLoader:AnimationLoader,AnimationMixer:AnimationMixer,AnimationObjectGroup:AnimationObjectGroup,AnimationUtils:AnimationUtils,ArcCurve:ArcCurve,ArrayCamera:ArrayCamera,ArrowHelper:ArrowHelper,Audio:Audio,AudioAnalyser:AudioAnalyser,AudioContext:AudioContext,AudioListener:AudioListener,AudioLoader:AudioLoader,AxesHelper:AxesHelper,BackSide:BackSide,BasicDepthPacking:BasicDepthPacking,BasicShadowMap:BasicShadowMap,Bone:Bone,BooleanKeyframeTrack:BooleanKeyframeTrack,Box2:Box2,Box3:Box3,Box3Helper:Box3Helper,BoxBufferGeometry:BoxBufferGeometry,BoxGeometry:BoxGeometry,BoxHelper:BoxHelper,BufferAttribute:BufferAttribute,BufferGeometry:BufferGeometry,BufferGeometryLoader:BufferGeometryLoader,ByteType:ByteType,Cache:Cache,Camera:Camera,CameraHelper:CameraHelper,CanvasTexture:CanvasTexture,CapsuleBufferGeometry:CapsuleBufferGeometry,CapsuleGeometry:CapsuleGeometry,CatmullRomCurve3:CatmullRomCurve3,CineonToneMapping:CineonToneMapping,CircleBufferGeometry:CircleBufferGeometry,CircleGeometry:CircleGeometry,ClampToEdgeWrapping:ClampToEdgeWrapping,Clock:Clock,Color:Color,ColorKeyframeTrack:ColorKeyframeTrack,ColorManagement:ColorManagement,CompressedTexture:CompressedTexture,CompressedTextureLoader:CompressedTextureLoader,ConeBufferGeometry:ConeBufferGeometry,ConeGeometry:ConeGeometry,CubeCamera:CubeCamera,CubeReflectionMapping:CubeReflectionMapping,CubeRefractionMapping:CubeRefractionMapping,CubeTexture:CubeTexture,CubeTextureLoader:CubeTextureLoader,CubeUVReflectionMapping:CubeUVReflectionMapping,CubicBezierCurve:CubicBezierCurve,CubicBezierCurve3:CubicBezierCurve3,CubicInterpolant:CubicInterpolant,CullFaceBack:CullFaceBack,CullFaceFront:CullFaceFront,CullFaceFrontBack:CullFaceFrontBack,CullFaceNone:CullFaceNone,Curve:Curve,CurvePath:CurvePath,CustomBlending:CustomBlending,CustomToneMapping:CustomToneMapping,CylinderBufferGeometry:CylinderBufferGeometry,CylinderGeometry:CylinderGeometry,Cylindrical:Cylindrical,Data3DTexture:Data3DTexture,DataArrayTexture:DataArrayTexture,DataTexture:DataTexture,DataTexture2DArray:DataTexture2DArray,DataTexture3D:DataTexture3D,DataTextureLoader:DataTextureLoader,DataUtils:DataUtils,DecrementStencilOp:DecrementStencilOp,DecrementWrapStencilOp:DecrementWrapStencilOp,DefaultLoadingManager:DefaultLoadingManager,DepthFormat:DepthFormat,DepthStencilFormat:DepthStencilFormat,DepthTexture:DepthTexture,DirectionalLight:DirectionalLight,DirectionalLightHelper:DirectionalLightHelper,DiscreteInterpolant:DiscreteInterpolant,DodecahedronBufferGeometry:DodecahedronBufferGeometry,DodecahedronGeometry:DodecahedronGeometry,DoubleSide:DoubleSide,DstAlphaFactor:DstAlphaFactor,DstColorFactor:DstColorFactor,DynamicCopyUsage:DynamicCopyUsage,DynamicDrawUsage:DynamicDrawUsage,DynamicReadUsage:DynamicReadUsage,EdgesGeometry:EdgesGeometry,EllipseCurve:EllipseCurve,EqualDepth:EqualDepth,EqualStencilFunc:EqualStencilFunc,EquirectangularReflectionMapping:EquirectangularReflectionMapping,EquirectangularRefractionMapping:EquirectangularRefractionMapping,Euler:Euler,EventDispatcher:EventDispatcher,ExtrudeBufferGeometry:ExtrudeBufferGeometry,ExtrudeGeometry:ExtrudeGeometry,FileLoader:FileLoader,Float16BufferAttribute:Float16BufferAttribute,Float32BufferAttribute:Float32BufferAttribute,Float64BufferAttribute:Float64BufferAttribute,FloatType:FloatType,Fog:Fog,FogExp2:FogExp2,FramebufferTexture:FramebufferTexture,FrontSide:FrontSide,Frustum:Frustum,GLBufferAttribute:GLBufferAttribute,GLSL1:GLSL1,GLSL3:GLSL3,GreaterDepth:GreaterDepth,GreaterEqualDepth:GreaterEqualDepth,GreaterEqualStencilFunc:GreaterEqualStencilFunc,GreaterStencilFunc:GreaterStencilFunc,GridHelper:GridHelper,Group:Group,HalfFloatType:HalfFloatType,HemisphereLight:HemisphereLight,HemisphereLightHelper:HemisphereLightHelper,HemisphereLightProbe:HemisphereLightProbe,IcosahedronBufferGeometry:IcosahedronBufferGeometry,IcosahedronGeometry:IcosahedronGeometry,ImageBitmapLoader:ImageBitmapLoader,ImageLoader:ImageLoader,ImageUtils:ImageUtils,ImmediateRenderObject:ImmediateRenderObject,IncrementStencilOp:IncrementStencilOp,IncrementWrapStencilOp:IncrementWrapStencilOp,InstancedBufferAttribute:InstancedBufferAttribute,InstancedBufferGeometry:InstancedBufferGeometry,InstancedInterleavedBuffer:InstancedInterleavedBuffer,InstancedMesh:InstancedMesh,Int16BufferAttribute:Int16BufferAttribute,Int32BufferAttribute:Int32BufferAttribute,Int8BufferAttribute:Int8BufferAttribute,IntType:IntType,InterleavedBuffer:InterleavedBuffer,InterleavedBufferAttribute:InterleavedBufferAttribute,Interpolant:Interpolant,InterpolateDiscrete:InterpolateDiscrete,InterpolateLinear:InterpolateLinear,InterpolateSmooth:InterpolateSmooth,InvertStencilOp:InvertStencilOp,KeepStencilOp:KeepStencilOp,KeyframeTrack:KeyframeTrack,LOD:LOD,LatheBufferGeometry:LatheBufferGeometry,LatheGeometry:LatheGeometry,Layers:Layers,LessDepth:LessDepth,LessEqualDepth:LessEqualDepth,LessEqualStencilFunc:LessEqualStencilFunc,LessStencilFunc:LessStencilFunc,Light:Light,LightProbe:LightProbe,Line:Line,Line3:Line3,LineBasicMaterial:LineBasicMaterial,LineCurve:LineCurve,LineCurve3:LineCurve3,LineDashedMaterial:LineDashedMaterial,LineLoop:LineLoop,LineSegments:LineSegments,LinearEncoding:LinearEncoding,LinearFilter:LinearFilter,LinearInterpolant:LinearInterpolant,LinearMipMapLinearFilter:LinearMipMapLinearFilter,LinearMipMapNearestFilter:LinearMipMapNearestFilter,LinearMipmapLinearFilter:LinearMipmapLinearFilter,LinearMipmapNearestFilter:LinearMipmapNearestFilter,LinearSRGBColorSpace:LinearSRGBColorSpace,LinearToneMapping:LinearToneMapping,Loader:Loader,LoaderUtils:LoaderUtils,LoadingManager:LoadingManager,LoopOnce:LoopOnce,LoopPingPong:LoopPingPong,LoopRepeat:LoopRepeat,LuminanceAlphaFormat:LuminanceAlphaFormat,LuminanceFormat:LuminanceFormat,MOUSE:MOUSE,Material:Material,MaterialLoader:MaterialLoader,MathUtils:MathUtils,Matrix3:Matrix3,Matrix4:Matrix4,MaxEquation:MaxEquation,Mesh:Mesh,MeshBasicMaterial:MeshBasicMaterial,MeshDepthMaterial:MeshDepthMaterial,MeshDistanceMaterial:MeshDistanceMaterial,MeshLambertMaterial:MeshLambertMaterial,MeshMatcapMaterial:MeshMatcapMaterial,MeshNormalMaterial:MeshNormalMaterial,MeshPhongMaterial:MeshPhongMaterial,MeshPhysicalMaterial:MeshPhysicalMaterial,MeshStandardMaterial:MeshStandardMaterial,MeshToonMaterial:MeshToonMaterial,MinEquation:MinEquation,MirroredRepeatWrapping:MirroredRepeatWrapping,MixOperation:MixOperation,MultiplyBlending:MultiplyBlending,MultiplyOperation:MultiplyOperation,NearestFilter:NearestFilter,NearestMipMapLinearFilter:NearestMipMapLinearFilter,NearestMipMapNearestFilter:NearestMipMapNearestFilter,NearestMipmapLinearFilter:NearestMipmapLinearFilter,NearestMipmapNearestFilter:NearestMipmapNearestFilter,NeverDepth:NeverDepth,NeverStencilFunc:NeverStencilFunc,NoBlending:NoBlending,NoColorSpace:NoColorSpace,NoToneMapping:NoToneMapping,NormalAnimationBlendMode:NormalAnimationBlendMode,NormalBlending:NormalBlending,NotEqualDepth:NotEqualDepth,NotEqualStencilFunc:NotEqualStencilFunc,NumberKeyframeTrack:NumberKeyframeTrack,Object3D:Object3D,ObjectLoader:ObjectLoader,ObjectSpaceNormalMap:ObjectSpaceNormalMap,OctahedronBufferGeometry:OctahedronBufferGeometry,OctahedronGeometry:OctahedronGeometry,OneFactor:OneFactor,OneMinusDstAlphaFactor:OneMinusDstAlphaFactor,OneMinusDstColorFactor:OneMinusDstColorFactor,OneMinusSrcAlphaFactor:OneMinusSrcAlphaFactor,OneMinusSrcColorFactor:OneMinusSrcColorFactor,OrthographicCamera:OrthographicCamera,PCFShadowMap:PCFShadowMap,PCFSoftShadowMap:PCFSoftShadowMap,PMREMGenerator:PMREMGenerator,Path:Path,PerspectiveCamera:PerspectiveCamera,Plane:Plane,PlaneBufferGeometry:PlaneBufferGeometry,PlaneGeometry:PlaneGeometry,PlaneHelper:PlaneHelper,PointLight:PointLight,PointLightHelper:PointLightHelper,Points:Points,PointsMaterial:PointsMaterial,PolarGridHelper:PolarGridHelper,PolyhedronBufferGeometry:PolyhedronBufferGeometry,PolyhedronGeometry:PolyhedronGeometry,PositionalAudio:PositionalAudio,PropertyBinding:PropertyBinding,PropertyMixer:PropertyMixer,QuadraticBezierCurve:QuadraticBezierCurve,QuadraticBezierCurve3:QuadraticBezierCurve3,Quaternion:Quaternion,QuaternionKeyframeTrack:QuaternionKeyframeTrack,QuaternionLinearInterpolant:QuaternionLinearInterpolant,REVISION:REVISION,RGBADepthPacking:RGBADepthPacking,RGBAFormat:RGBAFormat,RGBAIntegerFormat:RGBAIntegerFormat,RGBA_ASTC_10x10_Format:RGBA_ASTC_10x10_Format,RGBA_ASTC_10x5_Format:RGBA_ASTC_10x5_Format,RGBA_ASTC_10x6_Format:RGBA_ASTC_10x6_Format,RGBA_ASTC_10x8_Format:RGBA_ASTC_10x8_Format,RGBA_ASTC_12x10_Format:RGBA_ASTC_12x10_Format,RGBA_ASTC_12x12_Format:RGBA_ASTC_12x12_Format,RGBA_ASTC_4x4_Format:RGBA_ASTC_4x4_Format,RGBA_ASTC_5x4_Format:RGBA_ASTC_5x4_Format,RGBA_ASTC_5x5_Format:RGBA_ASTC_5x5_Format,RGBA_ASTC_6x5_Format:RGBA_ASTC_6x5_Format,RGBA_ASTC_6x6_Format:RGBA_ASTC_6x6_Format,RGBA_ASTC_8x5_Format:RGBA_ASTC_8x5_Format,RGBA_ASTC_8x6_Format:RGBA_ASTC_8x6_Format,RGBA_ASTC_8x8_Format:RGBA_ASTC_8x8_Format,RGBA_BPTC_Format:RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:RGBA_ETC2_EAC_Format,RGBA_PVRTC_2BPPV1_Format:RGBA_PVRTC_2BPPV1_Format,RGBA_PVRTC_4BPPV1_Format:RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:RGBA_S3TC_DXT1_Format,RGBA_S3TC_DXT3_Format:RGBA_S3TC_DXT3_Format,RGBA_S3TC_DXT5_Format:RGBA_S3TC_DXT5_Format,RGBFormat:RGBFormat,RGB_ETC1_Format:RGB_ETC1_Format,RGB_ETC2_Format:RGB_ETC2_Format,RGB_PVRTC_2BPPV1_Format:RGB_PVRTC_2BPPV1_Format,RGB_PVRTC_4BPPV1_Format:RGB_PVRTC_4BPPV1_Format,RGB_S3TC_DXT1_Format:RGB_S3TC_DXT1_Format,RGFormat:RGFormat,RGIntegerFormat:RGIntegerFormat,RawShaderMaterial:RawShaderMaterial,Ray:Ray,Raycaster:Raycaster,RectAreaLight:RectAreaLight,RedFormat:RedFormat,RedIntegerFormat:RedIntegerFormat,ReinhardToneMapping:ReinhardToneMapping,RepeatWrapping:RepeatWrapping,ReplaceStencilOp:ReplaceStencilOp,ReverseSubtractEquation:ReverseSubtractEquation,RingBufferGeometry:RingBufferGeometry,RingGeometry:RingGeometry,SRGBColorSpace:SRGBColorSpace,Scene:Scene,ShaderChunk:ShaderChunk,ShaderLib:ShaderLib,ShaderMaterial:ShaderMaterial,ShadowMaterial:ShadowMaterial,Shape:Shape,ShapeBufferGeometry:ShapeBufferGeometry,ShapeGeometry:ShapeGeometry,ShapePath:ShapePath,ShapeUtils:ShapeUtils,ShortType:ShortType,Skeleton:Skeleton,SkeletonHelper:SkeletonHelper,SkinnedMesh:SkinnedMesh,Source:Source,Sphere:Sphere,SphereBufferGeometry:SphereBufferGeometry,SphereGeometry:SphereGeometry,Spherical:Spherical,SphericalHarmonics3:SphericalHarmonics3,SplineCurve:SplineCurve,SpotLight:SpotLight,SpotLightHelper:SpotLightHelper,Sprite:Sprite,SpriteMaterial:SpriteMaterial,SrcAlphaFactor:SrcAlphaFactor,SrcAlphaSaturateFactor:SrcAlphaSaturateFactor,SrcColorFactor:SrcColorFactor,StaticCopyUsage:StaticCopyUsage,StaticDrawUsage:StaticDrawUsage,StaticReadUsage:StaticReadUsage,StereoCamera:StereoCamera,StreamCopyUsage:StreamCopyUsage,StreamDrawUsage:StreamDrawUsage,StreamReadUsage:StreamReadUsage,StringKeyframeTrack:StringKeyframeTrack,SubtractEquation:SubtractEquation,SubtractiveBlending:SubtractiveBlending,TOUCH:TOUCH,TangentSpaceNormalMap:TangentSpaceNormalMap,TetrahedronBufferGeometry:TetrahedronBufferGeometry,TetrahedronGeometry:TetrahedronGeometry,Texture:Texture,TextureLoader:TextureLoader,TorusBufferGeometry:TorusBufferGeometry,TorusGeometry:TorusGeometry,TorusKnotBufferGeometry:TorusKnotBufferGeometry,TorusKnotGeometry:TorusKnotGeometry,Triangle:Triangle,TriangleFanDrawMode:TriangleFanDrawMode,TriangleStripDrawMode:TriangleStripDrawMode,TrianglesDrawMode:TrianglesDrawMode,TubeBufferGeometry:TubeBufferGeometry,TubeGeometry:TubeGeometry,UVMapping:UVMapping,Uint16BufferAttribute:Uint16BufferAttribute,Uint32BufferAttribute:Uint32BufferAttribute,Uint8BufferAttribute:Uint8BufferAttribute,Uint8ClampedBufferAttribute:Uint8ClampedBufferAttribute,Uniform:Uniform,UniformsGroup:UniformsGroup,UniformsLib:UniformsLib,UniformsUtils:UniformsUtils,UnsignedByteType:UnsignedByteType,UnsignedInt248Type:UnsignedInt248Type,UnsignedIntType:UnsignedIntType,UnsignedShort4444Type:UnsignedShort4444Type,UnsignedShort5551Type:UnsignedShort5551Type,UnsignedShortType:UnsignedShortType,VSMShadowMap:VSMShadowMap,Vector2:Vector2,Vector3:Vector3,Vector4:Vector4,VectorKeyframeTrack:VectorKeyframeTrack,VideoTexture:VideoTexture,WebGL1Renderer:WebGL1Renderer,WebGL3DRenderTarget:WebGL3DRenderTarget,WebGLArrayRenderTarget:WebGLArrayRenderTarget,WebGLCubeRenderTarget:WebGLCubeRenderTarget,WebGLMultipleRenderTargets:WebGLMultipleRenderTargets,WebGLMultisampleRenderTarget:WebGLMultisampleRenderTarget,WebGLRenderTarget:WebGLRenderTarget,WebGLRenderer:WebGLRenderer,WebGLUtils:WebGLUtils,WireframeGeometry:WireframeGeometry,WrapAroundEnding:WrapAroundEnding,ZeroCurvatureEnding:ZeroCurvatureEnding,ZeroFactor:ZeroFactor,ZeroSlopeEnding:ZeroSlopeEnding,ZeroStencilOp:ZeroStencilOp,_SRGBAFormat:_SRGBAFormat,sRGBEncoding:sRGBEncoding});const _changeEvent={type:"change"},_startEvent={type:"start"},_endEvent={type:"end"};class OrbitControls extends EventDispatcher{constructor(e,t){super(),this.object=e,this.domElement=t,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:MOUSE.ROTATE,MIDDLE:MOUSE.DOLLY,RIGHT:MOUSE.PAN},this.touches={ONE:TOUCH.ROTATE,TWO:TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return r.phi},this.getAzimuthalAngle=function(){return r.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(e){e.addEventListener("keydown",F),this._domElementKeyEvents=e;},this.saveState=function(){n.target0.copy(n.target),n.position0.copy(n.object.position),n.zoom0=n.object.zoom;},this.reset=function(){n.target.copy(n.target0),n.object.position.copy(n.position0),n.object.zoom=n.zoom0,n.object.updateProjectionMatrix(),n.dispatchEvent(_changeEvent),n.update(),a=o.NONE;},this.update=function(){const t=new Vector3,m=(new Quaternion).setFromUnitVectors(e.up,new Vector3(0,1,0)),u=m.clone().invert(),h=new Vector3,d=new Quaternion,b=2*Math.PI;return function(){const e=n.object.position;t.copy(e).sub(n.target),t.applyQuaternion(m),r.setFromVector3(t),n.autoRotate&&a===o.NONE&&P(2*Math.PI/60/60*n.autoRotateSpeed),n.enableDamping?(r.theta+=c.theta*n.dampingFactor,r.phi+=c.phi*n.dampingFactor):(r.theta+=c.theta,r.phi+=c.phi);let E=n.minAzimuthAngle,g=n.maxAzimuthAngle;return isFinite(E)&&isFinite(g)&&(E<-Math.PI?E+=b:E>Math.PI&&(E-=b),g<-Math.PI?g+=b:g>Math.PI&&(g-=b),r.theta=E<=g?Math.max(E,Math.min(g,r.theta)):r.theta>(E+g)/2?Math.max(E,r.theta):Math.min(g,r.theta)),r.phi=Math.max(n.minPolarAngle,Math.min(n.maxPolarAngle,r.phi)),r.makeSafe(),r.radius*=s,r.radius=Math.max(n.minDistance,Math.min(n.maxDistance,r.radius)),!0===n.enableDamping?n.target.addScaledVector(l,n.dampingFactor):n.target.add(l),t.setFromSpherical(r),t.applyQuaternion(u),e.copy(n.target).add(t),n.object.lookAt(n.target),!0===n.enableDamping?(c.theta*=1-n.dampingFactor,c.phi*=1-n.dampingFactor,l.multiplyScalar(1-n.dampingFactor)):(c.set(0,0,0),l.set(0,0,0)),s=1,!!(p||h.distanceToSquared(n.object.position)>i||8*(1-d.dot(n.object.quaternion))>i)&&(n.dispatchEvent(_changeEvent),h.copy(n.object.position),d.copy(n.object.quaternion),p=!1,!0)}}(),this.dispose=function(){n.domElement.removeEventListener("contextmenu",X),n.domElement.removeEventListener("pointerdown",U),n.domElement.removeEventListener("pointercancel",V),n.domElement.removeEventListener("wheel",z),n.domElement.removeEventListener("pointermove",H),n.domElement.removeEventListener("pointerup",I),null!==n._domElementKeyEvents&&n._domElementKeyEvents.removeEventListener("keydown",F);};const n=this,o={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let a=o.NONE;const i=1e-6,r=new Spherical,c=new Spherical;let s=1;const l=new Vector3;let p=!1;const m=new Vector2,u=new Vector2,h=new Vector2,d=new Vector2,b=new Vector2,E=new Vector2,g=new Vector2,O=new Vector2,f=new Vector2,T=[],y={};function v(){return Math.pow(.95,n.zoomSpeed)}function P(e){c.theta-=e;}function A(e){c.phi-=e;}const L=function(){const e=new Vector3;return function(t,n){e.setFromMatrixColumn(n,0),e.multiplyScalar(-t),l.add(e);}}(),N=function(){const e=new Vector3;return function(t,o){!0===n.screenSpacePanning?e.setFromMatrixColumn(o,1):(e.setFromMatrixColumn(o,0),e.crossVectors(n.object.up,e)),e.multiplyScalar(t),l.add(e);}}(),M=function(){const e=new Vector3;return function(t,o){const a=n.domElement;if(n.object.isPerspectiveCamera){const i=n.object.position;e.copy(i).sub(n.target);let r=e.length();r*=Math.tan(n.object.fov/2*Math.PI/180),L(2*t*r/a.clientHeight,n.object.matrix),N(2*o*r/a.clientHeight,n.object.matrix);}else n.object.isOrthographicCamera?(L(t*(n.object.right-n.object.left)/n.object.zoom/a.clientWidth,n.object.matrix),N(o*(n.object.top-n.object.bottom)/n.object.zoom/a.clientHeight,n.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),n.enablePan=!1);}}();function w(e){n.object.isPerspectiveCamera?s/=e:n.object.isOrthographicCamera?(n.object.zoom=Math.max(n.minZoom,Math.min(n.maxZoom,n.object.zoom*e)),n.object.updateProjectionMatrix(),p=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),n.enableZoom=!1);}function j(e){n.object.isPerspectiveCamera?s*=e:n.object.isOrthographicCamera?(n.object.zoom=Math.max(n.minZoom,Math.min(n.maxZoom,n.object.zoom/e)),n.object.updateProjectionMatrix(),p=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),n.enableZoom=!1);}function S(e){m.set(e.clientX,e.clientY);}function C(e){d.set(e.clientX,e.clientY);}function R(){if(1===T.length)m.set(T[0].pageX,T[0].pageY);else {const e=.5*(T[0].pageX+T[1].pageX),t=.5*(T[0].pageY+T[1].pageY);m.set(e,t);}}function k(){if(1===T.length)d.set(T[0].pageX,T[0].pageY);else {const e=.5*(T[0].pageX+T[1].pageX),t=.5*(T[0].pageY+T[1].pageY);d.set(e,t);}}function x(){const e=T[0].pageX-T[1].pageX,t=T[0].pageY-T[1].pageY,n=Math.sqrt(e*e+t*t);g.set(0,n);}function Y(e){if(1==T.length)u.set(e.pageX,e.pageY);else {const t=B(e),n=.5*(e.pageX+t.x),o=.5*(e.pageY+t.y);u.set(n,o);}h.subVectors(u,m).multiplyScalar(n.rotateSpeed);const t=n.domElement;P(2*Math.PI*h.x/t.clientHeight),A(2*Math.PI*h.y/t.clientHeight),m.copy(u);}function _(e){if(1===T.length)b.set(e.pageX,e.pageY);else {const t=B(e),n=.5*(e.pageX+t.x),o=.5*(e.pageY+t.y);b.set(n,o);}E.subVectors(b,d).multiplyScalar(n.panSpeed),M(E.x,E.y),d.copy(b);}function D(e){const t=B(e),o=e.pageX-t.x,a=e.pageY-t.y,i=Math.sqrt(o*o+a*a);O.set(0,i),f.set(0,Math.pow(O.y/g.y,n.zoomSpeed)),w(f.y),g.copy(O);}function U(e){!1!==n.enabled&&(0===T.length&&(n.domElement.setPointerCapture(e.pointerId),n.domElement.addEventListener("pointermove",H),n.domElement.addEventListener("pointerup",I)),function(e){T.push(e);}(e),"touch"===e.pointerType?function(e){switch(K(e),T.length){case 1:switch(n.touches.ONE){case TOUCH.ROTATE:if(!1===n.enableRotate)return;R(),a=o.TOUCH_ROTATE;break;case TOUCH.PAN:if(!1===n.enablePan)return;k(),a=o.TOUCH_PAN;break;default:a=o.NONE;}break;case 2:switch(n.touches.TWO){case TOUCH.DOLLY_PAN:if(!1===n.enableZoom&&!1===n.enablePan)return;n.enableZoom&&x(),n.enablePan&&k(),a=o.TOUCH_DOLLY_PAN;break;case TOUCH.DOLLY_ROTATE:if(!1===n.enableZoom&&!1===n.enableRotate)return;n.enableZoom&&x(),n.enableRotate&&R(),a=o.TOUCH_DOLLY_ROTATE;break;default:a=o.NONE;}break;default:a=o.NONE;}a!==o.NONE&&n.dispatchEvent(_startEvent);}(e):function(e){let t;switch(e.button){case 0:t=n.mouseButtons.LEFT;break;case 1:t=n.mouseButtons.MIDDLE;break;case 2:t=n.mouseButtons.RIGHT;break;default:t=-1;}switch(t){case MOUSE.DOLLY:if(!1===n.enableZoom)return;!function(e){g.set(e.clientX,e.clientY);}(e),a=o.DOLLY;break;case MOUSE.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===n.enablePan)return;C(e),a=o.PAN;}else {if(!1===n.enableRotate)return;S(e),a=o.ROTATE;}break;case MOUSE.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===n.enableRotate)return;S(e),a=o.ROTATE;}else {if(!1===n.enablePan)return;C(e),a=o.PAN;}break;default:a=o.NONE;}a!==o.NONE&&n.dispatchEvent(_startEvent);}(e));}function H(e){!1!==n.enabled&&("touch"===e.pointerType?function(e){switch(K(e),a){case o.TOUCH_ROTATE:if(!1===n.enableRotate)return;Y(e),n.update();break;case o.TOUCH_PAN:if(!1===n.enablePan)return;_(e),n.update();break;case o.TOUCH_DOLLY_PAN:if(!1===n.enableZoom&&!1===n.enablePan)return;!function(e){n.enableZoom&&D(e),n.enablePan&&_(e);}(e),n.update();break;case o.TOUCH_DOLLY_ROTATE:if(!1===n.enableZoom&&!1===n.enableRotate)return;!function(e){n.enableZoom&&D(e),n.enableRotate&&Y(e);}(e),n.update();break;default:a=o.NONE;}}(e):function(e){switch(a){case o.ROTATE:if(!1===n.enableRotate)return;!function(e){u.set(e.clientX,e.clientY),h.subVectors(u,m).multiplyScalar(n.rotateSpeed);const t=n.domElement;P(2*Math.PI*h.x/t.clientHeight),A(2*Math.PI*h.y/t.clientHeight),m.copy(u),n.update();}(e);break;case o.DOLLY:if(!1===n.enableZoom)return;!function(e){O.set(e.clientX,e.clientY),f.subVectors(O,g),f.y>0?w(v()):f.y<0&&j(v()),g.copy(O),n.update();}(e);break;case o.PAN:if(!1===n.enablePan)return;!function(e){b.set(e.clientX,e.clientY),E.subVectors(b,d).multiplyScalar(n.panSpeed),M(E.x,E.y),d.copy(b),n.update();}(e);}}(e));}function I(e){Z(e),0===T.length&&(n.domElement.releasePointerCapture(e.pointerId),n.domElement.removeEventListener("pointermove",H),n.domElement.removeEventListener("pointerup",I)),n.dispatchEvent(_endEvent),a=o.NONE;}function V(e){Z(e);}function z(e){!1!==n.enabled&&!1!==n.enableZoom&&a===o.NONE&&(e.preventDefault(),n.dispatchEvent(_startEvent),function(e){e.deltaY<0?j(v()):e.deltaY>0&&w(v()),n.update();}(e),n.dispatchEvent(_endEvent));}function F(e){!1!==n.enabled&&!1!==n.enablePan&&function(e){let t=!1;switch(e.code){case n.keys.UP:M(0,n.keyPanSpeed),t=!0;break;case n.keys.BOTTOM:M(0,-n.keyPanSpeed),t=!0;break;case n.keys.LEFT:M(n.keyPanSpeed,0),t=!0;break;case n.keys.RIGHT:M(-n.keyPanSpeed,0),t=!0;}t&&(e.preventDefault(),n.update());}(e);}function X(e){!1!==n.enabled&&e.preventDefault();}function Z(e){delete y[e.pointerId];for(let t=0;t=2.0 are supported.")));const l=new GLTFParser(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e=0&&void 0===a[t]&&console.warn('THREE.GLTFLoader: Unknown extension "'+t+'".');}}l.setExtensions(i),l.setPlugins(a),l.parse(s,n);}parseAsync(e,t){const s=this;return new Promise((function(n,r){s.parse(e,t,n,r);}))}}function GLTFRegistry(){let e={};return {get:function(t){return e[t]},add:function(t,s){e[t]=s;},remove:function(t){delete e[t];},removeAll:function(){e={};}}}const EXTENSIONS={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:"KHR_materials_pbrSpecularGlossiness",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression"};class GLTFLightsExtension{constructor(e){this.parser=e,this.name=EXTENSIONS.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}};}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let s=0,n=t.length;s=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,i)}}class GLTFTextureWebPExtension{constructor(e){this.parser=e,this.name=EXTENSIONS.EXT_TEXTURE_WEBP,this.isSupported=null;}loadTexture(e){const t=this.name,s=this.parser,n=s.json,r=n.textures[e];if(!r.extensions||!r.extensions[t])return null;const i=r.extensions[t],a=n.images[i.source];let o=s.textureLoader;if(a.uri){const e=s.options.manager.getHandler(a.uri);null!==e&&(o=e);}return this.detectSupport().then((function(r){if(r)return s.loadTextureImage(e,i.source,o);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return s.loadTexture(e)}))}detectSupport(){return this.isSupported||(this.isSupported=new Promise((function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(1===t.height);};}))),this.isSupported}}class GLTFMeshoptCompression{constructor(e){this.name=EXTENSIONS.EXT_MESHOPT_COMPRESSION,this.parser=e;}loadBufferView(e){const t=this.parser.json,s=t.bufferViews[e];if(s.extensions&&s.extensions[this.name]){const e=s.extensions[this.name],n=this.parser.getDependency("buffer",e.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return n.then((function(t){const s=e.byteOffset||0,n=e.byteLength||0,i=e.count,a=e.byteStride,o=new Uint8Array(t,s,n);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(i,a,o,e.mode,e.filter).then((function(e){return e.buffer})):r.ready.then((function(){const t=new ArrayBuffer(i*a);return r.decodeGltfBuffer(new Uint8Array(t),i,a,o,e.mode,e.filter),t}))}))}return null}}const BINARY_EXTENSION_HEADER_MAGIC="glTF",BINARY_EXTENSION_HEADER_LENGTH=12,BINARY_EXTENSION_CHUNK_TYPES={JSON:1313821514,BIN:5130562};class GLTFBinaryExtension{constructor(e){this.name=EXTENSIONS.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,12);if(this.header={magic:LoaderUtils.decodeText(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==BINARY_EXTENSION_HEADER_MAGIC)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-12,n=new DataView(e,12);let r=0;for(;r",t).replace("#include ",s).replace("#include ",n).replace("#include ",r).replace("#include ",i);},Object.defineProperties(this,{specular:{get:function(){return a.specular.value},set:function(e){a.specular.value=e;}},specularMap:{get:function(){return a.specularMap.value},set:function(e){a.specularMap.value=e,e?this.defines.USE_SPECULARMAP="":delete this.defines.USE_SPECULARMAP;}},glossiness:{get:function(){return a.glossiness.value},set:function(e){a.glossiness.value=e;}},glossinessMap:{get:function(){return a.glossinessMap.value},set:function(e){a.glossinessMap.value=e,e?(this.defines.USE_GLOSSINESSMAP="",this.defines.USE_UV=""):(delete this.defines.USE_GLOSSINESSMAP,delete this.defines.USE_UV);}}}),delete this.metalness,delete this.roughness,delete this.metalnessMap,delete this.roughnessMap,this.setValues(e);}copy(e){return super.copy(e),this.specularMap=e.specularMap,this.specular.copy(e.specular),this.glossinessMap=e.glossinessMap,this.glossiness=e.glossiness,delete this.metalness,delete this.roughness,delete this.metalnessMap,delete this.roughnessMap,this}}class GLTFMaterialsPbrSpecularGlossinessExtension{constructor(){this.name=EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,this.specularGlossinessParams=["color","map","lightMap","lightMapIntensity","aoMap","aoMapIntensity","emissive","emissiveIntensity","emissiveMap","bumpMap","bumpScale","normalMap","normalMapType","displacementMap","displacementScale","displacementBias","specularMap","specular","glossinessMap","glossiness","alphaMap","envMap","envMapIntensity"];}getMaterialType(){return GLTFMeshStandardSGMaterial}extendParams(e,t,s){const n=t.extensions[this.name];e.color=new Color(1,1,1),e.opacity=1;const r=[];if(Array.isArray(n.diffuseFactor)){const t=n.diffuseFactor;e.color.fromArray(t),e.opacity=t[3];}if(void 0!==n.diffuseTexture&&r.push(s.assignTexture(e,"map",n.diffuseTexture,sRGBEncoding)),e.emissive=new Color(0,0,0),e.glossiness=void 0!==n.glossinessFactor?n.glossinessFactor:1,e.specular=new Color(1,1,1),Array.isArray(n.specularFactor)&&e.specular.fromArray(n.specularFactor),void 0!==n.specularGlossinessTexture){const t=n.specularGlossinessTexture;r.push(s.assignTexture(e,"glossinessMap",t)),r.push(s.assignTexture(e,"specularMap",t,sRGBEncoding));}return Promise.all(r)}createMaterial(e){const t=new GLTFMeshStandardSGMaterial(e);return t.fog=!0,t.color=e.color,t.map=void 0===e.map?null:e.map,t.lightMap=null,t.lightMapIntensity=1,t.aoMap=void 0===e.aoMap?null:e.aoMap,t.aoMapIntensity=1,t.emissive=e.emissive,t.emissiveIntensity=void 0===e.emissiveIntensity?1:e.emissiveIntensity,t.emissiveMap=void 0===e.emissiveMap?null:e.emissiveMap,t.bumpMap=void 0===e.bumpMap?null:e.bumpMap,t.bumpScale=1,t.normalMap=void 0===e.normalMap?null:e.normalMap,t.normalMapType=TangentSpaceNormalMap,e.normalScale&&(t.normalScale=e.normalScale),t.displacementMap=null,t.displacementScale=1,t.displacementBias=0,t.specularMap=void 0===e.specularMap?null:e.specularMap,t.specular=e.specular,t.glossinessMap=void 0===e.glossinessMap?null:e.glossinessMap,t.glossiness=e.glossiness,t.alphaMap=null,t.envMap=void 0===e.envMap?null:e.envMap,t.envMapIntensity=1,t}}class GLTFMeshQuantizationExtension{constructor(){this.name=EXTENSIONS.KHR_MESH_QUANTIZATION;}}class GLTFCubicSplineInterpolant extends Interpolant{constructor(e,t,s,n){super(e,t,s,n);}copySampleValue_(e){const t=this.resultBuffer,s=this.sampleValues,n=this.valueSize,r=e*n*3+n;for(let e=0;e!==n;e++)t[e]=s[r+e];return t}interpolate_(e,t,s,n){const r=this.resultBuffer,i=this.sampleValues,a=this.valueSize,o=2*a,l=3*a,c=n-t,u=(s-t)/c,h=u*u,d=h*u,p=e*l,m=p-l,T=-2*d+3*h,f=d-h,g=1-T,E=f-h+u;for(let e=0;e!==a;e++){const t=i[m+e+a],s=i[m+e+o]*c,n=i[p+e+a],l=i[p+e]*c;r[e]=g*t+E*s+T*n+f*l;}return r}}const _q=new Quaternion;class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant{interpolate_(e,t,s,n){const r=super.interpolate_(e,t,s,n);return _q.fromArray(r).normalize().toArray(r),r}}const WEBGL_CONSTANTS={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},WEBGL_COMPONENT_TYPES={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},WEBGL_FILTERS={9728:NearestFilter,9729:LinearFilter,9984:NearestMipmapNearestFilter,9985:LinearMipmapNearestFilter,9986:NearestMipmapLinearFilter,9987:LinearMipmapLinearFilter},WEBGL_WRAPPINGS={33071:ClampToEdgeWrapping,33648:MirroredRepeatWrapping,10497:RepeatWrapping},WEBGL_TYPE_SIZES={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ATTRIBUTES={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv2",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},PATH_PROPERTIES={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},INTERPOLATION={CUBICSPLINE:void 0,LINEAR:InterpolateLinear,STEP:InterpolateDiscrete},ALPHA_MODES={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function createDefaultMaterial(e){return void 0===e.DefaultMaterial&&(e.DefaultMaterial=new MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:FrontSide})),e.DefaultMaterial}function addUnknownExtensionsToUserData(e,t,s){for(const n in s.extensions)void 0===e[n]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[n]=s.extensions[n]);}function assignExtrasToUserData(e,t){void 0!==t.extras&&("object"==typeof t.extras?Object.assign(e.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras));}function addMorphTargets(e,t,s){let n=!1,r=!1,i=!1;for(let e=0,s=t.length;e0||0===e.search(/^data\:image\/jpeg/)?"image/jpeg":e.search(/\.webp($|\?)/i)>0||0===e.search(/^data\:image\/webp/)?"image/webp":"image/png"}class GLTFParser{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new GLTFRegistry,this.associations=new Map,this.primitiveCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};const s=!0===/^((?!chrome|android).)*safari/i.test(navigator.userAgent),n=navigator.userAgent.indexOf("Firefox")>-1,r=n?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1;"undefined"==typeof createImageBitmap||s||n&&r<98?this.textureLoader=new TextureLoader(this.options.manager):this.textureLoader=new ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),"use-credentials"===this.options.crossOrigin&&this.fileLoader.setWithCredentials(!0);}setExtensions(e){this.extensions=e;}setPlugins(e){this.plugins=e;}parse(e,t){const s=this,n=this.json,r=this.extensions;this.cache.removeAll(),this._invokeAll((function(e){return e._markDefs&&e._markDefs()})),Promise.all(this._invokeAll((function(e){return e.beforeRoot&&e.beforeRoot()}))).then((function(){return Promise.all([s.getDependencies("scene"),s.getDependencies("animation"),s.getDependencies("camera")])})).then((function(t){const i={scene:t[0][n.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:n.asset,parser:s,userData:{}};addUnknownExtensionsToUserData(r,i,n),assignExtrasToUserData(i,n),Promise.all(s._invokeAll((function(e){return e.afterRoot&&e.afterRoot(i)}))).then((function(){e(i);}));})).catch(t);}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],s=this.json.meshes||[];for(let s=0,n=t.length;s{const s=this.associations.get(e);null!=s&&this.associations.set(t,s);for(const[s,n]of e.children.entries())r(n,t.children[s]);};return r(s,n),n.name+="_instance_"+e.uses[t]++,n}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let s=0;s=2&&p.setY(t,u[e*i+1]),i>=3&&p.setZ(t,u[e*i+2]),i>=4&&p.setW(t,u[e*i+3]),i>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return p}))}loadTexture(e){const t=this.json,s=this.options,n=t.textures[e].source,r=t.images[n];let i=this.textureLoader;if(r.uri){const e=s.manager.getHandler(r.uri);null!==e&&(i=e);}return this.loadTextureImage(e,n,i)}loadTextureImage(e,t,s){const n=this,r=this.json,i=r.textures[e],a=r.images[t],o=(a.uri||a.bufferView)+":"+i.sampler;if(this.textureCache[o])return this.textureCache[o];const l=this.loadImageSource(t,s).then((function(t){t.flipY=!1,i.name&&(t.name=i.name);const s=(r.samplers||{})[i.sampler]||{};return t.magFilter=WEBGL_FILTERS[s.magFilter]||LinearFilter,t.minFilter=WEBGL_FILTERS[s.minFilter]||LinearMipmapLinearFilter,t.wrapS=WEBGL_WRAPPINGS[s.wrapS]||RepeatWrapping,t.wrapT=WEBGL_WRAPPINGS[s.wrapT]||RepeatWrapping,n.associations.set(t,{textures:e}),t})).catch((function(){return null}));return this.textureCache[o]=l,l}loadImageSource(e,t){const s=this,n=this.json,r=this.options;if(void 0!==this.sourceCache[e])return this.sourceCache[e].then(e=>e.clone());const i=n.images[e],a=self.URL||self.webkitURL;let o=i.uri||"",l=!1;if(void 0!==i.bufferView)o=s.getDependency("bufferView",i.bufferView).then((function(e){l=!0;const t=new Blob([e],{type:i.mimeType});return o=a.createObjectURL(t),o}));else if(void 0===i.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const c=Promise.resolve(o).then((function(e){return new Promise((function(s,n){let i=s;!0===t.isImageBitmapLoader&&(i=function(e){const t=new Texture(e);t.needsUpdate=!0,s(t);}),t.load(LoaderUtils.resolveURL(e,r.path),i,void 0,n);}))})).then((function(e){return !0===l&&a.revokeObjectURL(o),e.userData.mimeType=i.mimeType||getImageURIMimeType(i.uri),e})).catch((function(e){throw console.error("THREE.GLTFLoader: Couldn't load texture",o),e}));return this.sourceCache[e]=c,c}assignTexture(e,t,s,n){const r=this;return this.getDependency("texture",s.index).then((function(i){if(void 0===s.texCoord||0==s.texCoord||"aoMap"===t&&1==s.texCoord||console.warn("THREE.GLTFLoader: Custom UV set "+s.texCoord+" for texture "+t+" not yet supported."),r.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]){const e=void 0!==s.extensions?s.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=r.associations.get(i);i=r.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(i,e),r.associations.set(i,t);}}return void 0!==n&&(i.encoding=n),e[t]=i,i}))}assignFinalMaterial(e){const t=e.geometry;let s=e.material;const n=void 0===t.attributes.tangent,r=void 0!==t.attributes.color,i=void 0===t.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+s.uuid;let t=this.cache.get(e);t||(t=new PointsMaterial,Material.prototype.copy.call(t,s),t.color.copy(s.color),t.map=s.map,t.sizeAttenuation=!1,this.cache.add(e,t)),s=t;}else if(e.isLine){const e="LineBasicMaterial:"+s.uuid;let t=this.cache.get(e);t||(t=new LineBasicMaterial,Material.prototype.copy.call(t,s),t.color.copy(s.color),this.cache.add(e,t)),s=t;}if(n||r||i){let e="ClonedMaterial:"+s.uuid+":";s.isGLTFSpecularGlossinessMaterial&&(e+="specular-glossiness:"),n&&(e+="derivative-tangents:"),r&&(e+="vertex-colors:"),i&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=s.clone(),r&&(t.vertexColors=!0),i&&(t.flatShading=!0),n&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(s))),s=t;}s.aoMap&&void 0===t.attributes.uv2&&void 0!==t.attributes.uv&&t.setAttribute("uv2",t.attributes.uv),e.material=s;}getMaterialType(){return MeshStandardMaterial}loadMaterial(e){const t=this,s=this.json,n=this.extensions,r=s.materials[e];let i;const a={},o=r.extensions||{},l=[];if(o[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]){const e=n[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];i=e.getMaterialType(),l.push(e.extendParams(a,r,t));}else if(o[EXTENSIONS.KHR_MATERIALS_UNLIT]){const e=n[EXTENSIONS.KHR_MATERIALS_UNLIT];i=e.getMaterialType(),l.push(e.extendParams(a,r,t));}else {const s=r.pbrMetallicRoughness||{};if(a.color=new Color(1,1,1),a.opacity=1,Array.isArray(s.baseColorFactor)){const e=s.baseColorFactor;a.color.fromArray(e),a.opacity=e[3];}void 0!==s.baseColorTexture&&l.push(t.assignTexture(a,"map",s.baseColorTexture,sRGBEncoding)),a.metalness=void 0!==s.metallicFactor?s.metallicFactor:1,a.roughness=void 0!==s.roughnessFactor?s.roughnessFactor:1,void 0!==s.metallicRoughnessTexture&&(l.push(t.assignTexture(a,"metalnessMap",s.metallicRoughnessTexture)),l.push(t.assignTexture(a,"roughnessMap",s.metallicRoughnessTexture))),i=this._invokeOne((function(t){return t.getMaterialType&&t.getMaterialType(e)})),l.push(Promise.all(this._invokeAll((function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,a)}))));}!0===r.doubleSided&&(a.side=DoubleSide);const c=r.alphaMode||ALPHA_MODES.OPAQUE;if(c===ALPHA_MODES.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,c===ALPHA_MODES.MASK&&(a.alphaTest=void 0!==r.alphaCutoff?r.alphaCutoff:.5)),void 0!==r.normalTexture&&i!==MeshBasicMaterial&&(l.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new Vector2(1,1),void 0!==r.normalTexture.scale)){const e=r.normalTexture.scale;a.normalScale.set(e,e);}return void 0!==r.occlusionTexture&&i!==MeshBasicMaterial&&(l.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),void 0!==r.occlusionTexture.strength&&(a.aoMapIntensity=r.occlusionTexture.strength)),void 0!==r.emissiveFactor&&i!==MeshBasicMaterial&&(a.emissive=(new Color).fromArray(r.emissiveFactor)),void 0!==r.emissiveTexture&&i!==MeshBasicMaterial&&l.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,sRGBEncoding)),Promise.all(l).then((function(){let s;return s=i===GLTFMeshStandardSGMaterial?n[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(a):new i(a),r.name&&(s.name=r.name),assignExtrasToUserData(s,r),t.associations.set(s,{materials:e}),r.extensions&&addUnknownExtensionsToUserData(n,s,r),s}))}createUniqueName(e){const t=PropertyBinding.sanitizeNodeName(e||"");let s=t;for(let e=1;this.nodeNamesUsed[s];++e)s=t+"_"+e;return this.nodeNamesUsed[s]=!0,s}loadGeometries(e){const t=this,s=this.extensions,n=this.primitiveCache;function r(e){return s[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then((function(s){return addPrimitiveAttributes(s,e,t)}))}const i=[];for(let s=0,a=e.length;s0&&updateMorphTargets(h,r),h.name=t.createUniqueName(r.name||"mesh_"+e),assignExtrasToUserData(h,r),u.extensions&&addUnknownExtensionsToUserData(n,h,u),t.assignFinalMaterial(h),l.push(h);}for(let s=0,n=l.length;s1?new Group:1===t.length?t[0]:new Object3D,a!==t[0])for(let e=0,s=t.length;e{const t=new Map;for(const[e,s]of r.associations)(e instanceof Material||e instanceof Texture)&&t.set(e,s);return e.traverse(e=>{const s=r.associations.get(e);null!=s&&t.set(e,s);}),t})(i),i}))}}function buildNodeHierarchy(e,t,s,n){const r=s.nodes[e];return n.getDependency("node",e).then((function(e){if(void 0===r.skin)return e;let t;return n.getDependency("skin",r.skin).then((function(e){t=e;const s=[];for(let e=0,r=t.joints.length;ee.dispose()):t.material.dispose())),this.scene.remove(e.object3d);}start(){this.resize(),this.bindEventListeners(),this.renderer.render(this.scene,this.camera),this.loop();}update(){let e=this.clock.getDelta();this.scene.children.forEach(t=>{t.dispatchEvent({type:"update",delta:e});});}loop(){requestAnimationFrame(this.loop.bind(this)),this.update(),this.renderer.render(this.scene,this.camera);}resize(){this.fullscreen();let{width:e,height:t}=this.canvas;this.dimensions.width=e,this.dimensions.height=t,this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t);}fullscreen(){this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.width=this.canvas.offsetWidth,this.canvas.height=this.canvas.offsetHeight;}bindEventListeners(){window.onresize=this.resize.bind(this);}buildRenderer(){let{width:e,height:t}=this.dimensions,s=new WebGLRenderer({canvas:this.canvas});return s.setSize(e,t),s}buildCamera(){let{width:e,height:t}=this.dimensions,s=e/t;return new PerspectiveCamera(75,s,.1,1e3)}}class ThreeJSEntity{constructor(e={}){this.params=e,this.THREE=ThreeJSWrapper.THREE,this.object3d=this.create(),this.object3d.addEventListener("update",this.update.bind(this));}create(){throw new Error("Entities must have a create method")}update(){}}exports.GLTFLoader=GLTFLoader;exports.ThreeJSEntity=ThreeJSEntity;exports["default"]=ThreeJSWrapper; \ No newline at end of file diff --git a/build/three-js-wrapper.module.js b/build/three-js-wrapper.module.js index 8c23e2e..2565cea 100644 --- a/build/three-js-wrapper.module.js +++ b/build/three-js-wrapper.module.js @@ -1,5 +1,9 @@ -// threejs.org/license -const REVISION = '126'; +/** + * @license + * Copyright 2010-2022 Three.js Authors + * SPDX-License-Identifier: MIT + */ +const REVISION = '144'; const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; const CullFaceNone = 0; @@ -13,8 +17,6 @@ const VSMShadowMap = 3; const FrontSide = 0; const BackSide = 1; const DoubleSide = 2; -const FlatShading = 1; -const SmoothShading = 2; const NoBlending = 0; const NormalBlending = 1; const AdditiveBlending = 2; @@ -61,7 +63,6 @@ const CubeRefractionMapping = 302; const EquirectangularReflectionMapping = 303; const EquirectangularRefractionMapping = 304; const CubeUVReflectionMapping = 306; -const CubeUVRefractionMapping = 307; const RepeatWrapping = 1000; const ClampToEdgeWrapping = 1001; const MirroredRepeatWrapping = 1002; @@ -85,21 +86,18 @@ const FloatType = 1015; const HalfFloatType = 1016; const UnsignedShort4444Type = 1017; const UnsignedShort5551Type = 1018; -const UnsignedShort565Type = 1019; const UnsignedInt248Type = 1020; const AlphaFormat = 1021; -const RGBFormat = 1022; +const RGBFormat = 1022; // @deprecated since r137 const RGBAFormat = 1023; const LuminanceFormat = 1024; const LuminanceAlphaFormat = 1025; -const RGBEFormat = RGBAFormat; const DepthFormat = 1026; const DepthStencilFormat = 1027; const RedFormat = 1028; const RedIntegerFormat = 1029; const RGFormat = 1030; const RGIntegerFormat = 1031; -const RGBIntegerFormat = 1032; const RGBAIntegerFormat = 1033; const RGB_S3TC_DXT1_Format = 33776; @@ -128,20 +126,6 @@ const RGBA_ASTC_10x10_Format = 37819; const RGBA_ASTC_12x10_Format = 37820; const RGBA_ASTC_12x12_Format = 37821; const RGBA_BPTC_Format = 36492; -const SRGB8_ALPHA8_ASTC_4x4_Format = 37840; -const SRGB8_ALPHA8_ASTC_5x4_Format = 37841; -const SRGB8_ALPHA8_ASTC_5x5_Format = 37842; -const SRGB8_ALPHA8_ASTC_6x5_Format = 37843; -const SRGB8_ALPHA8_ASTC_6x6_Format = 37844; -const SRGB8_ALPHA8_ASTC_8x5_Format = 37845; -const SRGB8_ALPHA8_ASTC_8x6_Format = 37846; -const SRGB8_ALPHA8_ASTC_8x8_Format = 37847; -const SRGB8_ALPHA8_ASTC_10x5_Format = 37848; -const SRGB8_ALPHA8_ASTC_10x6_Format = 37849; -const SRGB8_ALPHA8_ASTC_10x8_Format = 37850; -const SRGB8_ALPHA8_ASTC_10x10_Format = 37851; -const SRGB8_ALPHA8_ASTC_12x10_Format = 37852; -const SRGB8_ALPHA8_ASTC_12x12_Format = 37853; const LoopOnce = 2200; const LoopRepeat = 2201; const LoopPingPong = 2202; @@ -158,17 +142,16 @@ const TriangleStripDrawMode = 1; const TriangleFanDrawMode = 2; const LinearEncoding = 3000; const sRGBEncoding = 3001; -const GammaEncoding = 3007; -const RGBEEncoding = 3002; -const LogLuvEncoding = 3003; -const RGBM7Encoding = 3004; -const RGBM16Encoding = 3005; -const RGBDEncoding = 3006; const BasicDepthPacking = 3200; const RGBADepthPacking = 3201; const TangentSpaceNormalMap = 0; const ObjectSpaceNormalMap = 1; +// Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available. +const NoColorSpace = ''; +const SRGBColorSpace = 'srgb'; +const LinearSRGBColorSpace = 'srgb-linear'; + const ZeroStencilOp = 0; const KeepStencilOp = 7680; const ReplaceStencilOp = 7681; @@ -200,15 +183,15 @@ const StreamCopyUsage = 35042; const GLSL1 = '100'; const GLSL3 = '300 es'; +const _SRGBAFormat = 1035; // fallback for WebGL 1 + /** * https://github.com/mrdoob/eventdispatcher.js/ */ -function EventDispatcher() {} +class EventDispatcher { -Object.assign( EventDispatcher.prototype, { - - addEventListener: function ( type, listener ) { + addEventListener( type, listener ) { if ( this._listeners === undefined ) this._listeners = {}; @@ -226,9 +209,9 @@ Object.assign( EventDispatcher.prototype, { } - }, + } - hasEventListener: function ( type, listener ) { + hasEventListener( type, listener ) { if ( this._listeners === undefined ) return false; @@ -236,9 +219,9 @@ Object.assign( EventDispatcher.prototype, { return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; - }, + } - removeEventListener: function ( type, listener ) { + removeEventListener( type, listener ) { if ( this._listeners === undefined ) return; @@ -257,9 +240,9 @@ Object.assign( EventDispatcher.prototype, { } - }, + } - dispatchEvent: function ( event ) { + dispatchEvent( event ) { if ( this._listeners === undefined ) return; @@ -279,246 +262,341 @@ Object.assign( EventDispatcher.prototype, { } + event.target = null; + } } -} ); +} + +const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; + +let _seed = 1234567; + + +const DEG2RAD = Math.PI / 180; +const RAD2DEG = 180 / Math.PI; -const _lut = []; +// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 +function generateUUID() { -for ( let i = 0; i < 256; i ++ ) { + const d0 = Math.random() * 0xffffffff | 0; + const d1 = Math.random() * 0xffffffff | 0; + const d2 = Math.random() * 0xffffffff | 0; + const d3 = Math.random() * 0xffffffff | 0; + const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; - _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); + // .toLowerCase() here flattens concatenated strings to save heap memory space. + return uuid.toLowerCase(); } -let _seed = 1234567; +function clamp( value, min, max ) { -const MathUtils = { + return Math.max( min, Math.min( max, value ) ); - DEG2RAD: Math.PI / 180, - RAD2DEG: 180 / Math.PI, +} - generateUUID: function () { +// compute euclidean modulo of m % n +// https://en.wikipedia.org/wiki/Modulo_operation +function euclideanModulo( n, m ) { - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 + return ( ( n % m ) + m ) % m; - const d0 = Math.random() * 0xffffffff | 0; - const d1 = Math.random() * 0xffffffff | 0; - const d2 = Math.random() * 0xffffffff | 0; - const d3 = Math.random() * 0xffffffff | 0; - const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + - _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + - _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + - _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; +} - // .toUpperCase() here flattens concatenated strings to save heap memory space. - return uuid.toUpperCase(); +// Linear mapping from range to range +function mapLinear( x, a1, a2, b1, b2 ) { - }, + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - clamp: function ( value, min, max ) { +} - return Math.max( min, Math.min( max, value ) ); +// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ +function inverseLerp( x, y, value ) { - }, + if ( x !== y ) { - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation + return ( value - x ) / ( y - x ); - euclideanModulo: function ( n, m ) { + } else { - return ( ( n % m ) + m ) % m; + return 0; - }, + } - // Linear mapping from range to range +} - mapLinear: function ( x, a1, a2, b1, b2 ) { +// https://en.wikipedia.org/wiki/Linear_interpolation +function lerp( x, y, t ) { - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + return ( 1 - t ) * x + t * y; - }, +} - // https://en.wikipedia.org/wiki/Linear_interpolation +// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ +function damp( x, y, lambda, dt ) { - lerp: function ( x, y, t ) { + return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); - return ( 1 - t ) * x + t * y; +} - }, +// https://www.desmos.com/calculator/vcsjnyz7x4 +function pingpong( x, length = 1 ) { - // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ + return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); - damp: function ( x, y, lambda, dt ) { +} - return MathUtils.lerp( x, y, 1 - Math.exp( - lambda * dt ) ); +// http://en.wikipedia.org/wiki/Smoothstep +function smoothstep( x, min, max ) { - }, + if ( x <= min ) return 0; + if ( x >= max ) return 1; - // https://www.desmos.com/calculator/vcsjnyz7x4 + x = ( x - min ) / ( max - min ); - pingpong: function ( x, length = 1 ) { + return x * x * ( 3 - 2 * x ); - return length - Math.abs( MathUtils.euclideanModulo( x, length * 2 ) - length ); +} - }, +function smootherstep( x, min, max ) { - // http://en.wikipedia.org/wiki/Smoothstep + if ( x <= min ) return 0; + if ( x >= max ) return 1; - smoothstep: function ( x, min, max ) { + x = ( x - min ) / ( max - min ); - if ( x <= min ) return 0; - if ( x >= max ) return 1; + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - x = ( x - min ) / ( max - min ); +} - return x * x * ( 3 - 2 * x ); +// Random integer from interval +function randInt( low, high ) { - }, + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - smootherstep: function ( x, min, max ) { +} + +// Random float from interval +function randFloat( low, high ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + return low + Math.random() * ( high - low ); - x = ( x - min ) / ( max - min ); +} - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); +// Random float from <-range/2, range/2> interval +function randFloatSpread( range ) { - }, + return range * ( 0.5 - Math.random() ); - // Random integer from interval +} - randInt: function ( low, high ) { +// Deterministic pseudo-random float in the interval [ 0, 1 ] +function seededRandom( s ) { - return low + Math.floor( Math.random() * ( high - low + 1 ) ); + if ( s !== undefined ) _seed = s; - }, + // Mulberry32 generator - // Random float from interval + let t = _seed += 0x6D2B79F5; - randFloat: function ( low, high ) { + t = Math.imul( t ^ t >>> 15, t | 1 ); - return low + Math.random() * ( high - low ); + t ^= t + Math.imul( t ^ t >>> 7, t | 61 ); - }, + return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296; - // Random float from <-range/2, range/2> interval +} - randFloatSpread: function ( range ) { +function degToRad( degrees ) { - return range * ( 0.5 - Math.random() ); + return degrees * DEG2RAD; - }, +} - // Deterministic pseudo-random float in the interval [ 0, 1 ] +function radToDeg( radians ) { - seededRandom: function ( s ) { + return radians * RAD2DEG; - if ( s !== undefined ) _seed = s % 2147483647; +} - // Park-Miller algorithm +function isPowerOfTwo( value ) { - _seed = _seed * 16807 % 2147483647; + return ( value & ( value - 1 ) ) === 0 && value !== 0; - return ( _seed - 1 ) / 2147483646; +} - }, +function ceilPowerOfTwo( value ) { - degToRad: function ( degrees ) { + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); - return degrees * MathUtils.DEG2RAD; +} - }, +function floorPowerOfTwo( value ) { - radToDeg: function ( radians ) { + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); - return radians * MathUtils.RAD2DEG; +} - }, +function setQuaternionFromProperEuler( q, a, b, c, order ) { - isPowerOfTwo: function ( value ) { + // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles - return ( value & ( value - 1 ) ) === 0 && value !== 0; + // rotations are applied to the axes in the order specified by 'order' + // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' + // angles are in radians - }, + const cos = Math.cos; + const sin = Math.sin; - ceilPowerOfTwo: function ( value ) { + const c2 = cos( b / 2 ); + const s2 = sin( b / 2 ); - return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); + const c13 = cos( ( a + c ) / 2 ); + const s13 = sin( ( a + c ) / 2 ); - }, + const c1_3 = cos( ( a - c ) / 2 ); + const s1_3 = sin( ( a - c ) / 2 ); - floorPowerOfTwo: function ( value ) { + const c3_1 = cos( ( c - a ) / 2 ); + const s3_1 = sin( ( c - a ) / 2 ); - return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); + switch ( order ) { - }, + case 'XYX': + q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); + break; - setQuaternionFromProperEuler: function ( q, a, b, c, order ) { + case 'YZY': + q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); + break; - // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles + case 'ZXZ': + q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); + break; - // rotations are applied to the axes in the order specified by 'order' - // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' - // angles are in radians + case 'XZX': + q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); + break; - const cos = Math.cos; - const sin = Math.sin; + case 'YXY': + q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); + break; - const c2 = cos( b / 2 ); - const s2 = sin( b / 2 ); + case 'ZYZ': + q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); + break; - const c13 = cos( ( a + c ) / 2 ); - const s13 = sin( ( a + c ) / 2 ); + default: + console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); - const c1_3 = cos( ( a - c ) / 2 ); - const s1_3 = sin( ( a - c ) / 2 ); + } - const c3_1 = cos( ( c - a ) / 2 ); - const s3_1 = sin( ( c - a ) / 2 ); +} - switch ( order ) { +function denormalize( value, array ) { - case 'XYX': - q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); - break; + switch ( array.constructor ) { - case 'YZY': - q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); - break; + case Float32Array: - case 'ZXZ': - q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); - break; + return value; - case 'XZX': - q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); - break; + case Uint16Array: - case 'YXY': - q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); - break; + return value / 65535.0; - case 'ZYZ': - q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); - break; + case Uint8Array: - default: - console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); + return value / 255.0; - } + case Int16Array: + + return Math.max( value / 32767.0, - 1.0 ); + + case Int8Array: + + return Math.max( value / 127.0, - 1.0 ); + + default: + + throw new Error( 'Invalid component type.' ); } -}; +} + +function normalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return Math.round( value * 65535.0 ); + + case Uint8Array: + + return Math.round( value * 255.0 ); + + case Int16Array: + + return Math.round( value * 32767.0 ); + + case Int8Array: + + return Math.round( value * 127.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + +} + +var MathUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + DEG2RAD: DEG2RAD, + RAD2DEG: RAD2DEG, + generateUUID: generateUUID, + clamp: clamp, + euclideanModulo: euclideanModulo, + mapLinear: mapLinear, + inverseLerp: inverseLerp, + lerp: lerp, + damp: damp, + pingpong: pingpong, + smoothstep: smoothstep, + smootherstep: smootherstep, + randInt: randInt, + randFloat: randFloat, + randFloatSpread: randFloatSpread, + seededRandom: seededRandom, + degToRad: degToRad, + radToDeg: radToDeg, + isPowerOfTwo: isPowerOfTwo, + ceilPowerOfTwo: ceilPowerOfTwo, + floorPowerOfTwo: floorPowerOfTwo, + setQuaternionFromProperEuler: setQuaternionFromProperEuler, + normalize: normalize, + denormalize: denormalize +}); class Vector2 { constructor( x = 0, y = 0 ) { + Vector2.prototype.isVector2 = true; + this.x = x; this.y = y; @@ -623,14 +701,7 @@ class Vector2 { } - add( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); - - } + add( v ) { this.x += v.x; this.y += v.y; @@ -666,14 +737,7 @@ class Vector2 { } - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } + sub( v ) { this.x -= v.x; this.y -= v.y; @@ -949,13 +1013,7 @@ class Vector2 { } - fromBufferAttribute( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); - - } + fromBufferAttribute( attribute, index ) { this.x = attribute.getX( index ); this.y = attribute.getY( index ); @@ -987,14 +1045,21 @@ class Vector2 { } -} + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + + } -Vector2.prototype.isVector2 = true; +} class Matrix3 { constructor() { + Matrix3.prototype.isMatrix3 = true; + this.elements = [ 1, 0, 0, @@ -1003,12 +1068,6 @@ class Matrix3 { ]; - if ( arguments.length > 0 ) { - - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - - } - } set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { @@ -1327,322 +1386,347 @@ class Matrix3 { } -Matrix3.prototype.isMatrix3 = true; - -let _canvas; +function arrayNeedsUint32( array ) { -const ImageUtils = { + // assumes larger values usually on last - getDataURL: function ( image ) { + for ( let i = array.length - 1; i >= 0; -- i ) { - if ( /^data:/i.test( image.src ) ) { + if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 - return image.src; + } - } + return false; - if ( typeof HTMLCanvasElement == 'undefined' ) { +} - return image.src; +const TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array +}; - } +function getTypedArray( type, buffer ) { - let canvas; + return new TYPED_ARRAYS[ type ]( buffer ); - if ( image instanceof HTMLCanvasElement ) { +} - canvas = image; +function createElementNS( name ) { - } else { + return document.createElementNS( 'http://www.w3.org/1999/xhtml', name ); - if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); +} - _canvas.width = image.width; - _canvas.height = image.height; +function SRGBToLinear( c ) { - const context = _canvas.getContext( '2d' ); + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); - if ( image instanceof ImageData ) { +} - context.putImageData( image, 0, 0 ); +function LinearToSRGB( c ) { - } else { + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; - context.drawImage( image, 0, 0, image.width, image.height ); +} - } +// JavaScript RGB-to-RGB transforms, defined as +// FN[InputColorSpace][OutputColorSpace] callback functions. +const FN = { + [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear }, + [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB }, +}; - canvas = _canvas; +const ColorManagement = { - } + legacyMode: true, - if ( canvas.width > 2048 || canvas.height > 2048 ) { + get workingColorSpace() { - return canvas.toDataURL( 'image/jpeg', 0.6 ); + return LinearSRGBColorSpace; - } else { + }, - return canvas.toDataURL( 'image/png' ); + set workingColorSpace( colorSpace ) { - } + console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' ); - } + }, -}; + convert: function ( color, sourceColorSpace, targetColorSpace ) { -let textureId = 0; + if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) { -class Texture extends EventDispatcher { + return color; - constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) { + } - super(); + if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) { - Object.defineProperty( this, 'id', { value: textureId ++ } ); + const fn = FN[ sourceColorSpace ][ targetColorSpace ]; - this.uuid = MathUtils.generateUUID(); + color.r = fn( color.r ); + color.g = fn( color.g ); + color.b = fn( color.b ); - this.name = ''; + return color; - this.image = image; - this.mipmaps = []; + } - this.mapping = mapping; + throw new Error( 'Unsupported color space conversion.' ); - this.wrapS = wrapS; - this.wrapT = wrapT; + }, - this.magFilter = magFilter; - this.minFilter = minFilter; + fromWorkingColorSpace: function ( color, targetColorSpace ) { - this.anisotropy = anisotropy; + return this.convert( color, this.workingColorSpace, targetColorSpace ); - this.format = format; - this.internalFormat = null; - this.type = type; + }, - this.offset = new Vector2( 0, 0 ); - this.repeat = new Vector2( 1, 1 ); - this.center = new Vector2( 0, 0 ); - this.rotation = 0; + toWorkingColorSpace: function ( color, sourceColorSpace ) { - this.matrixAutoUpdate = true; - this.matrix = new Matrix3(); + return this.convert( color, sourceColorSpace, this.workingColorSpace ); - 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) + }, - // 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; +}; - this.version = 0; - this.onUpdate = null; +const _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, 'rebeccapurple': 0x663399, '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 }; - } +const _rgb = { r: 0, g: 0, b: 0 }; +const _hslA = { h: 0, s: 0, l: 0 }; +const _hslB = { h: 0, s: 0, l: 0 }; - updateMatrix() { +function hue2rgb( p, q, t ) { - this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + 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; - } +} - clone() { +function toComponents( source, target ) { - return new this.constructor().copy( this ); + target.r = source.r; + target.g = source.g; + target.b = source.b; - } + return target; - copy( source ) { +} - this.name = source.name; +class Color { - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + constructor( r, g, b ) { - this.mapping = source.mapping; + this.isColor = true; - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + this.r = 1; + this.g = 1; + this.b = 1; - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + if ( g === undefined && b === undefined ) { - this.anisotropy = source.anisotropy; + // r is THREE.Color, hex or string + return this.set( r ); - this.format = source.format; - this.internalFormat = source.internalFormat; - this.type = source.type; + } - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); - this.center.copy( source.center ); - this.rotation = source.rotation; + return this.setRGB( r, g, b ); - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrix.copy( source.matrix ); + } - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + set( value ) { - return this; + if ( value && value.isColor ) { - } + this.copy( value ); - toJSON( meta ) { + } else if ( typeof value === 'number' ) { - const isRootObject = ( meta === undefined || typeof meta === 'string' ); + this.setHex( value ); - if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + } else if ( typeof value === 'string' ) { - return meta.textures[ this.uuid ]; + this.setStyle( value ); } - const output = { + return this; - metadata: { - version: 4.5, - type: 'Texture', - generator: 'Texture.toJSON' - }, + } - uuid: this.uuid, - name: this.name, + setScalar( scalar ) { - mapping: this.mapping, + this.r = scalar; + this.g = scalar; + this.b = scalar; - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - center: [ this.center.x, this.center.y ], - rotation: this.rotation, + return this; - wrap: [ this.wrapS, this.wrapT ], + } - format: this.format, - type: this.type, - encoding: this.encoding, + setHex( hex, colorSpace = SRGBColorSpace ) { - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + hex = Math.floor( hex ); - flipY: this.flipY, + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - premultiplyAlpha: this.premultiplyAlpha, - unpackAlignment: this.unpackAlignment + ColorManagement.toWorkingColorSpace( this, colorSpace ); - }; + return this; - if ( this.image !== undefined ) { + } - // TODO: Move to THREE.Image + setRGB( r, g, b, colorSpace = LinearSRGBColorSpace ) { - const image = this.image; + this.r = r; + this.g = g; + this.b = b; - if ( image.uuid === undefined ) { + ColorManagement.toWorkingColorSpace( this, colorSpace ); - image.uuid = MathUtils.generateUUID(); // UGH + return this; - } + } - if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) { + setHSL( h, s, l, colorSpace = LinearSRGBColorSpace ) { - let url; + // h,s,l ranges are in 0.0 - 1.0 + h = euclideanModulo( h, 1 ); + s = clamp( s, 0, 1 ); + l = clamp( l, 0, 1 ); - if ( Array.isArray( image ) ) { + if ( s === 0 ) { - // process array of images e.g. CubeTexture + this.r = this.g = this.b = l; - url = []; + } else { - for ( let i = 0, l = image.length; i < l; i ++ ) { + const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + const q = ( 2 * l ) - p; - // check cube texture with data textures + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - if ( image[ i ].isDataTexture ) { + } - url.push( serializeImage( image[ i ].image ) ); + ColorManagement.toWorkingColorSpace( this, colorSpace ); - } else { + return this; - url.push( serializeImage( image[ i ] ) ); + } - } + setStyle( style, colorSpace = SRGBColorSpace ) { - } + function handleAlpha( string ) { - } else { + if ( string === undefined ) return; - // process single image + if ( parseFloat( string ) < 1 ) { - url = serializeImage( image ); + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - } + } - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: url - }; + } - } - output.image = image.uuid; + let m; - } + if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { - if ( ! isRootObject ) { + // rgb / hsl - meta.textures[ this.uuid ] = output; + let color; + const name = m[ 1 ]; + const components = m[ 2 ]; - } + switch ( name ) { - return output; + case 'rgb': + case 'rgba': - } + if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - dispose() { + // 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; - this.dispatchEvent( { type: 'dispose' } ); + ColorManagement.toWorkingColorSpace( this, colorSpace ); - } + handleAlpha( color[ 4 ] ); - transformUv( uv ) { + return this; - if ( this.mapping !== UVMapping ) return uv; + } - uv.applyMatrix3( this.matrix ); + if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - if ( uv.x < 0 || uv.x > 1 ) { + // 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; - switch ( this.wrapS ) { + ColorManagement.toWorkingColorSpace( this, colorSpace ); - case RepeatWrapping: + handleAlpha( color[ 4 ] ); - uv.x = uv.x - Math.floor( uv.x ); - break; + return this; - case ClampToEdgeWrapping: + } - uv.x = uv.x < 0 ? 0 : 1; break; - case MirroredRepeatWrapping: + case 'hsl': + case 'hsla': - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { - uv.x = Math.ceil( uv.x ) - uv.x; + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + const h = parseFloat( color[ 1 ] ) / 360; + const s = parseFloat( color[ 2 ] ) / 100; + const l = parseFloat( color[ 3 ] ) / 100; - } else { + handleAlpha( color[ 4 ] ); - uv.x = uv.x - Math.floor( uv.x ); + return this.setHSL( h, s, l, colorSpace ); } @@ -1650,6918 +1734,6747 @@ class Texture extends EventDispatcher { } - } - - if ( uv.y < 0 || uv.y > 1 ) { - - switch ( this.wrapT ) { - - case RepeatWrapping: + } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { - uv.y = uv.y - Math.floor( uv.y ); - break; + // hex color - case ClampToEdgeWrapping: + const hex = m[ 1 ]; + const size = hex.length; - uv.y = uv.y < 0 ? 0 : 1; - break; + if ( size === 3 ) { - case MirroredRepeatWrapping: + // #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; - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + ColorManagement.toWorkingColorSpace( this, colorSpace ); - uv.y = Math.ceil( uv.y ) - uv.y; + return this; - } else { + } else if ( size === 6 ) { - uv.y = uv.y - Math.floor( uv.y ); + // #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; - } + ColorManagement.toWorkingColorSpace( this, colorSpace ); - break; + return this; } } - if ( this.flipY ) { + if ( style && style.length > 0 ) { - uv.y = 1 - uv.y; + return this.setColorName( style, colorSpace ); } - return uv; + return this; } - set needsUpdate( value ) { + setColorName( style, colorSpace = SRGBColorSpace ) { - if ( value === true ) this.version ++; + // color keywords + const hex = _colorKeywords[ style.toLowerCase() ]; - } + if ( hex !== undefined ) { -} + // red + this.setHex( hex, colorSpace ); -Texture.DEFAULT_IMAGE = undefined; -Texture.DEFAULT_MAPPING = UVMapping; + } else { -Texture.prototype.isTexture = true; + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); -function serializeImage( image ) { + } - if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || - ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + return this; - // default images + } - return ImageUtils.getDataURL( image ); + clone() { - } else { + return new this.constructor( this.r, this.g, this.b ); - if ( image.data ) { + } - // images of DataTexture + copy( color ) { - return { - data: Array.prototype.slice.call( image.data ), - width: image.width, - height: image.height, - type: image.data.constructor.name - }; - - } else { - - console.warn( 'THREE.Texture: Unable to serialize Texture.' ); - return {}; + this.r = color.r; + this.g = color.g; + this.b = color.b; - } + return this; } -} - -class Vector4 { + copySRGBToLinear( color ) { - constructor( x = 0, y = 0, z = 0, w = 1 ) { + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); - this.x = x; - this.y = y; - this.z = z; - this.w = w; + return this; } - get width() { - - return this.z; - - } + copyLinearToSRGB( color ) { - set width( value ) { + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); - this.z = value; + return this; } - get height() { - - return this.w; - - } + convertSRGBToLinear() { - set height( value ) { + this.copySRGBToLinear( this ); - this.w = value; + return this; } - set( x, y, z, w ) { + convertLinearToSRGB() { - this.x = x; - this.y = y; - this.z = z; - this.w = w; + this.copyLinearToSRGB( this ); return this; } - setScalar( scalar ) { + getHex( colorSpace = SRGBColorSpace ) { - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - return this; + return clamp( _rgb.r * 255, 0, 255 ) << 16 ^ clamp( _rgb.g * 255, 0, 255 ) << 8 ^ clamp( _rgb.b * 255, 0, 255 ) << 0; } - setX( x ) { - - this.x = x; + getHexString( colorSpace = SRGBColorSpace ) { - return this; + return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 ); } - setY( y ) { + getHSL( target, colorSpace = LinearSRGBColorSpace ) { - this.y = y; + // h,s,l ranges are in 0.0 - 1.0 - return this; + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - } + const r = _rgb.r, g = _rgb.g, b = _rgb.b; - setZ( z ) { + const max = Math.max( r, g, b ); + const min = Math.min( r, g, b ); - this.z = z; + let hue, saturation; + const lightness = ( min + max ) / 2.0; - return this; + if ( min === max ) { - } + hue = 0; + saturation = 0; - setW( w ) { + } else { - this.w = w; + const delta = max - min; - return this; + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - } + switch ( max ) { - setComponent( index, value ) { + 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; - switch ( index ) { + } - 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 ); + hue /= 6; } - return this; + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; } - getComponent( index ) { + getRGB( target, colorSpace = LinearSRGBColorSpace ) { - switch ( index ) { + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - 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 ); + target.r = _rgb.r; + target.g = _rgb.g; + target.b = _rgb.b; - } + return target; } - clone() { + getStyle( colorSpace = SRGBColorSpace ) { - return new this.constructor( this.x, this.y, this.z, this.w ); + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace ); - } + if ( colorSpace !== SRGBColorSpace ) { - copy( v ) { + // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). + return `color(${ colorSpace } ${ _rgb.r } ${ _rgb.g } ${ _rgb.b })`; - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + } - return this; + return `rgb(${( _rgb.r * 255 ) | 0},${( _rgb.g * 255 ) | 0},${( _rgb.b * 255 ) | 0})`; } - add( v, w ) { - - if ( w !== undefined ) { + offsetHSL( h, s, l ) { - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + this.getHSL( _hslA ); - } + _hslA.h += h; _hslA.s += s; _hslA.l += l; - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + this.setHSL( _hslA.h, _hslA.s, _hslA.l ); return this; } - addScalar( s ) { + add( color ) { - this.x += s; - this.y += s; - this.z += s; - this.w += s; + this.r += color.r; + this.g += color.g; + this.b += color.b; return this; } - addVectors( a, b ) { + addColors( color1, color2 ) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; return this; } - addScaledVector( v, s ) { + addScalar( s ) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + this.r += s; + this.g += s; + this.b += s; return this; } - sub( v, w ) { - - if ( w !== undefined ) { - - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); - - } + sub( color ) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + 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 ); return this; } - subScalar( s ) { + multiply( color ) { - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; return this; } - subVectors( a, b ) { + multiplyScalar( s ) { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + this.r *= s; + this.g *= s; + this.b *= s; return this; } - multiply( v ) { + lerp( color, alpha ) { - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - this.w *= v.w; + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; return this; } - multiplyScalar( scalar ) { + lerpColors( color1, color2, alpha ) { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + this.r = color1.r + ( color2.r - color1.r ) * alpha; + this.g = color1.g + ( color2.g - color1.g ) * alpha; + this.b = color1.b + ( color2.b - color1.b ) * alpha; return this; } - applyMatrix4( m ) { + lerpHSL( color, alpha ) { - const x = this.x, y = this.y, z = this.z, w = this.w; - const e = m.elements; + this.getHSL( _hslA ); + color.getHSL( _hslB ); - 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; + const h = lerp( _hslA.h, _hslB.h, alpha ); + const s = lerp( _hslA.s, _hslB.s, alpha ); + const l = lerp( _hslA.l, _hslB.l, alpha ); + + this.setHSL( h, s, l ); return this; } - divideScalar( scalar ) { + equals( c ) { - return this.multiplyScalar( 1 / scalar ); + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); } - setAxisAngleFromQuaternion( q ) { + fromArray( array, offset = 0 ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - // q is assumed to be normalized + return this; - this.w = 2 * Math.acos( q.w ); + } - const s = Math.sqrt( 1 - q.w * q.w ); + toArray( array = [], offset = 0 ) { - if ( s < 0.0001 ) { + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - this.x = 1; - this.y = 0; - this.z = 0; + return array; - } else { + } - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + fromBufferAttribute( attribute, index ) { - } + this.r = attribute.getX( index ); + this.g = attribute.getY( index ); + this.b = attribute.getZ( index ); return this; } - setAxisAngleFromRotationMatrix( m ) { - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - let angle, x, y, z; // variables for result - const epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - - te = m.elements, + toJSON() { - 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 ]; + return this.getHex(); - 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 + *[ Symbol.iterator ]() { - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + yield this.r; + yield this.g; + yield this.b; - // this singularity is identity matrix so angle = 0 + } - this.set( 1, 0, 0, 0 ); +} - return this; // zero angle, arbitrary axis +Color.NAMES = _colorKeywords; - } +let _canvas; - // otherwise this singularity is angle = 180 +class ImageUtils { - angle = Math.PI; + static getDataURL( image ) { - const xx = ( m11 + 1 ) / 2; - const yy = ( m22 + 1 ) / 2; - const zz = ( m33 + 1 ) / 2; - const xy = ( m12 + m21 ) / 4; - const xz = ( m13 + m31 ) / 4; - const yz = ( m23 + m32 ) / 4; + if ( /^data:/i.test( image.src ) ) { - if ( ( xx > yy ) && ( xx > zz ) ) { + return image.src; - // m11 is the largest diagonal term + } - if ( xx < epsilon ) { + if ( typeof HTMLCanvasElement == 'undefined' ) { - x = 0; - y = 0.707106781; - z = 0.707106781; + return image.src; - } else { + } - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + let canvas; - } + if ( image instanceof HTMLCanvasElement ) { - } else if ( yy > zz ) { + canvas = image; - // m22 is the largest diagonal term + } else { - if ( yy < epsilon ) { + if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' ); - x = 0.707106781; - y = 0; - z = 0.707106781; + _canvas.width = image.width; + _canvas.height = image.height; - } else { + const context = _canvas.getContext( '2d' ); - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + if ( image instanceof ImageData ) { - } + context.putImageData( image, 0, 0 ); } else { - // m33 is the largest diagonal term so base result on this + context.drawImage( image, 0, 0, image.width, image.height ); - if ( zz < epsilon ) { + } - x = 0.707106781; - y = 0.707106781; - z = 0; + canvas = _canvas; - } else { + } - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + if ( canvas.width > 2048 || canvas.height > 2048 ) { - } + console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image ); - } + return canvas.toDataURL( 'image/jpeg', 0.6 ); - this.set( x, y, z, angle ); + } else { - return this; // return 180 deg rotation + return canvas.toDataURL( 'image/png' ); } - // as we have reached here there are no singularities so we can handle normally - - let 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; + static sRGBToLinear( image ) { - // 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 + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + const canvas = createElementNS( 'canvas' ); - return this; + canvas.width = image.width; + canvas.height = image.height; - } + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height ); - min( v ) { + const imageData = context.getImageData( 0, 0, image.width, image.height ); + const data = imageData.data; - 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 ); + for ( let i = 0; i < data.length; i ++ ) { - return this; + data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255; - } + } - max( v ) { + context.putImageData( imageData, 0, 0 ); - 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 ); + return canvas; - return this; + } else if ( image.data ) { - } + const data = image.data.slice( 0 ); - clamp( min, max ) { + for ( let i = 0; i < data.length; i ++ ) { - // assumes min < max, componentwise + if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) { - 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 ) ); + data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 ); - return this; + } else { - } + // assuming float - clampScalar( minVal, maxVal ) { + data[ i ] = SRGBToLinear( data[ i ] ); - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); + } - return this; + } - } + return { + data: data, + width: image.width, + height: image.height + }; - clampLength( min, max ) { + } else { - const length = this.length(); + console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' ); + return image; - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + } } - floor() { +} - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); +class Source { - return this; + constructor( data = null ) { - } + this.isSource = true; - ceil() { + this.uuid = generateUUID(); - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + this.data = data; - return this; + this.version = 0; } - round() { - - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + set needsUpdate( value ) { - return this; + if ( value === true ) this.version ++; } - roundToZero() { + toJSON( meta ) { - 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 ); + const isRootObject = ( meta === undefined || typeof meta === 'string' ); - return this; + if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) { - } + return meta.images[ this.uuid ]; - negate() { + } - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + const output = { + uuid: this.uuid, + url: '' + }; - return this; + const data = this.data; - } + if ( data !== null ) { - dot( v ) { + let url; - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + if ( Array.isArray( data ) ) { - } + // cube texture - lengthSq() { + url = []; - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + for ( let i = 0, l = data.length; i < l; i ++ ) { - } + if ( data[ i ].isDataTexture ) { - length() { + url.push( serializeImage( data[ i ].image ) ); - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + } else { - } + url.push( serializeImage( data[ i ] ) ); - manhattanLength() { + } - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + } - } + } else { - normalize() { + // texture - return this.divideScalar( this.length() || 1 ); + url = serializeImage( data ); - } + } - setLength( length ) { + output.url = url; - return this.normalize().multiplyScalar( length ); + } - } + if ( ! isRootObject ) { - lerp( v, alpha ) { + meta.images[ this.uuid ] = output; - 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 this; + return output; } - lerpVectors( v1, v2, alpha ) { +} - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; - this.w = v1.w + ( v2.w - v1.w ) * alpha; +function serializeImage( image ) { - return this; + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - } + // default images - equals( v ) { + return ImageUtils.getDataURL( image ); - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + } else { - } + if ( image.data ) { - fromArray( array, offset = 0 ) { + // images of DataTexture - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + return { + data: Array.from( image.data ), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; - return this; + } else { + + console.warn( 'THREE.Texture: Unable to serialize Texture.' ); + return {}; + + } } - toArray( array = [], offset = 0 ) { +} - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; +let textureId = 0; - return array; +class Texture extends EventDispatcher { - } + constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) { - fromBufferAttribute( attribute, index, offset ) { + super(); - if ( offset !== undefined ) { + this.isTexture = true; - console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); + Object.defineProperty( this, 'id', { value: textureId ++ } ); - } + this.uuid = generateUUID(); - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - this.w = attribute.getW( index ); + this.name = ''; - return this; + this.source = new Source( image ); + this.mipmaps = []; - } + this.mapping = mapping; - random() { + this.wrapS = wrapS; + this.wrapT = wrapT; - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); - this.w = Math.random(); + this.magFilter = magFilter; + this.minFilter = minFilter; - return this; + this.anisotropy = anisotropy; - } + this.format = format; + this.internalFormat = null; + this.type = type; -} + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); + this.rotation = 0; -Vector4.prototype.isVector4 = true; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); -/* - In options, we can specify: - * Texture parameters for an auto-generated target texture - * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers -*/ -class WebGLRenderTarget extends EventDispatcher { + 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) - constructor( width, height, options ) { + // 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; - super(); + this.userData = {}; - this.width = width; - this.height = height; - this.depth = 1; + this.version = 0; + this.onUpdate = null; - this.scissor = new Vector4( 0, 0, width, height ); - this.scissorTest = false; + this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not + this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures) - this.viewport = new Vector4( 0, 0, width, height ); + } - options = options || {}; + get image() { - this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + return this.source.data; - this.texture.image = {}; - this.texture.image.width = width; - this.texture.image.height = height; - this.texture.image.depth = 1; + } - this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; - this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + set image( value ) { - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; - this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + this.source.data = value; } - setTexture( texture ) { - - texture.image = { - width: this.width, - height: this.height, - depth: this.depth - }; + updateMatrix() { - this.texture = texture; + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); } - setSize( width, height, depth = 1 ) { + clone() { - if ( this.width !== width || this.height !== height || this.depth !== depth ) { + return new this.constructor().copy( this ); - this.width = width; - this.height = height; - this.depth = depth; + } - this.texture.image.width = width; - this.texture.image.height = height; - this.texture.image.depth = depth; + copy( source ) { - this.dispose(); + this.name = source.name; - } + this.source = source.source; + this.mipmaps = source.mipmaps.slice( 0 ); - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); + this.mapping = source.mapping; - } + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - clone() { + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - return new this.constructor().copy( this ); + this.anisotropy = source.anisotropy; - } + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; - copy( source ) { + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; - this.width = source.width; - this.height = source.height; - this.depth = source.depth; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); - this.viewport.copy( source.viewport ); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - this.texture = source.texture.clone(); + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + this.needsUpdate = true; return this; } - dispose() { + toJSON( meta ) { - this.dispatchEvent( { type: 'dispose' } ); + const isRootObject = ( meta === undefined || typeof meta === 'string' ); - } + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { -} + return meta.textures[ this.uuid ]; -WebGLRenderTarget.prototype.isWebGLRenderTarget = true; + } -class WebGLMultisampleRenderTarget extends WebGLRenderTarget { + const output = { - constructor( width, height, options ) { + metadata: { + version: 4.5, + type: 'Texture', + generator: 'Texture.toJSON' + }, - super( width, height, options ); + uuid: this.uuid, + name: this.name, - this.samples = 4; + image: this.source.toJSON( meta ).uuid, - } + mapping: this.mapping, - copy( source ) { + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, - super.copy.call( this, source ); + wrap: [ this.wrapS, this.wrapT ], - this.samples = source.samples; + format: this.format, + type: this.type, + encoding: this.encoding, - return this; + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - } + flipY: this.flipY, -} + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment -WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true; + }; -class Quaternion { + if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData; - constructor( x = 0, y = 0, z = 0, w = 1 ) { + if ( ! isRootObject ) { - this._x = x; - this._y = y; - this._z = z; - this._w = w; + meta.textures[ this.uuid ] = output; + + } + + return output; } - static slerp( qa, qb, qm, t ) { + dispose() { - return qm.copy( qa ).slerp( qb, t ); + this.dispatchEvent( { type: 'dispose' } ); } - static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + transformUv( uv ) { - // fuzz-free, array-based Quaternion SLERP operation + if ( this.mapping !== UVMapping ) return uv; - let x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ]; + uv.applyMatrix3( this.matrix ); - const x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; + if ( uv.x < 0 || uv.x > 1 ) { - if ( t === 0 ) { + switch ( this.wrapS ) { - dst[ dstOffset + 0 ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; - return; + case RepeatWrapping: - } + uv.x = uv.x - Math.floor( uv.x ); + break; - if ( t === 1 ) { + case ClampToEdgeWrapping: - dst[ dstOffset + 0 ] = x1; - dst[ dstOffset + 1 ] = y1; - dst[ dstOffset + 2 ] = z1; - dst[ dstOffset + 3 ] = w1; - return; + uv.x = uv.x < 0 ? 0 : 1; + break; - } + case MirroredRepeatWrapping: - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - let s = 1 - t; - const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; + uv.x = Math.ceil( uv.x ) - uv.x; - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { + } else { - const sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); + uv.x = uv.x - Math.floor( uv.x ); - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; + } + + break; } - const tDir = t * dir; + } - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; + if ( uv.y < 0 || uv.y > 1 ) { - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { + switch ( this.wrapT ) { - const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + case RepeatWrapping: - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; + uv.y = uv.y - Math.floor( uv.y ); + break; - } + case ClampToEdgeWrapping: - } + uv.y = uv.y < 0 ? 0 : 1; + break; - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; + case MirroredRepeatWrapping: - } + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { + uv.y = Math.ceil( uv.y ) - uv.y; - const x0 = src0[ srcOffset0 ]; - const y0 = src0[ srcOffset0 + 1 ]; - const z0 = src0[ srcOffset0 + 2 ]; - const w0 = src0[ srcOffset0 + 3 ]; + } else { - const x1 = src1[ srcOffset1 ]; - const y1 = src1[ srcOffset1 + 1 ]; - const z1 = src1[ srcOffset1 + 2 ]; - const w1 = src1[ srcOffset1 + 3 ]; + uv.y = uv.y - Math.floor( uv.y ); - dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; - dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; - dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; - dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + } - return dst; + break; - } + } - get x() { + } - return this._x; + if ( this.flipY ) { - } + uv.y = 1 - uv.y; - set x( value ) { + } - this._x = value; - this._onChangeCallback(); + return uv; } - get y() { + set needsUpdate( value ) { - return this._y; + if ( value === true ) { + + this.version ++; + this.source.needsUpdate = true; + + } } - set y( value ) { +} - this._y = value; - this._onChangeCallback(); +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; + +class Vector4 { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + Vector4.prototype.isVector4 = true; + + this.x = x; + this.y = y; + this.z = z; + this.w = w; } - get z() { + get width() { - return this._z; + return this.z; } - set z( value ) { + set width( value ) { - this._z = value; - this._onChangeCallback(); + this.z = value; } - get w() { + get height() { - return this._w; + return this.w; } - set w( value ) { + set height( value ) { - this._w = value; - this._onChangeCallback(); + this.w = value; } set( x, y, z, w ) { - this._x = x; - this._y = y; - this._z = z; - this._w = w; - - this._onChangeCallback(); + this.x = x; + this.y = y; + this.z = z; + this.w = w; return this; } - clone() { + setScalar( scalar ) { - return new this.constructor( this._x, this._y, this._z, this._w ); + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - } + return this; - copy( quaternion ) { + } - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + setX( x ) { - this._onChangeCallback(); + this.x = x; return this; } - setFromEuler( euler, update ) { - - if ( ! ( euler && euler.isEuler ) ) { - - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + setY( y ) { - } + this.y = y; - const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + return this; - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + } - const cos = Math.cos; - const sin = Math.sin; + setZ( z ) { - const c1 = cos( x / 2 ); - const c2 = cos( y / 2 ); - const c3 = cos( z / 2 ); + this.z = z; - const s1 = sin( x / 2 ); - const s2 = sin( y / 2 ); - const s3 = sin( z / 2 ); + return this; - switch ( order ) { + } - case '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; - break; + setW( w ) { - case 'YXZ': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; - break; + this.w = w; - case 'ZXY': - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; + return this; - case '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; - break; + } - case 'YZX': - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; - break; + setComponent( index, value ) { - case 'XZY': - 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; - break; + switch ( index ) { - default: - console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); + 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 ( update !== false ) this._onChangeCallback(); - return this; } - setFromAxisAngle( axis, angle ) { + getComponent( index ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + switch ( index ) { - // assumes axis is normalized + 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 ); - const halfAngle = angle / 2, s = Math.sin( halfAngle ); + } - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + } - this._onChangeCallback(); + clone() { - return this; + return new this.constructor( this.x, this.y, this.z, this.w ); } - setFromRotationMatrix( m ) { + copy( v ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + return this; - const 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 ], + add( v ) { - trace = m11 + m22 + m33; + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - if ( trace > 0 ) { + return this; - const 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; - - } else if ( m11 > m22 && m11 > m33 ) { - - const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; - - } else if ( m22 > m33 ) { - - const 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 { - - const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; - - } + addScalar( s ) { - this._onChangeCallback(); + this.x += s; + this.y += s; + this.z += s; + this.w += s; return this; } - setFromUnitVectors( vFrom, vTo ) { - - // assumes direction vectors vFrom and vTo are normalized - - const EPS = 0.000001; - - let r = vFrom.dot( vTo ) + 1; - - if ( r < EPS ) { - - r = 0; + addVectors( a, b ) { - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.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; - this._x = - vFrom.y; - this._y = vFrom.x; - this._z = 0; - this._w = r; + return this; - } else { + } - this._x = 0; - this._y = - vFrom.z; - this._z = vFrom.y; - this._w = r; + addScaledVector( v, s ) { - } + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - } else { + return this; - // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 + } - this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; - this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; - this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; - this._w = r; + sub( v ) { - } + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - return this.normalize(); + return this; } - angleTo( q ) { - - return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) ); - - } + subScalar( s ) { - rotateTowards( q, step ) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - const angle = this.angleTo( q ); + return this; - if ( angle === 0 ) return this; + } - const t = Math.min( 1, step / angle ); + subVectors( a, b ) { - this.slerp( q, t ); + 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; } - identity() { + multiply( v ) { - return this.set( 0, 0, 0, 1 ); + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + + return this; } - invert() { + multiplyScalar( scalar ) { - // quaternion is assumed to have unit length + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - return this.conjugate(); + return this; } - conjugate() { + applyMatrix4( m ) { - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; - this._onChangeCallback(); + 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; return this; } - dot( v ) { - - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - - } - - lengthSq() { + divideScalar( scalar ) { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + return this.multiplyScalar( 1 / scalar ); } - length() { + setAxisAngleFromQuaternion( q ) { - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - } + // q is assumed to be normalized - normalize() { + this.w = 2 * Math.acos( q.w ); - let l = this.length(); + const s = Math.sqrt( 1 - q.w * q.w ); - if ( l === 0 ) { + if ( s < 0.0001 ) { - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + this.x = 1; + this.y = 0; + this.z = 0; } else { - l = 1 / l; - - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; } - this._onChangeCallback(); - return this; } - multiply( q, p ) { - - if ( p !== undefined ) { - - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + setAxisAngleFromRotationMatrix( m ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - return this.multiplyQuaternions( this, q ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - } + let angle, x, y, z; // variables for result + const epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - premultiply( q ) { + te = m.elements, - return this.multiplyQuaternions( q, this ); + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - } + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - multiplyQuaternions( a, b ) { + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + // this singularity is identity matrix so angle = 0 - 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.set( 1, 0, 0, 0 ); - this._onChangeCallback(); + return this; // zero angle, arbitrary axis - return this; + } - } + // otherwise this singularity is angle = 180 - slerp( qb, t ) { + angle = Math.PI; - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); + const xx = ( m11 + 1 ) / 2; + const yy = ( m22 + 1 ) / 2; + const zz = ( m33 + 1 ) / 2; + const xy = ( m12 + m21 ) / 4; + const xz = ( m13 + m31 ) / 4; + const yz = ( m23 + m32 ) / 4; - const x = this._x, y = this._y, z = this._z, w = this._w; + if ( ( xx > yy ) && ( xx > zz ) ) { - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + // m11 is the largest diagonal term - let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if ( xx < epsilon ) { - if ( cosHalfTheta < 0 ) { + x = 0; + y = 0.707106781; + z = 0.707106781; - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + } else { - cosHalfTheta = - cosHalfTheta; + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - } else { + } - this.copy( qb ); + } else if ( yy > zz ) { - } + // m22 is the largest diagonal term - if ( cosHalfTheta >= 1.0 ) { + if ( yy < epsilon ) { - this._w = w; - this._x = x; - this._y = y; - this._z = z; + x = 0.707106781; + y = 0; + z = 0.707106781; - return this; + } else { - } + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; + } - if ( sqrSinHalfTheta <= Number.EPSILON ) { + } else { - const s = 1 - t; - this._w = s * w + t * this._w; - this._x = s * x + t * this._x; - this._y = s * y + t * this._y; - this._z = s * z + t * this._z; + // m33 is the largest diagonal term so base result on this - this.normalize(); - this._onChangeCallback(); + if ( zz < epsilon ) { - return this; + x = 0.707106781; + y = 0.707106781; + z = 0; - } + } else { - const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); - const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - 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(); + } - return this; + this.set( x, y, z, angle ); - } + return this; // return 180 deg rotation - equals( quaternion ) { + } - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + // as we have reached here there are no singularities so we can handle normally - } + let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - fromArray( array, offset = 0 ) { + if ( Math.abs( s ) < 0.001 ) s = 1; - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + // 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 - this._onChangeCallback(); + 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; } - toArray( array = [], offset = 0 ) { + min( v ) { - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + 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 array; + return this; } - fromBufferAttribute( attribute, index ) { + max( v ) { - this._x = attribute.getX( index ); - this._y = attribute.getY( index ); - this._z = attribute.getZ( index ); - this._w = attribute.getW( index ); + 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 ); return this; } - _onChange( callback ) { + clamp( min, max ) { - this._onChangeCallback = callback; + // assumes min < max, componentwise + + 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; } - _onChangeCallback() {} + clampScalar( minVal, maxVal ) { -} + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); -Quaternion.prototype.isQuaternion = true; + return this; -class Vector3 { + } - constructor( x = 0, y = 0, z = 0 ) { + clampLength( min, max ) { - this.x = x; - this.y = y; - this.z = z; + const length = this.length(); - } + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - set( x, y, z ) { + } - if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) + floor() { - this.x = x; - this.y = y; - this.z = z; + 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; } - setScalar( scalar ) { + ceil() { - this.x = scalar; - this.y = scalar; - this.z = scalar; + 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; } - setX( x ) { + round() { - this.x = x; + 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; } - setY( y ) { + roundToZero() { - this.y = y; + 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; } - setZ( z ) { + negate() { - this.z = z; + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; return this; } - setComponent( index, value ) { + dot( v ) { - switch ( index ) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - 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 ); + } - } + lengthSq() { - return this; + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; } - getComponent( 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 ); + length() { - } + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); } - clone() { + manhattanLength() { - return new this.constructor( this.x, this.y, this.z ); + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); } - copy( v ) { - - this.x = v.x; - this.y = v.y; - this.z = v.z; + normalize() { - return this; + return this.divideScalar( this.length() || 1 ); } - add( v, w ) { + setLength( length ) { - if ( w !== undefined ) { + return this.normalize().multiplyScalar( length ); - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + } - } + lerp( v, alpha ) { - this.x += v.x; - this.y += v.y; - this.z += v.z; + 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 this; } - addScalar( s ) { + lerpVectors( v1, v2, alpha ) { - this.x += s; - this.y += s; - this.z += s; + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; return this; } - addVectors( a, b ) { - - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + equals( v ) { - return this; + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); } - addScaledVector( v, s ) { + fromArray( array, offset = 0 ) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; return this; } - sub( v, w ) { + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - if ( w !== undefined ) { + return array; - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + } - } + fromBufferAttribute( attribute, index ) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); return this; } - subScalar( s ) { + random() { - this.x -= s; - this.y -= s; - this.z -= s; + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); return this; } - subVectors( a, b ) { - - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + *[ Symbol.iterator ]() { - return this; + yield this.x; + yield this.y; + yield this.z; + yield this.w; } - multiply( v, w ) { +} - if ( w !== undefined ) { +/* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers +*/ +class WebGLRenderTarget extends EventDispatcher { - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + constructor( width, height, options = {} ) { - } + super(); - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + this.isWebGLRenderTarget = true; - return this; + this.width = width; + this.height = height; + this.depth = 1; - } + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - multiplyScalar( scalar ) { + this.viewport = new Vector4( 0, 0, width, height ); - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + const image = { width: width, height: height, depth: 1 }; - return this; + this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture.isRenderTargetTexture = true; - } + this.texture.flipY = false; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; - multiplyVectors( a, b ) { + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; - return this; + this.samples = options.samples !== undefined ? options.samples : 0; } - applyEuler( euler ) { + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; - if ( ! ( euler && euler.isEuler ) ) { + this.texture.image.width = width; + this.texture.image.height = height; + this.texture.image.depth = depth; - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + this.dispose(); } - return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); } - applyAxisAngle( axis, angle ) { + clone() { - return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); + return new this.constructor().copy( this ); } - applyMatrix3( m ) { + copy( source ) { - const x = this.x, y = this.y, z = this.z; - const e = m.elements; + this.width = source.width; + this.height = source.height; + this.depth = source.depth; - 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; + this.viewport.copy( source.viewport ); - return this; + this.texture = source.texture.clone(); + this.texture.isRenderTargetTexture = true; - } + // ensure image object is not shared, see #20328 - applyNormalMatrix( m ) { + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); - return this.applyMatrix3( m ).normalize(); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; - } + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); - applyMatrix4( m ) { + this.samples = source.samples; - const x = this.x, y = this.y, z = this.z; - const e = m.elements; + return this; - const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + } - 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; + dispose() { - return this; + this.dispatchEvent( { type: 'dispose' } ); } - applyQuaternion( q ) { - - const x = this.x, y = this.y, z = this.z; - const qx = q.x, qy = q.y, qz = q.z, qw = q.w; +} - // calculate quat * vector +class DataArrayTexture extends Texture { - const ix = qw * x + qy * z - qz * y; - const iy = qw * y + qz * x - qx * z; - const iz = qw * z + qx * y - qy * x; - const iw = - qx * x - qy * y - qz * z; + constructor( data = null, width = 1, height = 1, depth = 1 ) { - // calculate result * inverse quat + super( null ); - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; + this.isDataArrayTexture = true; - return this; + this.image = { data, width, height, depth }; - } + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; - project( camera ) { + this.wrapR = ClampToEdgeWrapping; - return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; } - unproject( camera ) { +} - return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); +class WebGLArrayRenderTarget extends WebGLRenderTarget { - } + constructor( width, height, depth ) { - transformDirection( m ) { + super( width, height ); - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + this.isWebGLArrayRenderTarget = true; - const x = this.x, y = this.y, z = this.z; - const e = m.elements; + this.depth = depth; - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + this.texture = new DataArrayTexture( null, width, height, depth ); - return this.normalize(); + this.texture.isRenderTargetTexture = true; } - divide( v ) { +} - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; +class Data3DTexture extends Texture { - return this; + constructor( data = null, width = 1, height = 1, depth = 1 ) { - } + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in DataTexture3D directly. + // + // const texture = new THREE.DataTexture3D( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 - divideScalar( scalar ) { + super( null ); - return this.multiplyScalar( 1 / scalar ); + this.isData3DTexture = true; - } + this.image = { data, width, height, depth }; - min( v ) { + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; - 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.wrapR = ClampToEdgeWrapping; - return this; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; } - max( v ) { +} - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); +class WebGL3DRenderTarget extends WebGLRenderTarget { - return this; + constructor( width, height, depth ) { - } + super( width, height ); - clamp( min, max ) { + this.isWebGL3DRenderTarget = true; - // assumes min < max, componentwise + this.depth = depth; - 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.texture = new Data3DTexture( null, width, height, depth ); - return this; + this.texture.isRenderTargetTexture = true; } - clampScalar( minVal, maxVal ) { - - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); +} - return this; +class WebGLMultipleRenderTargets extends WebGLRenderTarget { - } + constructor( width, height, count, options = {} ) { - clampLength( min, max ) { + super( width, height, options ); - const length = this.length(); + this.isWebGLMultipleRenderTargets = true; - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + const texture = this.texture; - } + this.texture = []; - floor() { + for ( let i = 0; i < count; i ++ ) { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + this.texture[ i ] = texture.clone(); + this.texture[ i ].isRenderTargetTexture = true; - return this; + } } - ceil() { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + setSize( width, height, depth = 1 ) { - return this; + if ( this.width !== width || this.height !== height || this.depth !== depth ) { - } + this.width = width; + this.height = height; + this.depth = depth; - round() { + for ( let i = 0, il = this.texture.length; i < il; i ++ ) { - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + this.texture[ i ].image.width = width; + this.texture[ i ].image.height = height; + this.texture[ i ].image.depth = depth; - return this; + } - } + this.dispose(); - roundToZero() { + } - 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.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); return this; } - negate() { + copy( source ) { - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + this.dispose(); - return this; + this.width = source.width; + this.height = source.height; + this.depth = source.depth; - } + this.viewport.set( 0, 0, this.width, this.height ); + this.scissor.set( 0, 0, this.width, this.height ); - dot( v ) { + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; - return this.x * v.x + this.y * v.y + this.z * v.z; + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); - } + this.texture.length = 0; - // TODO lengthSquared? + for ( let i = 0, il = source.texture.length; i < il; i ++ ) { - lengthSq() { + this.texture[ i ] = source.texture[ i ].clone(); + this.texture[ i ].isRenderTargetTexture = true; - return this.x * this.x + this.y * this.y + this.z * this.z; + } + + return this; } - length() { +} - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); +class Quaternion { - } + constructor( x = 0, y = 0, z = 0, w = 1 ) { - manhattanLength() { + this.isQuaternion = true; - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + this._x = x; + this._y = y; + this._z = z; + this._w = w; } - normalize() { + static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - return this.divideScalar( this.length() || 1 ); + // fuzz-free, array-based Quaternion SLERP operation - } + let x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ]; - setLength( length ) { + const x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - return this.normalize().multiplyScalar( length ); + if ( t === 0 ) { - } + dst[ dstOffset + 0 ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + return; - lerp( v, alpha ) { + } - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + if ( t === 1 ) { - return this; + dst[ dstOffset + 0 ] = x1; + dst[ dstOffset + 1 ] = y1; + dst[ dstOffset + 2 ] = z1; + dst[ dstOffset + 3 ] = w1; + return; - } + } - lerpVectors( v1, v2, alpha ) { + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - this.x = v1.x + ( v2.x - v1.x ) * alpha; - this.y = v1.y + ( v2.y - v1.y ) * alpha; - this.z = v1.z + ( v2.z - v1.z ) * alpha; + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - return this; + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - } + const sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - cross( v, w ) { + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - if ( w !== undefined ) { + } - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + const tDir = t * dir; - } + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - return this.crossVectors( this, v ); + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { - } + const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - crossVectors( a, b ) { + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; - const ax = a.x, ay = a.y, az = a.z; - const bx = b.x, by = b.y, bz = b.z; + } - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + } - return this; + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; } - projectOnVector( v ) { + static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { - const denominator = v.lengthSq(); + const x0 = src0[ srcOffset0 ]; + const y0 = src0[ srcOffset0 + 1 ]; + const z0 = src0[ srcOffset0 + 2 ]; + const w0 = src0[ srcOffset0 + 3 ]; - if ( denominator === 0 ) return this.set( 0, 0, 0 ); + const x1 = src1[ srcOffset1 ]; + const y1 = src1[ srcOffset1 + 1 ]; + const z1 = src1[ srcOffset1 + 2 ]; + const w1 = src1[ srcOffset1 + 3 ]; - const scalar = v.dot( this ) / denominator; + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; - return this.copy( v ).multiplyScalar( scalar ); + return dst; } - projectOnPlane( planeNormal ) { - - _vector.copy( this ).projectOnVector( planeNormal ); + get x() { - return this.sub( _vector ); + return this._x; } - reflect( normal ) { - - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + set x( value ) { - return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + this._x = value; + this._onChangeCallback(); } - angleTo( v ) { - - const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + get y() { - if ( denominator === 0 ) return Math.PI / 2; + return this._y; - const theta = this.dot( v ) / denominator; + } - // clamp, to handle numerical problems + set y( value ) { - return Math.acos( MathUtils.clamp( theta, - 1, 1 ) ); + this._y = value; + this._onChangeCallback(); } - distanceTo( v ) { + get z() { - return Math.sqrt( this.distanceToSquared( v ) ); + return this._z; } - distanceToSquared( v ) { - - const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + set z( value ) { - return dx * dx + dy * dy + dz * dz; + this._z = value; + this._onChangeCallback(); } - manhattanDistanceTo( v ) { + get w() { - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + return this._w; } - setFromSpherical( s ) { + set w( value ) { - return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + this._w = value; + this._onChangeCallback(); } - setFromSphericalCoords( radius, phi, theta ) { + set( x, y, z, w ) { - const sinPhiRadius = Math.sin( phi ) * radius; + this._x = x; + this._y = y; + this._z = z; + this._w = w; - this.x = sinPhiRadius * Math.sin( theta ); - this.y = Math.cos( phi ) * radius; - this.z = sinPhiRadius * Math.cos( theta ); + this._onChangeCallback(); return this; } - setFromCylindrical( c ) { + clone() { - return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + return new this.constructor( this._x, this._y, this._z, this._w ); } - setFromCylindricalCoords( radius, theta, y ) { + copy( quaternion ) { - this.x = radius * Math.sin( theta ); - this.y = y; - this.z = radius * Math.cos( theta ); + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + + this._onChangeCallback(); return this; } - setFromMatrixPosition( m ) { - - const e = m.elements; + setFromEuler( euler, update ) { - this.x = e[ 12 ]; - this.y = e[ 13 ]; - this.z = e[ 14 ]; + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; - return this; + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - } + const cos = Math.cos; + const sin = Math.sin; - setFromMatrixScale( m ) { + const c1 = cos( x / 2 ); + const c2 = cos( y / 2 ); + const c3 = cos( z / 2 ); - const sx = this.setFromMatrixColumn( m, 0 ).length(); - const sy = this.setFromMatrixColumn( m, 1 ).length(); - const sz = this.setFromMatrixColumn( m, 2 ).length(); + const s1 = sin( x / 2 ); + const s2 = sin( y / 2 ); + const s3 = sin( z / 2 ); - this.x = sx; - this.y = sy; - this.z = sz; + switch ( order ) { - return this; + case '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; + break; - } + case 'YXZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; - setFromMatrixColumn( m, index ) { + case 'ZXY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; - return this.fromArray( m.elements, index * 4 ); + case '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; + break; - } + case 'YZX': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; - setFromMatrix3Column( m, index ) { + case 'XZY': + 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; + break; - return this.fromArray( m.elements, index * 3 ); + default: + console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); - } + } - equals( v ) { + if ( update !== false ) this._onChangeCallback(); - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + return this; } - fromArray( array, offset = 0 ) { + setFromAxisAngle( axis, angle ) { - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - return this; + // assumes axis is normalized - } + const halfAngle = angle / 2, s = Math.sin( halfAngle ); - toArray( array = [], offset = 0 ) { + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + this._onChangeCallback(); - return array; + return this; } - fromBufferAttribute( attribute, index, offset ) { + setFromRotationMatrix( m ) { - if ( offset !== undefined ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - } + const te = m.elements, - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); + 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 ], - return this; + trace = m11 + m22 + m33; - } + if ( trace > 0 ) { - random() { + const s = 0.5 / Math.sqrt( trace + 1.0 ); - this.x = Math.random(); - this.y = Math.random(); - this.z = Math.random(); + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - return this; + } else if ( m11 > m22 && m11 > m33 ) { - } + const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); -} + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; -Vector3.prototype.isVector3 = true; + } else if ( m22 > m33 ) { -const _vector = /*@__PURE__*/ new Vector3(); -const _quaternion = /*@__PURE__*/ new Quaternion(); + const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); -class Box3 { + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + } else { - this.min = min; - this.max = max; + const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - } + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - set( min, max ) { + } - this.min.copy( min ); - this.max.copy( max ); + this._onChangeCallback(); return this; } - setFromArray( array ) { - - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; - - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; + setFromUnitVectors( vFrom, vTo ) { - for ( let i = 0, l = array.length; i < l; i += 3 ) { + // assumes direction vectors vFrom and vTo are normalized - const x = array[ i ]; - const y = array[ i + 1 ]; - const z = array[ i + 2 ]; + let r = vFrom.dot( vTo ) + 1; - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + if ( r < Number.EPSILON ) { - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + // vFrom and vTo point in opposite directions - } + r = 0; - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - return this; + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; - } + } else { - setFromBufferAttribute( attribute ) { + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; - let minX = + Infinity; - let minY = + Infinity; - let minZ = + Infinity; + } - let maxX = - Infinity; - let maxY = - Infinity; - let maxZ = - Infinity; + } else { - for ( let i = 0, l = attribute.count; i < l; i ++ ) { + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 - const x = attribute.getX( i ); - const y = attribute.getY( i ); - const z = attribute.getZ( i ); + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + } - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + return this.normalize(); - } + } - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + angleTo( q ) { - return this; + return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) ); } - setFromPoints( points ) { + rotateTowards( q, step ) { - this.makeEmpty(); + const angle = this.angleTo( q ); - for ( let i = 0, il = points.length; i < il; i ++ ) { + if ( angle === 0 ) return this; - this.expandByPoint( points[ i ] ); + const t = Math.min( 1, step / angle ); - } + this.slerp( q, t ); return this; } - setFromCenterAndSize( center, size ) { + identity() { + + return this.set( 0, 0, 0, 1 ); - const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 ); + } - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + invert() { - return this; + // quaternion is assumed to have unit length + + return this.conjugate(); } - setFromObject( object ) { + conjugate() { - this.makeEmpty(); + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; + + this._onChangeCallback(); - return this.expandByObject( object ); + return this; } - clone() { + dot( v ) { - return new this.constructor().copy( this ); + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; } - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); + lengthSq() { - return this; + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; } - makeEmpty() { - - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + length() { - return this; + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); } - isEmpty() { + normalize() { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + let l = this.length(); - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + if ( l === 0 ) { - } + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - getCenter( target ) { + } else { - if ( target === undefined ) { + l = 1 / l; - console.warn( 'THREE.Box3: .getCenter() target is now required' ); - target = new Vector3(); + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; } - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + this._onChangeCallback(); + + return this; } - getSize( target ) { + multiply( q ) { - if ( target === undefined ) { + return this.multiplyQuaternions( this, q ); - console.warn( 'THREE.Box3: .getSize() target is now required' ); - target = new Vector3(); + } - } + premultiply( q ) { - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + return this.multiplyQuaternions( q, this ); } - expandByPoint( point ) { - - this.min.min( point ); - this.max.max( point ); + multiplyQuaternions( a, b ) { - return this; + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - } + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - expandByVector( vector ) { + 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.min.sub( vector ); - this.max.add( vector ); + this._onChangeCallback(); return this; } - expandByScalar( scalar ) { + slerp( qb, t ) { - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - return this; + const x = this._x, y = this._y, z = this._z, w = this._w; - } + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - expandByObject( object ) { + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + if ( cosHalfTheta < 0 ) { - object.updateWorldMatrix( false, false ); + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - const geometry = object.geometry; + cosHalfTheta = - cosHalfTheta; - if ( geometry !== undefined ) { + } else { - if ( geometry.boundingBox === null ) { + this.copy( qb ); - geometry.computeBoundingBox(); + } - } + if ( cosHalfTheta >= 1.0 ) { - _box.copy( geometry.boundingBox ); - _box.applyMatrix4( object.matrixWorld ); + this._w = w; + this._x = x; + this._y = y; + this._z = z; - this.union( _box ); + return this; } - const children = object.children; + const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; - for ( let i = 0, l = children.length; i < l; i ++ ) { + if ( sqrSinHalfTheta <= Number.EPSILON ) { + + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + + this.normalize(); + this._onChangeCallback(); - this.expandByObject( children[ i ] ); + return this; } - return this; + const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); + const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - } + 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 ); - containsPoint( point ) { + this._onChangeCallback(); - return 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 ? false : true; + return this; } - containsBox( box ) { + slerpQuaternions( qa, qb, t ) { - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y && - this.min.z <= box.min.z && box.max.z <= this.max.z; + return this.copy( qa ).slerp( qb, t ); } - getParameter( point, target ) { + random() { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + // Derived from http://planning.cs.uiuc.edu/node198.html + // Note, this source uses w, x, y, z ordering, + // so we swap the order below. - if ( target === undefined ) { + const u1 = Math.random(); + const sqrt1u1 = Math.sqrt( 1 - u1 ); + const sqrtu1 = Math.sqrt( u1 ); - console.warn( 'THREE.Box3: .getParameter() target is now required' ); - target = new Vector3(); + const u2 = 2 * Math.PI * Math.random(); - } + const u3 = 2 * Math.PI * Math.random(); - return target.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.set( + sqrt1u1 * Math.cos( u2 ), + sqrtu1 * Math.sin( u3 ), + sqrtu1 * Math.cos( u3 ), + sqrt1u1 * Math.sin( u2 ), ); } - intersectsBox( box ) { + equals( quaternion ) { - // using 6 splitting planes to rule out intersections. - return 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 ? false : true; + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); } - intersectsSphere( sphere ) { + fromArray( array, offset = 0 ) { - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, _vector$1 ); + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - // If that point is inside the sphere, the AABB and sphere intersect. - return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + this._onChangeCallback(); + + return this; } - intersectsPlane( plane ) { + toArray( array = [], offset = 0 ) { - // 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. + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - let min, max; + return array; - if ( plane.normal.x > 0 ) { + } - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + fromBufferAttribute( attribute, index ) { - } else { + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + return this; - } + } - if ( plane.normal.y > 0 ) { + _onChange( callback ) { - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; + this._onChangeCallback = callback; - } else { + return this; - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; + } - } + _onChangeCallback() {} - if ( plane.normal.z > 0 ) { + *[ Symbol.iterator ]() { - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + yield this._x; + yield this._y; + yield this._z; + yield this._w; - } else { + } - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; +} - } +class Vector3 { - return ( min <= - plane.constant && max >= - plane.constant ); + constructor( x = 0, y = 0, z = 0 ) { + + Vector3.prototype.isVector3 = true; + + this.x = x; + this.y = y; + this.z = z; } - intersectsTriangle( triangle ) { + set( x, y, z ) { - if ( this.isEmpty() ) { + if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) - return false; + this.x = x; + this.y = y; + this.z = z; - } + return this; - // compute box center and extents - this.getCenter( _center ); - _extents.subVectors( this.max, _center ); + } - // translate triangle to aabb origin - _v0.subVectors( triangle.a, _center ); - _v1.subVectors( triangle.b, _center ); - _v2.subVectors( triangle.c, _center ); + setScalar( scalar ) { - // compute edge vectors for triangle - _f0.subVectors( _v1, _v0 ); - _f1.subVectors( _v2, _v1 ); - _f2.subVectors( _v0, _v2 ); + this.x = scalar; + this.y = scalar; + this.z = scalar; - // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb - // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation - // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) - let axes = [ - 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, - _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, - - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 - ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { + return this; - return false; + } - } + setX( x ) { - // test 3 face normals from the aabb - axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) { + this.x = x; - return false; + return this; - } + } - // finally testing the face normal of the triangle - // use already existing triangle edge vectors here - _triangleNormal.crossVectors( _f0, _f1 ); - axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + setY( y ) { + + this.y = y; - return satForAxes( axes, _v0, _v1, _v2, _extents ); + return this; } - clampPoint( point, target ) { + setZ( z ) { - if ( target === undefined ) { + this.z = z; - console.warn( 'THREE.Box3: .clampPoint() target is now required' ); - target = new Vector3(); + return this; - } + } - return target.copy( point ).clamp( this.min, this.max ); + setComponent( index, value ) { - } + switch ( index ) { - distanceToPoint( point ) { + 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 ); - const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max ); + } - return clampedPoint.sub( point ).length(); + return this; } - getBoundingSphere( target ) { + getComponent( index ) { - if ( target === undefined ) { + switch ( index ) { - console.error( 'THREE.Box3: .getBoundingSphere() target is now required' ); - //target = new Sphere(); // removed to avoid cyclic dependency + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'index is out of range: ' + index ); } - this.getCenter( target.center ); + } - target.radius = this.getSize( _vector$1 ).length() * 0.5; + clone() { - return target; + return new this.constructor( this.x, this.y, this.z ); } - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); + copy( v ) { - // 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(); + this.x = v.x; + this.y = v.y; + this.z = v.z; return this; } - union( box ) { + add( v ) { - this.min.min( box.min ); - this.max.max( box.max ); + this.x += v.x; + this.y += v.y; + this.z += v.z; return this; } - applyMatrix4( matrix ) { - - // 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 + addScalar( s ) { - this.setFromPoints( _points ); + this.x += s; + this.y += s; + this.z += s; return this; } - translate( offset ) { + addVectors( a, b ) { - this.min.add( offset ); - this.max.add( offset ); + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; return this; } - equals( box ) { + addScaledVector( v, s ) { - return box.min.equals( this.min ) && box.max.equals( this.max ); + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + + return this; } -} + sub( v ) { -Box3.prototype.isBox3 = true; + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; -const _points = [ - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3(), - /*@__PURE__*/ new Vector3() -]; + return this; -const _vector$1 = /*@__PURE__*/ new Vector3(); + } -const _box = /*@__PURE__*/ new Box3(); + subScalar( s ) { -// triangle centered vertices + this.x -= s; + this.y -= s; + this.z -= s; -const _v0 = /*@__PURE__*/ new Vector3(); -const _v1 = /*@__PURE__*/ new Vector3(); -const _v2 = /*@__PURE__*/ new Vector3(); + return this; -// triangle edge vectors + } -const _f0 = /*@__PURE__*/ new Vector3(); -const _f1 = /*@__PURE__*/ new Vector3(); -const _f2 = /*@__PURE__*/ new Vector3(); + subVectors( a, b ) { -const _center = /*@__PURE__*/ new Vector3(); -const _extents = /*@__PURE__*/ new Vector3(); -const _triangleNormal = /*@__PURE__*/ new Vector3(); -const _testAxis = /*@__PURE__*/ new Vector3(); + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; -function satForAxes( axes, v0, v1, v2, extents ) { + return this; - for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { + } - _testAxis.fromArray( axes, i ); - // project the aabb onto the seperating axis - const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); - // project all 3 vertices of the triangle onto the seperating axis - const p0 = v0.dot( _testAxis ); - const p1 = v1.dot( _testAxis ); - const p2 = v2.dot( _testAxis ); - // actual test, basically see if either of the most extreme of the triangle points intersects r - if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + multiply( v ) { - // points of the projected triangle are outside the projected half-length of the aabb - // the axis is seperating and we can exit - return false; + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - } + return this; } - return true; - -} - -const _box$1 = /*@__PURE__*/ new Box3(); - -class Sphere { + multiplyScalar( scalar ) { - constructor( center = new Vector3(), radius = - 1 ) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - this.center = center; - this.radius = radius; + return this; } - set( center, radius ) { + multiplyVectors( a, b ) { - this.center.copy( center ); - this.radius = radius; + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; return this; } - setFromPoints( points, optionalCenter ) { + applyEuler( euler ) { - const center = this.center; + return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) ); - if ( optionalCenter !== undefined ) { + } - center.copy( optionalCenter ); + applyAxisAngle( axis, angle ) { - } else { + return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) ); - _box$1.setFromPoints( points ).getCenter( center ); + } - } + applyMatrix3( m ) { - let maxRadiusSq = 0; + const x = this.x, y = this.y, z = this.z; + const e = m.elements; - for ( let i = 0, il = points.length; i < il; i ++ ) { + 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; - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + return this; - } + } - this.radius = Math.sqrt( maxRadiusSq ); + applyNormalMatrix( m ) { - return this; + return this.applyMatrix3( m ).normalize(); } - copy( sphere ) { + applyMatrix4( m ) { - this.center.copy( sphere.center ); - this.radius = sphere.radius; + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + + 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; return this; } - isEmpty() { + applyQuaternion( q ) { - return ( this.radius < 0 ); + const x = this.x, y = this.y, z = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; - } + // calculate quat * vector - makeEmpty() { + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = - qx * x - qy * y - qz * z; - this.center.set( 0, 0, 0 ); - this.radius = - 1; + // calculate result * inverse quat + + 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; return this; } - containsPoint( point ) { + project( camera ) { - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); } - distanceToPoint( point ) { + unproject( camera ) { - return ( point.distanceTo( this.center ) - this.radius ); + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); } - intersectsSphere( sphere ) { + transformDirection( m ) { - const radiusSum = this.radius + sphere.radius; + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + + return this.normalize(); } - intersectsBox( box ) { + divide( v ) { - return box.intersectsSphere( this ); + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + + return this; } - intersectsPlane( plane ) { + divideScalar( scalar ) { - return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + return this.multiplyScalar( 1 / scalar ); } - clampPoint( point, target ) { + min( v ) { - const deltaLengthSq = this.center.distanceToSquared( point ); + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); - if ( target === undefined ) { + return this; - console.warn( 'THREE.Sphere: .clampPoint() target is now required' ); - target = new Vector3(); + } - } + max( v ) { - target.copy( point ); + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + return this; - target.sub( this.center ).normalize(); - target.multiplyScalar( this.radius ).add( this.center ); + } - } + clamp( min, max ) { - return target; + // assumes min < max, componentwise - } + 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 ) ); - getBoundingBox( target ) { + return this; - if ( target === undefined ) { + } - console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' ); - target = new Box3(); + clampScalar( minVal, maxVal ) { - } + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - if ( this.isEmpty() ) { + return this; - // Empty sphere produces empty bounding box - target.makeEmpty(); - return target; + } - } + clampLength( min, max ) { - target.set( this.center, this.center ); - target.expandByScalar( this.radius ); + const length = this.length(); - return target; + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); } - applyMatrix4( matrix ) { + floor() { - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); return this; } - translate( offset ) { + ceil() { - this.center.add( offset ); + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); return this; } - equals( sphere ) { + round() { - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + + return this; } - clone() { + roundToZero() { - return new this.constructor().copy( 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 ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + + return this; } -} + negate() { -const _vector$2 = /*@__PURE__*/ new Vector3(); -const _segCenter = /*@__PURE__*/ new Vector3(); -const _segDir = /*@__PURE__*/ new Vector3(); -const _diff = /*@__PURE__*/ new Vector3(); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; -const _edge1 = /*@__PURE__*/ new Vector3(); -const _edge2 = /*@__PURE__*/ new Vector3(); -const _normal = /*@__PURE__*/ new Vector3(); + return this; -class Ray { + } - constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { + dot( v ) { - this.origin = origin; - this.direction = direction; + return this.x * v.x + this.y * v.y + this.z * v.z; } - set( origin, direction ) { + // TODO lengthSquared? - this.origin.copy( origin ); - this.direction.copy( direction ); + lengthSq() { - return this; + return this.x * this.x + this.y * this.y + this.z * this.z; } - copy( ray ) { + length() { - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - return this; + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); } - at( t, target ) { + normalize() { - if ( target === undefined ) { + return this.divideScalar( this.length() || 1 ); - console.warn( 'THREE.Ray: .at() target is now required' ); - target = new Vector3(); + } - } + setLength( length ) { - return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + return this.normalize().multiplyScalar( length ); } - lookAt( v ) { + lerp( v, alpha ) { - this.direction.copy( v ).sub( this.origin ).normalize(); + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; return this; } - recast( t ) { + lerpVectors( v1, v2, alpha ) { - this.origin.copy( this.at( t, _vector$2 ) ); + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; return this; } - closestPointToPoint( point, target ) { + cross( v ) { - if ( target === undefined ) { + return this.crossVectors( this, v ); - console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' ); - target = new Vector3(); + } - } + crossVectors( a, b ) { - target.subVectors( point, this.origin ); + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; - const directionDistance = target.dot( this.direction ); + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - if ( directionDistance < 0 ) { + return this; - return target.copy( this.origin ); + } - } + projectOnVector( v ) { - return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + const denominator = v.lengthSq(); - } + if ( denominator === 0 ) return this.set( 0, 0, 0 ); - distanceToPoint( point ) { + const scalar = v.dot( this ) / denominator; - return Math.sqrt( this.distanceSqToPoint( point ) ); + return this.copy( v ).multiplyScalar( scalar ); } - distanceSqToPoint( point ) { - - const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction ); + projectOnPlane( planeNormal ) { - // point behind the ray + _vector$c.copy( this ).projectOnVector( planeNormal ); - if ( directionDistance < 0 ) { + return this.sub( _vector$c ); - return this.origin.distanceToSquared( point ); + } - } + reflect( normal ) { - _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - return _vector$2.distanceToSquared( point ); + return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); } - 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 ); + angleTo( v ) { - const segExtent = v0.distanceTo( v1 ) * 0.5; - const a01 = - this.direction.dot( _segDir ); - const b0 = _diff.dot( this.direction ); - const b1 = - _diff.dot( _segDir ); - const c = _diff.lengthSq(); - const det = Math.abs( 1 - a01 * a01 ); - let s0, s1, sqrDist, extDet; + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); - if ( det > 0 ) { + if ( denominator === 0 ) return Math.PI / 2; - // The ray and segment are not parallel. + const theta = this.dot( v ) / denominator; - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + // clamp, to handle numerical problems - if ( s0 >= 0 ) { + return Math.acos( clamp( theta, - 1, 1 ) ); - if ( s1 >= - extDet ) { + } - if ( s1 <= extDet ) { + distanceTo( v ) { - // region 0 - // Minimum at interior points of ray and segment. + return Math.sqrt( this.distanceToSquared( v ) ); - const invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + } - } else { + distanceToSquared( v ) { - // region 1 + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + return dx * dx + dy * dy + dz * dz; - } + } - } else { + manhattanDistanceTo( v ) { - // region 5 + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + } - } + setFromSpherical( s ) { - } else { + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); - if ( s1 <= - extDet ) { + } - // region 4 + setFromSphericalCoords( radius, phi, theta ) { - 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; + const sinPhiRadius = Math.sin( phi ) * radius; - } else if ( s1 <= extDet ) { + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); - // region 3 + return this; - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + } - } else { + setFromCylindrical( c ) { - // region 2 + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); - 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; + } - } + setFromCylindricalCoords( radius, theta, y ) { - } + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); - } else { + return this; - // Ray and segment are parallel. + } - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + setFromMatrixPosition( m ) { - } + const e = m.elements; - if ( optionalPointOnRay ) { + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + return this; - } + } - if ( optionalPointOnSegment ) { + setFromMatrixScale( m ) { - optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); + const sx = this.setFromMatrixColumn( m, 0 ).length(); + const sy = this.setFromMatrixColumn( m, 1 ).length(); + const sz = this.setFromMatrixColumn( m, 2 ).length(); - } + this.x = sx; + this.y = sy; + this.z = sz; - return sqrDist; + return this; } - intersectSphere( sphere, target ) { + setFromMatrixColumn( m, index ) { - _vector$2.subVectors( sphere.center, this.origin ); - const tca = _vector$2.dot( this.direction ); - const d2 = _vector$2.dot( _vector$2 ) - tca * tca; - const radius2 = sphere.radius * sphere.radius; + return this.fromArray( m.elements, index * 4 ); - if ( d2 > radius2 ) return null; + } - const thc = Math.sqrt( radius2 - d2 ); + setFromMatrix3Column( m, index ) { - // t0 = first intersect point - entrance on front of sphere - const t0 = tca - thc; + return this.fromArray( m.elements, index * 3 ); - // t1 = second intersect point - exit point on back of sphere - const t1 = tca + thc; + } - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + setFromEuler( e ) { - // 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, target ); + this.x = e._x; + this.y = e._y; + this.z = e._z; - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, target ); + return this; } - intersectsSphere( sphere ) { + equals( v ) { - return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); } - distanceToPlane( plane ) { + fromArray( array, offset = 0 ) { - const denominator = plane.normal.dot( this.direction ); + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - if ( denominator === 0 ) { + return this; - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { - - return 0; + } - } + toArray( array = [], offset = 0 ) { - // Null is preferable to undefined since undefined means.... it is undefined + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - return null; + return array; - } + } - const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + fromBufferAttribute( attribute, index ) { - // Return if the ray never intersects the plane + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); - return t >= 0 ? t : null; + return this; } - intersectPlane( plane, target ) { + random() { - const t = this.distanceToPlane( plane ); + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); - if ( t === null ) { + return this; - return null; + } - } + randomDirection() { - return this.at( t, target ); + // Derived from https://mathworld.wolfram.com/SpherePointPicking.html - } + const u = ( Math.random() - 0.5 ) * 2; + const t = Math.random() * Math.PI * 2; + const f = Math.sqrt( 1 - u ** 2 ); - intersectsPlane( plane ) { + this.x = f * Math.cos( t ); + this.y = f * Math.sin( t ); + this.z = u; - // check if the ray lies on the plane first + return this; - const distToPoint = plane.distanceToPoint( this.origin ); + } - if ( distToPoint === 0 ) { + *[ Symbol.iterator ]() { - return true; + yield this.x; + yield this.y; + yield this.z; - } + } - const denominator = plane.normal.dot( this.direction ); +} - if ( denominator * distToPoint < 0 ) { +const _vector$c = /*@__PURE__*/ new Vector3(); +const _quaternion$4 = /*@__PURE__*/ new Quaternion(); - return true; +class Box3 { - } + constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { - // ray origin is behind the plane (and is pointing behind it) + this.isBox3 = true; - return false; + this.min = min; + this.max = max; } - intersectBox( box, target ) { + set( min, max ) { - let tmin, tmax, tymin, tymax, tzmin, tzmax; + this.min.copy( min ); + this.max.copy( max ); - const invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + return this; - const origin = this.origin; + } - if ( invdirx >= 0 ) { + setFromArray( array ) { - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; - } else { + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + for ( let i = 0, l = array.length; i < l; i += 3 ) { - } + const x = array[ i ]; + const y = array[ i + 1 ]; + const z = array[ i + 2 ]; - if ( invdiry >= 0 ) { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - } else { + } - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - } + return this; - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + } - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + setFromBufferAttribute( attribute ) { - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; - if ( invdirz >= 0 ) { + for ( let i = 0, l = attribute.count; i < l; i ++ ) { - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + const x = attribute.getX( i ); + const y = attribute.getY( i ); + const z = attribute.getZ( i ); - } else { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; } - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + return this; - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + } - //return point closest to the ray (positive side) + setFromPoints( points ) { - if ( tmax < 0 ) return null; + this.makeEmpty(); - return this.at( tmin >= 0 ? tmin : tmax, target ); + for ( let i = 0, il = points.length; i < il; i ++ ) { - } + this.expandByPoint( points[ i ] ); - intersectsBox( box ) { + } - return this.intersectBox( box, _vector$2 ) !== null; + return this; } - intersectTriangle( a, b, c, backfaceCulling, target ) { + setFromCenterAndSize( center, size ) { - // Compute the offset origin, edges, and normal. + const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 ); - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - _edge1.subVectors( b, a ); - _edge2.subVectors( c, a ); - _normal.crossVectors( _edge1, _edge2 ); + return this; - // 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) - let DdN = this.direction.dot( _normal ); - let sign; + } - if ( DdN > 0 ) { + setFromObject( object, precise = false ) { - if ( backfaceCulling ) return null; - sign = 1; + this.makeEmpty(); - } else if ( DdN < 0 ) { + return this.expandByObject( object, precise ); - sign = - 1; - DdN = - DdN; + } - } else { + clone() { - return null; + return new this.constructor().copy( this ); - } + } - _diff.subVectors( this.origin, a ); - const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); + copy( box ) { - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + this.min.copy( box.min ); + this.max.copy( box.max ); - return null; + return this; - } + } - const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); + makeEmpty() { - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - return null; + return this; - } + } - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + isEmpty() { - return null; + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - } + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - // Line intersects triangle, check if ray does. - const QdN = - sign * _diff.dot( _normal ); + } - // t < 0, no intersection - if ( QdN < 0 ) { + getCenter( target ) { - return null; + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - } + } - // Ray intersects triangle. - return this.at( QdN / DdN, target ); + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); } - applyMatrix4( matrix4 ) { + expandByPoint( point ) { - this.origin.applyMatrix4( matrix4 ); - this.direction.transformDirection( matrix4 ); + this.min.min( point ); + this.max.max( point ); return this; } - equals( ray ) { + expandByVector( vector ) { - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + this.min.sub( vector ); + this.max.add( vector ); + + return this; } - clone() { + expandByScalar( scalar ) { - return new this.constructor().copy( this ); + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; } -} + expandByObject( object, precise = false ) { -class Matrix4 { + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - constructor() { + object.updateWorldMatrix( false, false ); - this.elements = [ + const geometry = object.geometry; - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + if ( geometry !== undefined ) { - ]; + if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) { - if ( arguments.length > 0 ) { + const position = geometry.attributes.position; + for ( let i = 0, l = position.count; i < l; i ++ ) { - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld ); + this.expandByPoint( _vector$b ); - } + } - } + } else { - set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + if ( geometry.boundingBox === null ) { - const te = this.elements; + geometry.computeBoundingBox(); - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + } - return this; + _box$3.copy( geometry.boundingBox ); + _box$3.applyMatrix4( object.matrixWorld ); - } + this.union( _box$3 ); - identity() { + } - this.set( + } - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + const children = object.children; - ); + for ( let i = 0, l = children.length; i < l; i ++ ) { + + this.expandByObject( children[ i ], precise ); + + } return this; } - clone() { + containsPoint( point ) { - return new Matrix4().fromArray( this.elements ); + return 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 ? false : true; } - copy( m ) { - - const te = this.elements; - const me = m.elements; - - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; - te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; - te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; - te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + containsBox( box ) { - return this; + return 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; } - copyPosition( m ) { - - const te = this.elements, me = m.elements; + getParameter( point, target ) { - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - return this; + return target.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 ) + ); } - setFromMatrix3( m ) { + intersectsBox( box ) { - const me = m.elements; + // using 6 splitting planes to rule out intersections. + return 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 ? false : true; - this.set( + } - me[ 0 ], me[ 3 ], me[ 6 ], 0, - me[ 1 ], me[ 4 ], me[ 7 ], 0, - me[ 2 ], me[ 5 ], me[ 8 ], 0, - 0, 0, 0, 1 + intersectsSphere( sphere ) { - ); + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$b ); - return this; + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); } - extractBasis( xAxis, yAxis, zAxis ) { + intersectsPlane( plane ) { - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + // 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. - return this; + let min, max; - } + if ( plane.normal.x > 0 ) { - makeBasis( xAxis, yAxis, zAxis ) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - 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 - ); + } else { - return this; + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - } + } - extractRotation( m ) { + if ( plane.normal.y > 0 ) { - // this method does not support reflection matrices + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - const te = this.elements; - const me = m.elements; + } else { - const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length(); - const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length(); - const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length(); + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; - te[ 3 ] = 0; + } - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; - te[ 7 ] = 0; + if ( plane.normal.z > 0 ) { - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; - te[ 11 ] = 0; + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + } else { - return this; + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + + } + + return ( min <= - plane.constant && max >= - plane.constant ); } - makeRotationFromEuler( euler ) { + intersectsTriangle( triangle ) { - if ( ! ( euler && euler.isEuler ) ) { + if ( this.isEmpty() ) { - console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + return false; } - const te = this.elements; + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); - const x = euler.x, y = euler.y, z = euler.z; - const a = Math.cos( x ), b = Math.sin( x ); - const c = Math.cos( y ), d = Math.sin( y ); - const e = Math.cos( z ), f = Math.sin( z ); + // translate triangle to aabb origin + _v0$2.subVectors( triangle.a, _center ); + _v1$7.subVectors( triangle.b, _center ); + _v2$3.subVectors( triangle.c, _center ); - if ( euler.order === 'XYZ' ) { + // compute edge vectors for triangle + _f0.subVectors( _v1$7, _v0$2 ); + _f1.subVectors( _v2$3, _v1$7 ); + _f2.subVectors( _v0$2, _v2$3 ); - const ae = a * e, af = a * f, be = b * e, bf = b * f; + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + let axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) { - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + return false; - 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; + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) { - } else if ( euler.order === 'YXZ' ) { + return false; - const ce = c * e, cf = c * f, de = d * e, df = d * f; + } - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ); - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + } - } else if ( euler.order === 'ZXY' ) { + clampPoint( point, target ) { - const ce = c * e, cf = c * f, de = d * e, df = d * f; + return target.copy( point ).clamp( this.min, this.max ); - 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; + distanceToPoint( point ) { - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max ); - } else if ( euler.order === 'ZYX' ) { + return clampedPoint.sub( point ).length(); - const 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; + getBoundingSphere( target ) { - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + this.getCenter( target.center ); - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + target.radius = this.getSize( _vector$b ).length() * 0.5; - } else if ( euler.order === 'YZX' ) { + return target; - const 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; + intersect( box ) { - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + this.min.max( box.min ); + this.max.min( box.max ); - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + // 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(); - } else if ( euler.order === 'XZY' ) { + return this; - const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + } - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + union( box ) { - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + this.min.min( box.min ); + this.max.max( box.max ); - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + return this; - } + } - // bottom row - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + applyMatrix4( matrix ) { - // last column - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + // 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 + + this.setFromPoints( _points ); return this; } - makeRotationFromQuaternion( q ) { + translate( offset ) { - return this.compose( _zero, q, _one ); + this.min.add( offset ); + this.max.add( offset ); + + return this; } - lookAt( eye, target, up ) { + equals( box ) { - const te = this.elements; + return box.min.equals( this.min ) && box.max.equals( this.max ); - _z.subVectors( eye, target ); + } - if ( _z.lengthSq() === 0 ) { +} - // eye and target are in the same position +const _points = [ + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3() +]; - _z.z = 1; +const _vector$b = /*@__PURE__*/ new Vector3(); - } +const _box$3 = /*@__PURE__*/ new Box3(); - _z.normalize(); - _x.crossVectors( up, _z ); +// triangle centered vertices - if ( _x.lengthSq() === 0 ) { +const _v0$2 = /*@__PURE__*/ new Vector3(); +const _v1$7 = /*@__PURE__*/ new Vector3(); +const _v2$3 = /*@__PURE__*/ new Vector3(); - // up and z are parallel +// triangle edge vectors - if ( Math.abs( up.z ) === 1 ) { +const _f0 = /*@__PURE__*/ new Vector3(); +const _f1 = /*@__PURE__*/ new Vector3(); +const _f2 = /*@__PURE__*/ new Vector3(); - _z.x += 0.0001; +const _center = /*@__PURE__*/ new Vector3(); +const _extents = /*@__PURE__*/ new Vector3(); +const _triangleNormal = /*@__PURE__*/ new Vector3(); +const _testAxis = /*@__PURE__*/ new Vector3(); - } else { +function satForAxes( axes, v0, v1, v2, extents ) { - _z.z += 0.0001; + for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { - } + _testAxis.fromArray( axes, i ); + // project the aabb onto the separating axis + const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the separating axis + const p0 = v0.dot( _testAxis ); + const p1 = v1.dot( _testAxis ); + const p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { - _z.normalize(); - _x.crossVectors( up, _z ); + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is separating and we can exit + return false; } - _x.normalize(); - _y.crossVectors( _z, _x ); + } - 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 true; - return this; +} - } +const _box$2 = /*@__PURE__*/ new Box3(); +const _v1$6 = /*@__PURE__*/ new Vector3(); +const _toFarthestPoint = /*@__PURE__*/ new Vector3(); +const _toPoint = /*@__PURE__*/ new Vector3(); - multiply( m, n ) { +class Sphere { - if ( n !== undefined ) { + constructor( center = new Vector3(), radius = - 1 ) { - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + this.center = center; + this.radius = radius; - } + } - return this.multiplyMatrices( this, m ); + set( center, radius ) { + + this.center.copy( center ); + this.radius = radius; + + return this; } - premultiply( m ) { + setFromPoints( points, optionalCenter ) { - return this.multiplyMatrices( m, this ); + const center = this.center; - } + if ( optionalCenter !== undefined ) { - multiplyMatrices( a, b ) { + center.copy( optionalCenter ); - const ae = a.elements; - const be = b.elements; - const te = this.elements; + } else { - const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + _box$2.setFromPoints( points ).getCenter( center ); - const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + } - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + let maxRadiusSq = 0; - 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; + for ( let i = 0, il = points.length; i < il; i ++ ) { - 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; + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + } + + this.radius = Math.sqrt( maxRadiusSq ); return this; } - multiplyScalar( s ) { - - const te = this.elements; + copy( sphere ) { - 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; + this.center.copy( sphere.center ); + this.radius = sphere.radius; return this; } - determinant() { + isEmpty() { - const te = this.elements; + return ( this.radius < 0 ); - const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + } - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + makeEmpty() { - 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 - ) + this.center.set( 0, 0, 0 ); + this.radius = - 1; - ); + return this; } - transpose() { + containsPoint( point ) { - const te = this.elements; - let tmp; + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - 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; + distanceToPoint( point ) { - return this; + return ( point.distanceTo( this.center ) - this.radius ); } - setPosition( x, y, z ) { + intersectsSphere( sphere ) { - const te = this.elements; + const radiusSum = this.radius + sphere.radius; - if ( x.isVector3 ) { + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - te[ 12 ] = x.x; - te[ 13 ] = x.y; - te[ 14 ] = x.z; + } - } else { + intersectsBox( box ) { - te[ 12 ] = x; - te[ 13 ] = y; - te[ 14 ] = z; + return box.intersectsSphere( this ); - } + } - return this; + intersectsPlane( plane ) { + + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; } - invert() { + clampPoint( point, target ) { - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - const te = this.elements, + const deltaLengthSq = this.center.distanceToSquared( point ); - n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], - n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], - n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], - n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], + target.copy( point ); - 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; + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); - if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + } - const detInv = 1 / det; + return target; - 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; + getBoundingBox( target ) { - 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; + if ( this.isEmpty() ) { - 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; + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; - return this; + } - } + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); - scale( v ) { + return target; - const te = this.elements; - const x = v.x, y = v.y, z = v.z; + } - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + applyMatrix4( matrix ) { + + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); return this; } - getMaxScaleOnAxis() { - - const te = this.elements; + translate( offset ) { - const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + this.center.add( offset ); - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + return this; } - makeTranslation( x, y, z ) { - - this.set( - - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + expandByPoint( point ) { - ); + // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671 - return this; + _toPoint.subVectors( point, this.center ); - } + const lengthSq = _toPoint.lengthSq(); - makeRotationX( theta ) { + if ( lengthSq > ( this.radius * this.radius ) ) { - const c = Math.cos( theta ), s = Math.sin( theta ); + const length = Math.sqrt( lengthSq ); + const missingRadiusHalf = ( length - this.radius ) * 0.5; - this.set( + // Nudge this sphere towards the target point. Add half the missing distance to radius, + // and the other half to position. This gives a tighter enclosure, instead of if + // the whole missing distance were just added to radius. - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) ); + this.radius += missingRadiusHalf; - ); + } return this; } - makeRotationY( theta ) { - - const c = Math.cos( theta ), s = Math.sin( theta ); - - this.set( + union( sphere ) { - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769 - ); + // To enclose another sphere into this sphere, we only need to enclose two points: + // 1) Enclose the farthest point on the other sphere into this sphere. + // 2) Enclose the opposite point of the farthest point into this sphere. - return this; + if ( this.center.equals( sphere.center ) === true ) { - } + _toFarthestPoint.set( 0, 0, 1 ).multiplyScalar( sphere.radius ); - makeRotationZ( theta ) { - const c = Math.cos( theta ), s = Math.sin( theta ); + } else { - this.set( + _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius ); - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + } - ); + this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) ); + this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) ); return this; } - makeRotationAxis( axis, angle ) { - - // Based on http://www.gamedev.net/reference/articles/article1199.asp - - const c = Math.cos( angle ); - const s = Math.sin( angle ); - const t = 1 - c; - const x = axis.x, y = axis.y, z = axis.z; - const tx = t * x, ty = t * y; + equals( sphere ) { - this.set( + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - 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 + } - ); + clone() { - return this; + return new this.constructor().copy( this ); } - makeScale( x, y, z ) { - - this.set( +} - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 +const _vector$a = /*@__PURE__*/ new Vector3(); +const _segCenter = /*@__PURE__*/ new Vector3(); +const _segDir = /*@__PURE__*/ new Vector3(); +const _diff = /*@__PURE__*/ new Vector3(); - ); +const _edge1 = /*@__PURE__*/ new Vector3(); +const _edge2 = /*@__PURE__*/ new Vector3(); +const _normal$1 = /*@__PURE__*/ new Vector3(); - return this; +class Ray { - } + constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { - makeShear( x, y, z ) { + this.origin = origin; + this.direction = direction; - this.set( + } - 1, y, z, 0, - x, 1, z, 0, - x, y, 1, 0, - 0, 0, 0, 1 + set( origin, direction ) { - ); + this.origin.copy( origin ); + this.direction.copy( direction ); return this; } - compose( position, quaternion, scale ) { + copy( ray ) { - const te = this.elements; + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; - const x2 = x + x, y2 = y + y, z2 = z + z; - const xx = x * x2, xy = x * y2, xz = x * z2; - const yy = y * y2, yz = y * z2, zz = z * z2; - const wx = w * x2, wy = w * y2, wz = w * z2; + return this; - const sx = scale.x, sy = scale.y, sz = scale.z; + } - te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; - te[ 1 ] = ( xy + wz ) * sx; - te[ 2 ] = ( xz - wy ) * sx; - te[ 3 ] = 0; + at( t, target ) { - te[ 4 ] = ( xy - wz ) * sy; - te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; - te[ 6 ] = ( yz + wx ) * sy; - te[ 7 ] = 0; + return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - te[ 8 ] = ( xz + wy ) * sz; - te[ 9 ] = ( yz - wx ) * sz; - te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; - te[ 11 ] = 0; + } - te[ 12 ] = position.x; - te[ 13 ] = position.y; - te[ 14 ] = position.z; - te[ 15 ] = 1; + lookAt( v ) { + + this.direction.copy( v ).sub( this.origin ).normalize(); return this; } - decompose( position, quaternion, scale ) { + recast( t ) { - const te = this.elements; + this.origin.copy( this.at( t, _vector$a ) ); - let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + return this; - // if determine is negative, we need to invert one scale - const det = this.determinant(); - if ( det < 0 ) sx = - sx; + } - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + closestPointToPoint( point, target ) { - // scale the rotation part - _m1.copy( this ); + target.subVectors( point, this.origin ); - const invSX = 1 / sx; - const invSY = 1 / sy; - const invSZ = 1 / sz; + const directionDistance = target.dot( this.direction ); - _m1.elements[ 0 ] *= invSX; - _m1.elements[ 1 ] *= invSX; - _m1.elements[ 2 ] *= invSX; + if ( directionDistance < 0 ) { - _m1.elements[ 4 ] *= invSY; - _m1.elements[ 5 ] *= invSY; - _m1.elements[ 6 ] *= invSY; + return target.copy( this.origin ); - _m1.elements[ 8 ] *= invSZ; - _m1.elements[ 9 ] *= invSZ; - _m1.elements[ 10 ] *= invSZ; + } - quaternion.setFromRotationMatrix( _m1 ); + return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - scale.x = sx; - scale.y = sy; - scale.z = sz; + } - return this; + distanceToPoint( point ) { + + return Math.sqrt( this.distanceSqToPoint( point ) ); } - makePerspective( left, right, top, bottom, near, far ) { + distanceSqToPoint( point ) { - if ( far === undefined ) { + const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction ); - console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); + // point behind the ray - } + if ( directionDistance < 0 ) { - const te = this.elements; - const x = 2 * near / ( right - left ); - const y = 2 * near / ( top - bottom ); + return this.origin.distanceToSquared( point ); - const a = ( right + left ) / ( right - left ); - const b = ( top + bottom ) / ( top - bottom ); - const c = - ( far + near ) / ( far - near ); - const 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; + _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - return this; + return _vector$a.distanceToSquared( point ); } - makeOrthographic( left, right, top, bottom, near, far ) { - - const te = this.elements; - const w = 1.0 / ( right - left ); - const h = 1.0 / ( top - bottom ); - const p = 1.0 / ( far - near ); + distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - const x = ( right + left ) * w; - const y = ( top + bottom ) * h; - const z = ( far + near ) * p; - - 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; - - return this; + // from https://github.com/pmjoniak/GeometricTools/blob/master/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 ); - equals( matrix ) { + const segExtent = v0.distanceTo( v1 ) * 0.5; + const a01 = - this.direction.dot( _segDir ); + const b0 = _diff.dot( this.direction ); + const b1 = - _diff.dot( _segDir ); + const c = _diff.lengthSq(); + const det = Math.abs( 1 - a01 * a01 ); + let s0, s1, sqrDist, extDet; - const te = this.elements; - const me = matrix.elements; + if ( det > 0 ) { - for ( let i = 0; i < 16; i ++ ) { + // The ray and segment are not parallel. - if ( te[ i ] !== me[ i ] ) return false; + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - } + if ( s0 >= 0 ) { - return true; + if ( s1 >= - extDet ) { - } + if ( s1 <= extDet ) { - fromArray( array, offset = 0 ) { + // region 0 + // Minimum at interior points of ray and segment. - for ( let i = 0; i < 16; i ++ ) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - this.elements[ i ] = array[ i + offset ]; + } else { - } + // region 1 - return this; + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } + } - toArray( array = [], offset = 0 ) { + } else { - const te = this.elements; + // region 5 - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + } - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + } else { - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + if ( s1 <= - extDet ) { - return array; + // region 4 - } + 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; -} + } else if ( s1 <= extDet ) { -Matrix4.prototype.isMatrix4 = true; + // region 3 -const _v1$1 = /*@__PURE__*/ new Vector3(); -const _m1 = /*@__PURE__*/ new Matrix4(); -const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); -const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); -const _x = /*@__PURE__*/ new Vector3(); -const _y = /*@__PURE__*/ new Vector3(); -const _z = /*@__PURE__*/ new Vector3(); + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; -const _matrix = /*@__PURE__*/ new Matrix4(); -const _quaternion$1 = /*@__PURE__*/ new Quaternion(); + } else { -class Euler { + // region 2 - constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { + 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._x = x; - this._y = y; - this._z = z; - this._order = order; + } - } + } - get x() { + } else { - return this._x; + // Ray and segment are parallel. - } + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - set x( value ) { + } - this._x = value; - this._onChangeCallback(); + if ( optionalPointOnRay ) { - } + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - get y() { + } - return this._y; + if ( optionalPointOnSegment ) { - } + optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); - set y( value ) { + } - this._y = value; - this._onChangeCallback(); + return sqrDist; } - get z() { + intersectSphere( sphere, target ) { - return this._z; + _vector$a.subVectors( sphere.center, this.origin ); + const tca = _vector$a.dot( this.direction ); + const d2 = _vector$a.dot( _vector$a ) - tca * tca; + const radius2 = sphere.radius * sphere.radius; - } + if ( d2 > radius2 ) return null; - set z( value ) { + const thc = Math.sqrt( radius2 - d2 ); - this._z = value; - this._onChangeCallback(); + // t0 = first intersect point - entrance on front of sphere + const t0 = tca - thc; - } + // t1 = second intersect point - exit point on back of sphere + const t1 = tca + thc; - get order() { + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - return this._order; + // 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, target ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); } - set order( value ) { + intersectsSphere( sphere ) { - this._order = value; - this._onChangeCallback(); + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); } - set( x, y, z, order ) { + distanceToPlane( plane ) { - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + const denominator = plane.normal.dot( this.direction ); - this._onChangeCallback(); + if ( denominator === 0 ) { - return this; + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - } + return 0; - clone() { + } - return new this.constructor( this._x, this._y, this._z, this._order ); + // Null is preferable to undefined since undefined means.... it is undefined - } + return null; - copy( euler ) { + } - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - this._onChangeCallback(); + // Return if the ray never intersects the plane - return this; + return t >= 0 ? t : null; } - setFromRotationMatrix( m, order, update ) { - - const clamp = MathUtils.clamp; - - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - - const te = m.elements; - const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + intersectPlane( plane, target ) { - order = order || this._order; + const t = this.distanceToPlane( plane ); - switch ( order ) { + if ( t === null ) { - case 'XYZ': + return null; - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + } - if ( Math.abs( m13 ) < 0.9999999 ) { + return this.at( t, target ); - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + } - } else { + intersectsPlane( plane ) { - this._x = Math.atan2( m32, m22 ); - this._z = 0; + // check if the ray lies on the plane first - } + const distToPoint = plane.distanceToPoint( this.origin ); - break; + if ( distToPoint === 0 ) { - case 'YXZ': + return true; - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + } - if ( Math.abs( m23 ) < 0.9999999 ) { + const denominator = plane.normal.dot( this.direction ); - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + if ( denominator * distToPoint < 0 ) { - } else { + return true; - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + } - } + // ray origin is behind the plane (and is pointing behind it) - break; + return false; - case 'ZXY': + } - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + intersectBox( box, target ) { - if ( Math.abs( m32 ) < 0.9999999 ) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + const invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - } else { + const origin = this.origin; - this._y = 0; - this._z = Math.atan2( m21, m11 ); + if ( invdirx >= 0 ) { - } + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - break; + } else { - case 'ZYX': + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + } - if ( Math.abs( m31 ) < 0.9999999 ) { + if ( invdiry >= 0 ) { - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - } else { + } else { - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - } + } - break; + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - case 'YZX': + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - if ( Math.abs( m21 ) < 0.9999999 ) { + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + if ( invdirz >= 0 ) { - } else { + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - this._x = 0; - this._y = Math.atan2( m13, m33 ); + } else { - } + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - break; + } - case 'XZY': + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - if ( Math.abs( m12 ) < 0.9999999 ) { + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + //return point closest to the ray (positive side) - } else { + if ( tmax < 0 ) return null; - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + return this.at( tmin >= 0 ? tmin : tmax, target ); - } + } - break; + intersectsBox( box ) { - default: + return this.intersectBox( box, _vector$a ) !== null; - console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); + } - } + intersectTriangle( a, b, c, backfaceCulling, target ) { - this._order = order; + // Compute the offset origin, edges, and normal. - if ( update !== false ) this._onChangeCallback(); + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - return this; + _edge1.subVectors( b, a ); + _edge2.subVectors( c, a ); + _normal$1.crossVectors( _edge1, _edge2 ); - } + // 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) + let DdN = this.direction.dot( _normal$1 ); + let sign; - setFromQuaternion( q, order, update ) { + if ( DdN > 0 ) { - _matrix.makeRotationFromQuaternion( q ); + if ( backfaceCulling ) return null; + sign = 1; - return this.setFromRotationMatrix( _matrix, order, update ); + } else if ( DdN < 0 ) { - } + sign = - 1; + DdN = - DdN; - setFromVector3( v, order ) { + } else { - return this.set( v.x, v.y, v.z, order || this._order ); + return null; - } + } - reorder( newOrder ) { + _diff.subVectors( this.origin, a ); + const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); - // WARNING: this discards revolution information -bhouston + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - _quaternion$1.setFromEuler( this ); + return null; - return this.setFromQuaternion( _quaternion$1, newOrder ); + } - } + const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); - equals( euler ) { + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + return null; - } + } - fromArray( array ) { + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + return null; - this._onChangeCallback(); + } - return this; + // Line intersects triangle, check if ray does. + const QdN = - sign * _diff.dot( _normal$1 ); - } + // t < 0, no intersection + if ( QdN < 0 ) { - toArray( array = [], offset = 0 ) { + return null; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + } - return array; + // Ray intersects triangle. + return this.at( QdN / DdN, target ); } - toVector3( optionalResult ) { + applyMatrix4( matrix4 ) { - if ( optionalResult ) { + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); - return optionalResult.set( this._x, this._y, this._z ); + return this; - } else { + } - return new Vector3( this._x, this._y, this._z ); + equals( ray ) { - } + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); } - _onChange( callback ) { - - this._onChangeCallback = callback; + clone() { - return this; + return new this.constructor().copy( this ); } - _onChangeCallback() {} - } -Euler.prototype.isEuler = true; - -Euler.DefaultOrder = 'XYZ'; -Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - -class Layers { +class Matrix4 { constructor() { - this.mask = 1 | 0; + Matrix4.prototype.isMatrix4 = true; - } + this.elements = [ - set( channel ) { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - this.mask = 1 << channel | 0; + ]; } - enable( channel ) { - - this.mask |= 1 << channel | 0; + set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - } + const te = this.elements; - enableAll() { + 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; - this.mask = 0xffffffff | 0; + return this; } - toggle( channel ) { + identity() { - this.mask ^= 1 << channel | 0; + this.set( - } + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - disable( channel ) { + ); - this.mask &= ~ ( 1 << channel | 0 ); + return this; } - disableAll() { + clone() { - this.mask = 0; + return new Matrix4().fromArray( this.elements ); } - test( layers ) { - - return ( this.mask & layers.mask ) !== 0; - - } + copy( m ) { -} + const te = this.elements; + const me = m.elements; -let _object3DId = 0; + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; -const _v1$2 = new Vector3(); -const _q1 = new Quaternion(); -const _m1$1 = new Matrix4(); -const _target = new Vector3(); + return this; -const _position = new Vector3(); -const _scale = new Vector3(); -const _quaternion$2 = new Quaternion(); + } -const _xAxis = new Vector3( 1, 0, 0 ); -const _yAxis = new Vector3( 0, 1, 0 ); -const _zAxis = new Vector3( 0, 0, 1 ); + copyPosition( m ) { -const _addedEvent = { type: 'added' }; -const _removedEvent = { type: 'removed' }; + const te = this.elements, me = m.elements; -function Object3D() { + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - Object.defineProperty( this, 'id', { value: _object3DId ++ } ); + return this; - this.uuid = MathUtils.generateUUID(); + } - this.name = ''; - this.type = 'Object3D'; + setFromMatrix3( m ) { - this.parent = null; - this.children = []; + const me = m.elements; - this.up = Object3D.DefaultUp.clone(); + this.set( - const position = new Vector3(); - const rotation = new Euler(); - const quaternion = new Quaternion(); - const scale = new Vector3( 1, 1, 1 ); + me[ 0 ], me[ 3 ], me[ 6 ], 0, + me[ 1 ], me[ 4 ], me[ 7 ], 0, + me[ 2 ], me[ 5 ], me[ 8 ], 0, + 0, 0, 0, 1 - function onRotationChange() { + ); - quaternion.setFromEuler( rotation, false ); + return this; } - function onQuaternionChange() { + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - rotation.setFromQuaternion( quaternion, undefined, false ); + return this; } - rotation._onChange( onRotationChange ); - quaternion._onChange( onQuaternionChange ); + makeBasis( xAxis, yAxis, zAxis ) { - Object.defineProperties( this, { - position: { - configurable: true, - enumerable: true, - value: position - }, - rotation: { - configurable: true, - enumerable: true, - value: rotation - }, - quaternion: { - configurable: true, - enumerable: true, - value: quaternion - }, - scale: { - configurable: true, - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new Matrix4() - }, - normalMatrix: { - value: new Matrix3() - } - } ); - - this.matrix = new Matrix4(); - this.matrixWorld = new Matrix4(); - - this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; - - this.layers = new Layers(); - this.visible = true; + 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 + ); - this.castShadow = false; - this.receiveShadow = false; + return this; - this.frustumCulled = true; - this.renderOrder = 0; + } - this.animations = []; + extractRotation( m ) { - this.userData = {}; + // this method does not support reflection matrices -} + const te = this.elements; + const me = m.elements; -Object3D.DefaultUp = new Vector3( 0, 1, 0 ); -Object3D.DefaultMatrixAutoUpdate = true; + const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length(); -Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; - constructor: Object3D, + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; - isObject3D: true, + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; - onBeforeRender: function () {}, - onAfterRender: function () {}, + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - applyMatrix4: function ( matrix ) { + return this; - if ( this.matrixAutoUpdate ) this.updateMatrix(); + } - this.matrix.premultiply( matrix ); + makeRotationFromEuler( euler ) { - this.matrix.decompose( this.position, this.quaternion, this.scale ); + const te = this.elements; - }, + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos( x ), b = Math.sin( x ); + const c = Math.cos( y ), d = Math.sin( y ); + const e = Math.cos( z ), f = Math.sin( z ); - applyQuaternion: function ( q ) { + if ( euler.order === 'XYZ' ) { - this.quaternion.premultiply( q ); + const ae = a * e, af = a * f, be = b * e, bf = b * f; - return this; + 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; - setRotationFromAxisAngle: function ( axis, angle ) { + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - // assumes axis is normalized + } else if ( euler.order === 'YXZ' ) { - this.quaternion.setFromAxisAngle( axis, angle ); + const ce = c * e, cf = c * f, de = d * e, df = d * f; - }, + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - setRotationFromEuler: function ( euler ) { + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - this.quaternion.setFromEuler( euler, true ); + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - }, + } else if ( euler.order === 'ZXY' ) { - setRotationFromMatrix: function ( m ) { + const ce = c * e, cf = c * f, de = d * e, df = d * f; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - this.quaternion.setFromRotationMatrix( m ); + 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; - setRotationFromQuaternion: function ( q ) { + } else if ( euler.order === 'ZYX' ) { - // assumes q is normalized + const ae = a * e, af = a * f, be = b * e, bf = b * f; - this.quaternion.copy( q ); + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - }, + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - rotateOnAxis: function ( axis, angle ) { + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - // rotate object on axis in object space - // axis is assumed to be normalized + } else if ( euler.order === 'YZX' ) { - _q1.setFromAxisAngle( axis, angle ); + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - this.quaternion.multiply( _q1 ); + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - return this; + 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; - rotateOnWorldAxis: function ( axis, angle ) { + } else if ( euler.order === 'XZY' ) { - // rotate object on axis in world space - // axis is assumed to be normalized - // method assumes no rotated parent + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; - _q1.setFromAxisAngle( axis, angle ); + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - this.quaternion.premultiply( _q1 ); + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - return this; + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - }, + } - rotateX: function ( angle ) { + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - return this.rotateOnAxis( _xAxis, angle ); + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - }, + return this; - rotateY: function ( angle ) { + } - return this.rotateOnAxis( _yAxis, angle ); + makeRotationFromQuaternion( q ) { - }, + return this.compose( _zero, q, _one ); - rotateZ: function ( angle ) { + } - return this.rotateOnAxis( _zAxis, angle ); + lookAt( eye, target, up ) { - }, + const te = this.elements; - translateOnAxis: function ( axis, distance ) { + _z.subVectors( eye, target ); - // translate object by distance along axis in object space - // axis is assumed to be normalized + if ( _z.lengthSq() === 0 ) { - _v1$2.copy( axis ).applyQuaternion( this.quaternion ); + // eye and target are in the same position - this.position.add( _v1$2.multiplyScalar( distance ) ); + _z.z = 1; - return this; + } - }, + _z.normalize(); + _x.crossVectors( up, _z ); - translateX: function ( distance ) { + if ( _x.lengthSq() === 0 ) { - return this.translateOnAxis( _xAxis, distance ); + // up and z are parallel - }, + if ( Math.abs( up.z ) === 1 ) { - translateY: function ( distance ) { + _z.x += 0.0001; - return this.translateOnAxis( _yAxis, distance ); + } else { - }, + _z.z += 0.0001; - translateZ: function ( distance ) { + } - return this.translateOnAxis( _zAxis, distance ); + _z.normalize(); + _x.crossVectors( up, _z ); - }, + } - localToWorld: function ( vector ) { + _x.normalize(); + _y.crossVectors( _z, _x ); - return vector.applyMatrix4( this.matrixWorld ); + 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; - worldToLocal: function ( vector ) { + } - return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + multiply( m ) { - }, + return this.multiplyMatrices( this, m ); - lookAt: function ( x, y, z ) { + } - // This method does not support objects having non-uniformly-scaled parent(s) + premultiply( m ) { - if ( x.isVector3 ) { + return this.multiplyMatrices( m, this ); - _target.copy( x ); + } - } else { + multiplyMatrices( a, b ) { - _target.set( x, y, z ); + const ae = a.elements; + const be = b.elements; + const te = this.elements; - } + const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - const parent = this.parent; + const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - this.updateWorldMatrix( true, 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; - _position.setFromMatrixPosition( this.matrixWorld ); + 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; - if ( this.isCamera || this.isLight ) { + 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; - _m1$1.lookAt( _position, _target, this.up ); + 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; - } else { + return this; - _m1$1.lookAt( _target, _position, this.up ); + } - } + multiplyScalar( s ) { - this.quaternion.setFromRotationMatrix( _m1$1 ); + const te = this.elements; - if ( parent ) { + 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; - _m1$1.extractRotation( parent.matrixWorld ); - _q1.setFromRotationMatrix( _m1$1 ); - this.quaternion.premultiply( _q1.invert() ); + return this; - } + } - }, + determinant() { - add: function ( object ) { + const te = this.elements; - if ( arguments.length > 1 ) { + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - for ( let i = 0; i < arguments.length; i ++ ) { + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - this.add( arguments[ i ] ); + 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 + ) - } + ); - return this; + } - } + transpose() { - if ( object === this ) { + const te = this.elements; + let tmp; - console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); - return this; + 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; - if ( object && object.isObject3D ) { + return this; - if ( object.parent !== null ) { + } - object.parent.remove( object ); + setPosition( x, y, z ) { - } + const te = this.elements; - object.parent = this; - this.children.push( object ); + if ( x.isVector3 ) { - object.dispatchEvent( _addedEvent ); + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; } else { - console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; } return this; - }, - - remove: function ( object ) { + } - if ( arguments.length > 1 ) { + invert() { - for ( let i = 0; i < arguments.length; i ++ ) { + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + const te = this.elements, - this.remove( arguments[ i ] ); + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], + n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], + n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], + n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], - } + 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; - return this; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - } + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - const index = this.children.indexOf( object ); + const detInv = 1 / det; - if ( index !== - 1 ) { + 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; - object.parent = null; - this.children.splice( index, 1 ); + 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; - object.dispatchEvent( _removedEvent ); + 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; - } + 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; - }, + } - clear: function () { + scale( v ) { - for ( let i = 0; i < this.children.length; i ++ ) { + const te = this.elements; + const x = v.x, y = v.y, z = v.z; - const object = this.children[ i ]; + 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; - object.parent = null; + return this; - object.dispatchEvent( _removedEvent ); + } - } + getMaxScaleOnAxis() { - this.children.length = 0; + const te = this.elements; - return this; + const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - }, + } - attach: function ( object ) { + makeTranslation( x, y, z ) { - // adds object as a child of this, while maintaining the object's world transform + this.set( - this.updateWorldMatrix( true, false ); + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - _m1$1.copy( this.matrixWorld ).invert(); + ); - if ( object.parent !== null ) { + return this; - object.parent.updateWorldMatrix( true, false ); + } - _m1$1.multiply( object.parent.matrixWorld ); + makeRotationX( theta ) { - } + const c = Math.cos( theta ), s = Math.sin( theta ); - object.applyMatrix4( _m1$1 ); + this.set( - this.add( object ); + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - object.updateWorldMatrix( false, true ); + ); return this; - }, + } - getObjectById: function ( id ) { + makeRotationY( theta ) { - return this.getObjectByProperty( 'id', id ); + const c = Math.cos( theta ), s = Math.sin( theta ); - }, + this.set( - getObjectByName: function ( name ) { + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - return this.getObjectByProperty( 'name', name ); + ); - }, + return this; - getObjectByProperty: function ( name, value ) { + } - if ( this[ name ] === value ) return this; + makeRotationZ( theta ) { - for ( let i = 0, l = this.children.length; i < l; i ++ ) { + const c = Math.cos( theta ), s = Math.sin( theta ); - const child = this.children[ i ]; - const object = child.getObjectByProperty( name, value ); + this.set( - if ( object !== undefined ) { + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - return object; + ); - } + return this; - } + } - return undefined; + makeRotationAxis( axis, angle ) { - }, + // Based on http://www.gamedev.net/reference/articles/article1199.asp - getWorldPosition: function ( target ) { + const c = Math.cos( angle ); + const s = Math.sin( angle ); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; - if ( target === undefined ) { + this.set( - console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' ); - target = new Vector3(); + 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 - } + ); - this.updateWorldMatrix( true, false ); + return this; - return target.setFromMatrixPosition( this.matrixWorld ); + } - }, + makeScale( x, y, z ) { - getWorldQuaternion: function ( target ) { + this.set( - if ( target === undefined ) { + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' ); - target = new Quaternion(); + ); - } + return this; - this.updateWorldMatrix( true, false ); + } - this.matrixWorld.decompose( _position, target, _scale ); + makeShear( xy, xz, yx, yz, zx, zy ) { - return target; + this.set( - }, + 1, yx, zx, 0, + xy, 1, zy, 0, + xz, yz, 1, 0, + 0, 0, 0, 1 - getWorldScale: function ( target ) { + ); - if ( target === undefined ) { + return this; - console.warn( 'THREE.Object3D: .getWorldScale() target is now required' ); - target = new Vector3(); + } - } + compose( position, quaternion, scale ) { - this.updateWorldMatrix( true, false ); + const te = this.elements; - this.matrixWorld.decompose( _position, _quaternion$2, target ); + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; - return target; + const sx = scale.x, sy = scale.y, sz = scale.z; - }, + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; - getWorldDirection: function ( target ) { + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; - if ( target === undefined ) { + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; - console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' ); - target = new Vector3(); + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; - } + return this; - this.updateWorldMatrix( true, false ); + } - const e = this.matrixWorld.elements; + decompose( position, quaternion, scale ) { - return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + const te = this.elements; - }, + let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - raycast: function () {}, + // if determine is negative, we need to invert one scale + const det = this.determinant(); + if ( det < 0 ) sx = - sx; - traverse: function ( callback ) { + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - callback( this ); + // scale the rotation part + _m1$2.copy( this ); - const children = this.children; + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; - for ( let i = 0, l = children.length; i < l; i ++ ) { + _m1$2.elements[ 0 ] *= invSX; + _m1$2.elements[ 1 ] *= invSX; + _m1$2.elements[ 2 ] *= invSX; - children[ i ].traverse( callback ); + _m1$2.elements[ 4 ] *= invSY; + _m1$2.elements[ 5 ] *= invSY; + _m1$2.elements[ 6 ] *= invSY; - } + _m1$2.elements[ 8 ] *= invSZ; + _m1$2.elements[ 9 ] *= invSZ; + _m1$2.elements[ 10 ] *= invSZ; - }, + quaternion.setFromRotationMatrix( _m1$2 ); - traverseVisible: function ( callback ) { + scale.x = sx; + scale.y = sy; + scale.z = sz; - if ( this.visible === false ) return; + return this; - callback( this ); + } - const children = this.children; + makePerspective( left, right, top, bottom, near, far ) { - for ( let i = 0, l = children.length; i < l; i ++ ) { + const te = this.elements; + const x = 2 * near / ( right - left ); + const y = 2 * near / ( top - bottom ); - children[ i ].traverseVisible( callback ); + const a = ( right + left ) / ( right - left ); + const b = ( top + bottom ) / ( top - bottom ); + const c = - ( far + near ) / ( far - near ); + const 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; - }, + return this; - traverseAncestors: function ( callback ) { + } - const parent = this.parent; + makeOrthographic( left, right, top, bottom, near, far ) { - if ( parent !== null ) { + const te = this.elements; + const w = 1.0 / ( right - left ); + const h = 1.0 / ( top - bottom ); + const p = 1.0 / ( far - near ); - callback( parent ); + const x = ( right + left ) * w; + const y = ( top + bottom ) * h; + const z = ( far + near ) * p; - parent.traverseAncestors( callback ); + 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; - } + return this; - }, + } - updateMatrix: function () { + equals( matrix ) { - this.matrix.compose( this.position, this.quaternion, this.scale ); + const te = this.elements; + const me = matrix.elements; - this.matrixWorldNeedsUpdate = true; + for ( let i = 0; i < 16; i ++ ) { - }, + if ( te[ i ] !== me[ i ] ) return false; - updateMatrixWorld: function ( force ) { + } - if ( this.matrixAutoUpdate ) this.updateMatrix(); + return true; - if ( this.matrixWorldNeedsUpdate || force ) { + } - if ( this.parent === null ) { + fromArray( array, offset = 0 ) { - this.matrixWorld.copy( this.matrix ); + for ( let i = 0; i < 16; i ++ ) { - } else { + this.elements[ i ] = array[ i + offset ]; - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + } - } + return this; - this.matrixWorldNeedsUpdate = false; + } - force = true; + toArray( array = [], offset = 0 ) { - } + const te = this.elements; - // update children + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - const children = this.children; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - for ( let i = 0, l = children.length; i < l; i ++ ) { + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - children[ i ].updateMatrixWorld( force ); + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - } + return array; - }, + } - updateWorldMatrix: function ( updateParents, updateChildren ) { +} - const parent = this.parent; +const _v1$5 = /*@__PURE__*/ new Vector3(); +const _m1$2 = /*@__PURE__*/ new Matrix4(); +const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); +const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); +const _x = /*@__PURE__*/ new Vector3(); +const _y = /*@__PURE__*/ new Vector3(); +const _z = /*@__PURE__*/ new Vector3(); - if ( updateParents === true && parent !== null ) { +const _matrix$1 = /*@__PURE__*/ new Matrix4(); +const _quaternion$3 = /*@__PURE__*/ new Quaternion(); - parent.updateWorldMatrix( true, false ); +class Euler { - } + constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) { - if ( this.matrixAutoUpdate ) this.updateMatrix(); + this.isEuler = true; - if ( this.parent === null ) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; - this.matrixWorld.copy( this.matrix ); + } - } else { + get x() { - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + return this._x; - } + } - // update children + set x( value ) { - if ( updateChildren === true ) { + this._x = value; + this._onChangeCallback(); - const children = this.children; + } - for ( let i = 0, l = children.length; i < l; i ++ ) { + get y() { - children[ i ].updateWorldMatrix( false, true ); + return this._y; - } + } - } + set y( value ) { - }, + this._y = value; + this._onChangeCallback(); - toJSON: function ( meta ) { + } - // meta is a string when called from JSON.stringify - const isRootObject = ( meta === undefined || typeof meta === 'string' ); + get z() { - const output = {}; + return this._z; - // 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: {}, - shapes: {}, - skeletons: {}, - animations: {} - }; + set z( value ) { - output.metadata = { - version: 4.5, - type: 'Object', - generator: 'Object3D.toJSON' - }; + this._z = value; + this._onChangeCallback(); - } + } - // standard Object3D serialization + get order() { - const object = {}; + return this._order; - object.uuid = this.uuid; - object.type = this.type; + } - if ( this.name !== '' ) object.name = this.name; - if ( this.castShadow === true ) object.castShadow = true; - if ( this.receiveShadow === true ) object.receiveShadow = true; - if ( this.visible === false ) object.visible = false; - if ( this.frustumCulled === false ) object.frustumCulled = false; - if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; - if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; + set order( value ) { - object.layers = this.layers.mask; - object.matrix = this.matrix.toArray(); + this._order = value; + this._onChangeCallback(); - if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; + } - // object specific properties + set( x, y, z, order = this._order ) { - if ( this.isInstancedMesh ) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; - object.type = 'InstancedMesh'; - object.count = this.count; - object.instanceMatrix = this.instanceMatrix.toJSON(); + this._onChangeCallback(); - } + return this; - // + } - function serialize( library, element ) { + clone() { - if ( library[ element.uuid ] === undefined ) { + return new this.constructor( this._x, this._y, this._z, this._order ); - library[ element.uuid ] = element.toJSON( meta ); + } - } + copy( euler ) { - return element.uuid; + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - } + this._onChangeCallback(); - if ( this.isMesh || this.isLine || this.isPoints ) { + return this; - object.geometry = serialize( meta.geometries, this.geometry ); + } - const parameters = this.geometry.parameters; + setFromRotationMatrix( m, order = this._order, update = true ) { - if ( parameters !== undefined && parameters.shapes !== undefined ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - const shapes = parameters.shapes; + const te = m.elements; + const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - if ( Array.isArray( shapes ) ) { + switch ( order ) { - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + case 'XYZ': - const shape = shapes[ i ]; + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - serialize( meta.shapes, shape ); + if ( Math.abs( m13 ) < 0.9999999 ) { - } + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); } else { - serialize( meta.shapes, shapes ); + this._x = Math.atan2( m32, m22 ); + this._z = 0; } - } + break; - } + case 'YXZ': - if ( this.isSkinnedMesh ) { + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - object.bindMode = this.bindMode; - object.bindMatrix = this.bindMatrix.toArray(); + if ( Math.abs( m23 ) < 0.9999999 ) { - if ( this.skeleton !== undefined ) { + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - serialize( meta.skeletons, this.skeleton ); + } else { - object.skeleton = this.skeleton.uuid; + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - } + } - } + break; - if ( this.material !== undefined ) { + case 'ZXY': - if ( Array.isArray( this.material ) ) { + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - const uuids = []; + if ( Math.abs( m32 ) < 0.9999999 ) { - for ( let i = 0, l = this.material.length; i < l; i ++ ) { + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - uuids.push( serialize( meta.materials, this.material[ i ] ) ); + } else { - } + this._y = 0; + this._z = Math.atan2( m21, m11 ); - object.material = uuids; + } - } else { + break; - object.material = serialize( meta.materials, this.material ); + case 'ZYX': - } + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - } + if ( Math.abs( m31 ) < 0.9999999 ) { - // + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - if ( this.children.length > 0 ) { + } else { - object.children = []; + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - for ( let i = 0; i < this.children.length; i ++ ) { + } - object.children.push( this.children[ i ].toJSON( meta ).object ); + break; - } + case 'YZX': - } + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - // + if ( Math.abs( m21 ) < 0.9999999 ) { - if ( this.animations.length > 0 ) { + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - object.animations = []; + } else { - for ( let i = 0; i < this.animations.length; i ++ ) { + this._x = 0; + this._y = Math.atan2( m13, m33 ); - const animation = this.animations[ i ]; + } - object.animations.push( serialize( meta.animations, animation ) ); + break; - } + case 'XZY': - } + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - if ( isRootObject ) { + if ( Math.abs( m12 ) < 0.9999999 ) { - const geometries = extractFromCache( meta.geometries ); - const materials = extractFromCache( meta.materials ); - const textures = extractFromCache( meta.textures ); - const images = extractFromCache( meta.images ); - const shapes = extractFromCache( meta.shapes ); - const skeletons = extractFromCache( meta.skeletons ); - const animations = extractFromCache( meta.animations ); + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - 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; - if ( shapes.length > 0 ) output.shapes = shapes; - if ( skeletons.length > 0 ) output.skeletons = skeletons; - if ( animations.length > 0 ) output.animations = animations; + } else { - } + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - output.object = object; + } - return output; + break; - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache( cache ) { + default: - const values = []; - for ( const key in cache ) { + console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); - const data = cache[ key ]; - delete data.metadata; - values.push( data ); + } - } + this._order = order; - return values; + if ( update === true ) this._onChangeCallback(); - } + return this; - }, + } - clone: function ( recursive ) { + setFromQuaternion( q, order, update ) { - return new this.constructor().copy( this, recursive ); + _matrix$1.makeRotationFromQuaternion( q ); - }, + return this.setFromRotationMatrix( _matrix$1, order, update ); - copy: function ( source, recursive = true ) { + } - this.name = source.name; + setFromVector3( v, order = this._order ) { - this.up.copy( source.up ); + return this.set( v.x, v.y, v.z, order ); - this.position.copy( source.position ); - this.rotation.order = source.rotation.order; - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + } - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + reorder( newOrder ) { - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + // WARNING: this discards revolution information -bhouston - this.layers.mask = source.layers.mask; - this.visible = source.visible; + _quaternion$3.setFromEuler( this ); - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + return this.setFromQuaternion( _quaternion$3, newOrder ); - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + } - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + equals( euler ) { - if ( recursive === true ) { + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - for ( let i = 0; i < source.children.length; i ++ ) { + } - const child = source.children[ i ]; - this.add( child.clone() ); + fromArray( array ) { - } + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - } + this._onChangeCallback(); return this; } -} ); - -const _vector1 = /*@__PURE__*/ new Vector3(); -const _vector2 = /*@__PURE__*/ new Vector3(); -const _normalMatrix = /*@__PURE__*/ new Matrix3(); - -class Plane { - - constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + toArray( array = [], offset = 0 ) { - // normal is assumed to be normalized + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - this.normal = normal; - this.constant = constant; + return array; } - set( normal, constant ) { + _onChange( callback ) { - this.normal.copy( normal ); - this.constant = constant; + this._onChangeCallback = callback; return this; } - setComponents( x, y, z, w ) { + _onChangeCallback() {} - this.normal.set( x, y, z ); - this.constant = w; + *[ Symbol.iterator ]() { - return this; + yield this._x; + yield this._y; + yield this._z; + yield this._order; } - setFromNormalAndCoplanarPoint( normal, point ) { + // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53 - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); + toVector3() { - return this; + console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' ); } - setFromCoplanarPoints( a, b, c ) { +} - const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); +Euler.DefaultOrder = 'XYZ'; +Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? +class Layers { - this.setFromNormalAndCoplanarPoint( normal, a ); + constructor() { - return this; + this.mask = 1 | 0; } - copy( plane ) { - - this.normal.copy( plane.normal ); - this.constant = plane.constant; + set( channel ) { - return this; + this.mask = ( 1 << channel | 0 ) >>> 0; } - normalize() { - - // Note: will lead to a divide by zero if the plane is invalid. - - const inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + enable( channel ) { - return this; + this.mask |= 1 << channel | 0; } - negate() { - - this.constant *= - 1; - this.normal.negate(); + enableAll() { - return this; + this.mask = 0xffffffff | 0; } - distanceToPoint( point ) { + toggle( channel ) { - return this.normal.dot( point ) + this.constant; + this.mask ^= 1 << channel | 0; } - distanceToSphere( sphere ) { + disable( channel ) { - return this.distanceToPoint( sphere.center ) - sphere.radius; + this.mask &= ~ ( 1 << channel | 0 ); } - projectPoint( point, target ) { + disableAll() { - if ( target === undefined ) { + this.mask = 0; - console.warn( 'THREE.Plane: .projectPoint() target is now required' ); - target = new Vector3(); + } - } + test( layers ) { - return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + return ( this.mask & layers.mask ) !== 0; } - intersectLine( line, target ) { + isEnabled( channel ) { - if ( target === undefined ) { + return ( this.mask & ( 1 << channel | 0 ) ) !== 0; - console.warn( 'THREE.Plane: .intersectLine() target is now required' ); - target = new Vector3(); + } - } +} - const direction = line.delta( _vector1 ); +let _object3DId = 0; - const denominator = this.normal.dot( direction ); +const _v1$4 = /*@__PURE__*/ new Vector3(); +const _q1 = /*@__PURE__*/ new Quaternion(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); +const _target = /*@__PURE__*/ new Vector3(); - if ( denominator === 0 ) { +const _position$3 = /*@__PURE__*/ new Vector3(); +const _scale$2 = /*@__PURE__*/ new Vector3(); +const _quaternion$2 = /*@__PURE__*/ new Quaternion(); - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { +const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 ); +const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); - return target.copy( line.start ); +const _addedEvent = { type: 'added' }; +const _removedEvent = { type: 'removed' }; - } +class Object3D extends EventDispatcher { - // Unsure if this is the correct method to handle this case. - return undefined; + constructor() { - } + super(); - const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + this.isObject3D = true; - if ( t < 0 || t > 1 ) { + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); - return undefined; + this.uuid = generateUUID(); - } + this.name = ''; + this.type = 'Object3D'; - return target.copy( direction ).multiplyScalar( t ).add( line.start ); + this.parent = null; + this.children = []; - } + this.up = Object3D.DefaultUp.clone(); - intersectsLine( line ) { + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3( 1, 1, 1 ); - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + function onRotationChange() { - const startSign = this.distanceToPoint( line.start ); - const endSign = this.distanceToPoint( line.end ); + quaternion.setFromEuler( rotation, false ); - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + } - } + function onQuaternionChange() { - intersectsBox( box ) { + rotation.setFromQuaternion( quaternion, undefined, false ); - return box.intersectsPlane( this ); + } - } + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); - intersectsSphere( sphere ) { + Object.defineProperties( this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - return sphere.intersectsPlane( this ); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - } + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - coplanarPoint( target ) { + this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer - if ( target === undefined ) { + this.layers = new Layers(); + this.visible = true; - console.warn( 'THREE.Plane: .coplanarPoint() target is now required' ); - target = new Vector3(); + this.castShadow = false; + this.receiveShadow = false; - } + this.frustumCulled = true; + this.renderOrder = 0; - return target.copy( this.normal ).multiplyScalar( - this.constant ); + this.animations = []; + + this.userData = {}; } - applyMatrix4( matrix, optionalNormalMatrix ) { + onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {} - const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {} - const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + applyMatrix4( matrix ) { - const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + if ( this.matrixAutoUpdate ) this.updateMatrix(); - this.constant = - referencePoint.dot( normal ); + this.matrix.premultiply( matrix ); - return this; + this.matrix.decompose( this.position, this.quaternion, this.scale ); } - translate( offset ) { + applyQuaternion( q ) { - this.constant -= offset.dot( this.normal ); + this.quaternion.premultiply( q ); return this; } - equals( plane ) { + setRotationFromAxisAngle( axis, angle ) { - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + // assumes axis is normalized + + this.quaternion.setFromAxisAngle( axis, angle ); } - clone() { + setRotationFromEuler( euler ) { - return new this.constructor().copy( this ); + this.quaternion.setFromEuler( euler, true ); } -} + setRotationFromMatrix( m ) { -Plane.prototype.isPlane = true; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) -const _v0$1 = /*@__PURE__*/ new Vector3(); -const _v1$3 = /*@__PURE__*/ new Vector3(); -const _v2$1 = /*@__PURE__*/ new Vector3(); -const _v3 = /*@__PURE__*/ new Vector3(); + this.quaternion.setFromRotationMatrix( m ); -const _vab = /*@__PURE__*/ new Vector3(); -const _vac = /*@__PURE__*/ new Vector3(); -const _vbc = /*@__PURE__*/ new Vector3(); -const _vap = /*@__PURE__*/ new Vector3(); -const _vbp = /*@__PURE__*/ new Vector3(); -const _vcp = /*@__PURE__*/ new Vector3(); + } -class Triangle { + setRotationFromQuaternion( q ) { - constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { + // assumes q is normalized - this.a = a; - this.b = b; - this.c = c; + this.quaternion.copy( q ); } - static getNormal( a, b, c, target ) { + rotateOnAxis( axis, angle ) { - if ( target === undefined ) { + // rotate object on axis in object space + // axis is assumed to be normalized - console.warn( 'THREE.Triangle: .getNormal() target is now required' ); - target = new Vector3(); + _q1.setFromAxisAngle( axis, angle ); - } + this.quaternion.multiply( _q1 ); - target.subVectors( c, b ); - _v0$1.subVectors( a, b ); - target.cross( _v0$1 ); + return this; - const targetLengthSq = target.lengthSq(); - if ( targetLengthSq > 0 ) { + } - return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + rotateOnWorldAxis( axis, angle ) { - } + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent - return target.set( 0, 0, 0 ); + _q1.setFromAxisAngle( axis, angle ); - } + this.quaternion.premultiply( _q1 ); - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - static getBarycoord( point, a, b, c, target ) { + return this; - _v0$1.subVectors( c, a ); - _v1$3.subVectors( b, a ); - _v2$1.subVectors( point, a ); + } - const dot00 = _v0$1.dot( _v0$1 ); - const dot01 = _v0$1.dot( _v1$3 ); - const dot02 = _v0$1.dot( _v2$1 ); - const dot11 = _v1$3.dot( _v1$3 ); - const dot12 = _v1$3.dot( _v2$1 ); + rotateX( angle ) { - const denom = ( dot00 * dot11 - dot01 * dot01 ); + return this.rotateOnAxis( _xAxis, angle ); - if ( target === undefined ) { + } - console.warn( 'THREE.Triangle: .getBarycoord() target is now required' ); - target = new Vector3(); + rotateY( angle ) { - } + return this.rotateOnAxis( _yAxis, angle ); - // collinear or singular triangle - if ( denom === 0 ) { + } - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return target.set( - 2, - 1, - 1 ); + rotateZ( angle ) { - } + return this.rotateOnAxis( _zAxis, angle ); - const invDenom = 1 / denom; - const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + } - // barycentric coordinates must always sum to 1 - return target.set( 1 - u - v, v, u ); + translateOnAxis( axis, distance ) { - } + // translate object by distance along axis in object space + // axis is assumed to be normalized - static containsPoint( point, a, b, c ) { + _v1$4.copy( axis ).applyQuaternion( this.quaternion ); - this.getBarycoord( point, a, b, c, _v3 ); + this.position.add( _v1$4.multiplyScalar( distance ) ); - return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); + return this; } - static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { + translateX( distance ) { - this.getBarycoord( point, p1, p2, p3, _v3 ); + return this.translateOnAxis( _xAxis, distance ); - target.set( 0, 0 ); - target.addScaledVector( uv1, _v3.x ); - target.addScaledVector( uv2, _v3.y ); - target.addScaledVector( uv3, _v3.z ); + } - return target; + translateY( distance ) { - } + return this.translateOnAxis( _yAxis, distance ); - static isFrontFacing( a, b, c, direction ) { + } - _v0$1.subVectors( c, b ); - _v1$3.subVectors( a, b ); + translateZ( distance ) { - // strictly front facing - return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; + return this.translateOnAxis( _zAxis, distance ); } - set( a, b, c ) { - - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + localToWorld( vector ) { - return this; + return vector.applyMatrix4( this.matrixWorld ); } - setFromPointsAndIndices( points, i0, i1, i2 ) { - - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + worldToLocal( vector ) { - return this; + return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); } - clone() { + lookAt( x, y, z ) { - return new this.constructor().copy( this ); + // This method does not support objects having non-uniformly-scaled parent(s) - } + if ( x.isVector3 ) { - copy( triangle ) { + _target.copy( x ); - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + } else { - return this; + _target.set( x, y, z ); - } + } - getArea() { + const parent = this.parent; - _v0$1.subVectors( this.c, this.b ); - _v1$3.subVectors( this.a, this.b ); + this.updateWorldMatrix( true, false ); - return _v0$1.cross( _v1$3 ).length() * 0.5; + _position$3.setFromMatrixPosition( this.matrixWorld ); - } + if ( this.isCamera || this.isLight ) { - getMidpoint( target ) { + _m1$1.lookAt( _position$3, _target, this.up ); - if ( target === undefined ) { + } else { - console.warn( 'THREE.Triangle: .getMidpoint() target is now required' ); - target = new Vector3(); + _m1$1.lookAt( _target, _position$3, this.up ); } - return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + this.quaternion.setFromRotationMatrix( _m1$1 ); - } + if ( parent ) { - getNormal( target ) { + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.invert() ); - return Triangle.getNormal( this.a, this.b, this.c, target ); + } } - getPlane( target ) { + add( object ) { - if ( target === undefined ) { + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.add( arguments[ i ] ); + + } - console.warn( 'THREE.Triangle: .getPlane() target is now required' ); - target = new Plane(); + return this; } - return target.setFromCoplanarPoints( this.a, this.b, this.c ); + if ( object === this ) { - } + console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); + return this; - getBarycoord( point, target ) { + } - return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + if ( object && object.isObject3D ) { - } + if ( object.parent !== null ) { - getUV( point, uv1, uv2, uv3, target ) { + object.parent.remove( object ); - return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); + } - } + object.parent = this; + this.children.push( object ); - containsPoint( point ) { + object.dispatchEvent( _addedEvent ); - return Triangle.containsPoint( point, this.a, this.b, this.c ); + } else { - } + console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); - isFrontFacing( direction ) { + } - return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + return this; } - intersectsBox( box ) { + remove( object ) { - return box.intersectsTriangle( this ); + if ( arguments.length > 1 ) { - } + for ( let i = 0; i < arguments.length; i ++ ) { - closestPointToPoint( p, target ) { + this.remove( arguments[ i ] ); - if ( target === undefined ) { + } - console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' ); - target = new Vector3(); + return this; } - const a = this.a, b = this.b, c = this.c; - let v, w; + const index = this.children.indexOf( object ); - // algorithm thanks to Real-Time Collision Detection by Christer Ericson, - // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., - // under the accompanying license; see chapter 5.1.5 for detailed explanation. - // basically, we're distinguishing which of the voronoi regions of the triangle - // the point lies in with the minimum amount of redundant computation. + if ( index !== - 1 ) { - _vab.subVectors( b, a ); - _vac.subVectors( c, a ); - _vap.subVectors( p, a ); - const d1 = _vab.dot( _vap ); - const d2 = _vac.dot( _vap ); - if ( d1 <= 0 && d2 <= 0 ) { + object.parent = null; + this.children.splice( index, 1 ); - // vertex region of A; barycentric coords (1, 0, 0) - return target.copy( a ); + object.dispatchEvent( _removedEvent ); } - _vbp.subVectors( p, b ); - const d3 = _vab.dot( _vbp ); - const d4 = _vac.dot( _vbp ); - if ( d3 >= 0 && d4 <= d3 ) { + return this; - // vertex region of B; barycentric coords (0, 1, 0) - return target.copy( b ); + } - } + removeFromParent() { - const vc = d1 * d4 - d3 * d2; - if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + const parent = this.parent; - v = d1 / ( d1 - d3 ); - // edge region of AB; barycentric coords (1-v, v, 0) - return target.copy( a ).addScaledVector( _vab, v ); + if ( parent !== null ) { - } + parent.remove( this ); - _vcp.subVectors( p, c ); - const d5 = _vab.dot( _vcp ); - const d6 = _vac.dot( _vcp ); - if ( d6 >= 0 && d5 <= d6 ) { + } - // vertex region of C; barycentric coords (0, 0, 1) - return target.copy( c ); + return this; - } + } - const vb = d5 * d2 - d1 * d6; - if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + clear() { - w = d2 / ( d2 - d6 ); - // edge region of AC; barycentric coords (1-w, 0, w) - return target.copy( a ).addScaledVector( _vac, w ); + for ( let i = 0; i < this.children.length; i ++ ) { - } + const object = this.children[ i ]; - const va = d3 * d6 - d5 * d4; - if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + object.parent = null; - _vbc.subVectors( c, b ); - w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); - // edge region of BC; barycentric coords (0, 1-w, w) - return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + object.dispatchEvent( _removedEvent ); } - // face region - const denom = 1 / ( va + vb + vc ); - // u = va * denom - v = vb * denom; - w = vc * denom; + this.children.length = 0; + + return this; - return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); } - equals( triangle ) { + attach( object ) { - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + // adds object as a child of this, while maintaining the object's world transform - } + // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) -} + this.updateWorldMatrix( true, false ); -let materialId = 0; + _m1$1.copy( this.matrixWorld ).invert(); -function Material() { + if ( object.parent !== null ) { - Object.defineProperty( this, 'id', { value: materialId ++ } ); + object.parent.updateWorldMatrix( true, false ); - this.uuid = MathUtils.generateUUID(); + _m1$1.multiply( object.parent.matrixWorld ); - this.name = ''; - this.type = 'Material'; + } - this.fog = true; + object.applyMatrix4( _m1$1 ); - this.blending = NormalBlending; - this.side = FrontSide; - this.vertexColors = false; + this.add( object ); - this.opacity = 1; - this.transparent = false; + object.updateWorldMatrix( false, true ); - this.blendSrc = SrcAlphaFactor; - this.blendDst = OneMinusSrcAlphaFactor; - this.blendEquation = AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + return this; - this.depthFunc = LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + } - this.stencilWriteMask = 0xff; - this.stencilFunc = AlwaysStencilFunc; - this.stencilRef = 0; - this.stencilFuncMask = 0xff; - this.stencilFail = KeepStencilOp; - this.stencilZFail = KeepStencilOp; - this.stencilZPass = KeepStencilOp; - this.stencilWrite = false; + getObjectById( id ) { - this.clippingPlanes = null; - this.clipIntersection = false; - this.clipShadows = false; + return this.getObjectByProperty( 'id', id ); - this.shadowSide = null; + } - this.colorWrite = true; + getObjectByName( name ) { - this.precision = null; // override the renderer's default precision for this material + return this.getObjectByProperty( 'name', name ); - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + } - this.dithering = false; + getObjectByProperty( name, value ) { - this.alphaTest = 0; - this.premultipliedAlpha = false; + if ( this[ name ] === value ) return this; - this.visible = true; + for ( let i = 0, l = this.children.length; i < l; i ++ ) { - this.toneMapped = true; + const child = this.children[ i ]; + const object = child.getObjectByProperty( name, value ); - this.userData = {}; + if ( object !== undefined ) { - this.version = 0; + return object; -} + } -Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + } - constructor: Material, + return undefined; - isMaterial: true, + } - onBeforeCompile: function ( /* shaderobject, renderer */ ) {}, + getWorldPosition( target ) { - customProgramCacheKey: function () { + this.updateWorldMatrix( true, false ); - return this.onBeforeCompile.toString(); + return target.setFromMatrixPosition( this.matrixWorld ); - }, + } - setValues: function ( values ) { + getWorldQuaternion( target ) { - if ( values === undefined ) return; + this.updateWorldMatrix( true, false ); - for ( const key in values ) { + this.matrixWorld.decompose( _position$3, target, _scale$2 ); - const newValue = values[ key ]; + return target; - if ( newValue === undefined ) { + } - console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); - continue; + getWorldScale( target ) { - } + this.updateWorldMatrix( true, false ); - // for backward compatability if shading is set in the constructor - if ( key === 'shading' ) { + this.matrixWorld.decompose( _position$3, _quaternion$2, target ); - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( newValue === FlatShading ) ? true : false; - continue; + return target; - } + } - const currentValue = this[ key ]; + getWorldDirection( target ) { - if ( currentValue === undefined ) { + this.updateWorldMatrix( true, false ); - console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' ); - continue; + const e = this.matrixWorld.elements; - } + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); - if ( currentValue && currentValue.isColor ) { + } - currentValue.set( newValue ); + raycast( /* raycaster, intersects */ ) {} - } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + traverse( callback ) { - currentValue.copy( newValue ); + callback( this ); - } else { + const children = this.children; - this[ key ] = newValue; + for ( let i = 0, l = children.length; i < l; i ++ ) { - } + children[ i ].traverse( callback ); } - }, - - toJSON: function ( meta ) { + } - const isRoot = ( meta === undefined || typeof meta === 'string' ); + traverseVisible( callback ) { - if ( isRoot ) { + if ( this.visible === false ) return; - meta = { - textures: {}, - images: {} - }; + callback( this ); - } + const children = this.children; - const data = { - metadata: { - version: 4.5, - type: 'Material', - generator: 'Material.toJSON' - } - }; + for ( let i = 0, l = children.length; i < l; i ++ ) { - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + children[ i ].traverseVisible( callback ); - if ( this.name !== '' ) data.name = this.name; + } - 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; + traverseAncestors( callback ) { - if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex(); - if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); - if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + const parent = this.parent; - if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); - if ( this.shininess !== undefined ) data.shininess = this.shininess; - if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; - if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; + if ( parent !== null ) { - if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { + callback( parent ); - data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; + parent.traverseAncestors( callback ); } - if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { + } - data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; + updateMatrix() { - } + this.matrix.compose( this.position, this.quaternion, this.scale ); - if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + this.matrixWorldNeedsUpdate = true; - data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; - data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } - } + updateMatrixWorld( force ) { - if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid; - if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( this.matrixAutoUpdate ) this.updateMatrix(); - if ( this.lightMap && this.lightMap.isTexture ) { + if ( this.matrixWorldNeedsUpdate || force ) { - data.lightMap = this.lightMap.toJSON( meta ).uuid; - data.lightMapIntensity = this.lightMapIntensity; + if ( this.parent === null ) { - } + this.matrixWorld.copy( this.matrix ); - if ( this.aoMap && this.aoMap.isTexture ) { + } else { - data.aoMap = this.aoMap.toJSON( meta ).uuid; - data.aoMapIntensity = this.aoMapIntensity; + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - } + } - if ( this.bumpMap && this.bumpMap.isTexture ) { + this.matrixWorldNeedsUpdate = false; - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + force = true; } - if ( this.normalMap && this.normalMap.isTexture ) { + // update children - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalMapType = this.normalMapType; - data.normalScale = this.normalScale.toArray(); + const children = this.children; - } + for ( let i = 0, l = children.length; i < l; i ++ ) { - if ( this.displacementMap && this.displacementMap.isTexture ) { + const child = children[ i ]; - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + if ( child.matrixWorldAutoUpdate === true || force === true ) { + + child.updateMatrixWorld( force ); + + } } - 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; + updateWorldMatrix( updateParents, updateChildren ) { - if ( this.envMap && this.envMap.isTexture ) { + const parent = this.parent; - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap - data.refractionRatio = this.refractionRatio; + if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) { - if ( this.combine !== undefined ) data.combine = this.combine; - if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + parent.updateWorldMatrix( true, false ); } - if ( this.gradientMap && this.gradientMap.isTexture ) { + if ( this.matrixAutoUpdate ) this.updateMatrix(); - data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); } - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + // update children - if ( this.blending !== NormalBlending ) data.blending = this.blending; - if ( this.side !== FrontSide ) data.side = this.side; - if ( this.vertexColors ) data.vertexColors = true; + if ( updateChildren === true ) { - if ( this.opacity < 1 ) data.opacity = this.opacity; - if ( this.transparent === true ) data.transparent = this.transparent; + const children = this.children; - data.depthFunc = this.depthFunc; - data.depthTest = this.depthTest; - data.depthWrite = this.depthWrite; + for ( let i = 0, l = children.length; i < l; i ++ ) { - data.stencilWrite = this.stencilWrite; - data.stencilWriteMask = this.stencilWriteMask; - data.stencilFunc = this.stencilFunc; - data.stencilRef = this.stencilRef; - data.stencilFuncMask = this.stencilFuncMask; - data.stencilFail = this.stencilFail; - data.stencilZFail = this.stencilZFail; - data.stencilZPass = this.stencilZPass; + const child = children[ i ]; - // rotation (SpriteMaterial) - if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation; + if ( child.matrixWorldAutoUpdate === true ) { - if ( this.polygonOffset === true ) data.polygonOffset = true; - if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; - if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; + child.updateWorldMatrix( false, true ); - if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth; - if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; - if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; - if ( this.scale !== undefined ) data.scale = this.scale; + } - if ( this.dithering === true ) data.dithering = true; + } - 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; - if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; - if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; + } - if ( this.morphTargets === true ) data.morphTargets = true; - if ( this.morphNormals === true ) data.morphNormals = true; - if ( this.skinning === true ) data.skinning = true; + toJSON( meta ) { - if ( this.flatShading === true ) data.flatShading = this.flatShading; + // meta is a string when called from JSON.stringify + const isRootObject = ( meta === undefined || typeof meta === 'string' ); - if ( this.visible === false ) data.visible = false; + const output = {}; - if ( this.toneMapped === false ) data.toneMapped = false; + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; - // TODO: Copied from Object3D.toJSON + output.metadata = { + version: 4.5, + type: 'Object', + generator: 'Object3D.toJSON' + }; - function extractFromCache( cache ) { + } - const values = []; + // standard Object3D serialization - for ( const key in cache ) { + const object = {}; - const data = cache[ key ]; - delete data.metadata; - values.push( data ); + object.uuid = this.uuid; + object.type = this.type; - } + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - return values; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); - } + if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; - if ( isRoot ) { + // object specific properties - const textures = extractFromCache( meta.textures ); - const images = extractFromCache( meta.images ); + if ( this.isInstancedMesh ) { - if ( textures.length > 0 ) data.textures = textures; - if ( images.length > 0 ) data.images = images; + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON(); } - return data; - - }, + // - clone: function () { + function serialize( library, element ) { - return new this.constructor().copy( this ); + if ( library[ element.uuid ] === undefined ) { - }, + library[ element.uuid ] = element.toJSON( meta ); - copy: function ( source ) { + } - this.name = source.name; + return element.uuid; - this.fog = source.fog; + } - this.blending = source.blending; - this.side = source.side; - this.vertexColors = source.vertexColors; + if ( this.isScene ) { - this.opacity = source.opacity; - this.transparent = source.transparent; + if ( this.background ) { - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + if ( this.background.isColor ) { - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + object.background = this.background.toJSON(); - this.stencilWriteMask = source.stencilWriteMask; - this.stencilFunc = source.stencilFunc; - this.stencilRef = source.stencilRef; - this.stencilFuncMask = source.stencilFuncMask; - this.stencilFail = source.stencilFail; - this.stencilZFail = source.stencilZFail; - this.stencilZPass = source.stencilZPass; - this.stencilWrite = source.stencilWrite; + } else if ( this.background.isTexture ) { - const srcPlanes = source.clippingPlanes; - let dstPlanes = null; + object.background = this.background.toJSON( meta ).uuid; - if ( srcPlanes !== null ) { + } - const n = srcPlanes.length; - dstPlanes = new Array( n ); + } - for ( let i = 0; i !== n; ++ i ) { + if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) { - dstPlanes[ i ] = srcPlanes[ i ].clone(); + object.environment = this.environment.toJSON( meta ).uuid; } - } + } else if ( this.isMesh || this.isLine || this.isPoints ) { - this.clippingPlanes = dstPlanes; - this.clipIntersection = source.clipIntersection; - this.clipShadows = source.clipShadows; + object.geometry = serialize( meta.geometries, this.geometry ); - this.shadowSide = source.shadowSide; + const parameters = this.geometry.parameters; - this.colorWrite = source.colorWrite; + if ( parameters !== undefined && parameters.shapes !== undefined ) { - this.precision = source.precision; + const shapes = parameters.shapes; - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + if ( Array.isArray( shapes ) ) { - this.dithering = source.dithering; + for ( let i = 0, l = shapes.length; i < l; i ++ ) { - this.alphaTest = source.alphaTest; - this.premultipliedAlpha = source.premultipliedAlpha; + const shape = shapes[ i ]; - this.visible = source.visible; + serialize( meta.shapes, shape ); - this.toneMapped = source.toneMapped; + } - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + } else { - return this; + serialize( meta.shapes, shapes ); - }, + } - dispose: function () { + } - this.dispatchEvent( { type: 'dispose' } ); + } - } + if ( this.isSkinnedMesh ) { -} ); + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); -Object.defineProperty( Material.prototype, 'needsUpdate', { + if ( this.skeleton !== undefined ) { - set: function ( value ) { + serialize( meta.skeletons, this.skeleton ); - if ( value === true ) this.version ++; + object.skeleton = this.skeleton.uuid; - } + } -} ); + } -const _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, 'rebeccapurple': 0x663399, '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 }; + if ( this.material !== undefined ) { -const _hslA = { h: 0, s: 0, l: 0 }; -const _hslB = { h: 0, s: 0, l: 0 }; + if ( Array.isArray( this.material ) ) { -function hue2rgb( p, q, t ) { + const uuids = []; - 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; + for ( let i = 0, l = this.material.length; i < l; i ++ ) { -} + uuids.push( serialize( meta.materials, this.material[ i ] ) ); -function SRGBToLinear( c ) { + } - return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + object.material = uuids; -} + } else { -function LinearToSRGB( c ) { + object.material = serialize( meta.materials, this.material ); - return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; + } -} + } -class Color { + // - constructor( r, g, b ) { + if ( this.children.length > 0 ) { - if ( g === undefined && b === undefined ) { + object.children = []; - // r is THREE.Color, hex or string - return this.set( r ); + for ( let i = 0; i < this.children.length; i ++ ) { - } + object.children.push( this.children[ i ].toJSON( meta ).object ); - return this.setRGB( r, g, b ); + } - } + } - set( value ) { + // - if ( value && value.isColor ) { + if ( this.animations.length > 0 ) { - this.copy( value ); + object.animations = []; - } else if ( typeof value === 'number' ) { + for ( let i = 0; i < this.animations.length; i ++ ) { - this.setHex( value ); + const animation = this.animations[ i ]; - } else if ( typeof value === 'string' ) { + object.animations.push( serialize( meta.animations, animation ) ); - this.setStyle( value ); + } } - return this; + if ( isRootObject ) { - } + const geometries = extractFromCache( meta.geometries ); + const materials = extractFromCache( meta.materials ); + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + const shapes = extractFromCache( meta.shapes ); + const skeletons = extractFromCache( meta.skeletons ); + const animations = extractFromCache( meta.animations ); + const nodes = extractFromCache( meta.nodes ); - setScalar( scalar ) { + 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; + if ( shapes.length > 0 ) output.shapes = shapes; + if ( skeletons.length > 0 ) output.skeletons = skeletons; + if ( animations.length > 0 ) output.animations = animations; + if ( nodes.length > 0 ) output.nodes = nodes; - this.r = scalar; - this.g = scalar; - this.b = scalar; + } - return this; + output.object = object; - } + return output; + + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { - setHex( hex ) { + const values = []; + for ( const key in cache ) { - hex = Math.floor( hex ); + const data = cache[ key ]; + delete data.metadata; + values.push( data ); - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + } - return this; + return values; - } + } - setRGB( r, g, b ) { + } - this.r = r; - this.g = g; - this.b = b; + clone( recursive ) { - return this; + return new this.constructor().copy( this, recursive ); } - setHSL( h, s, l ) { - - // h,s,l ranges are in 0.0 - 1.0 - h = MathUtils.euclideanModulo( h, 1 ); - s = MathUtils.clamp( s, 0, 1 ); - l = MathUtils.clamp( l, 0, 1 ); + copy( source, recursive = true ) { - if ( s === 0 ) { + this.name = source.name; - this.r = this.g = this.b = l; + this.up.copy( source.up ); - } else { + this.position.copy( source.position ); + this.rotation.order = source.rotation.order; + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - const q = ( 2 * l ) - p; + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - } + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; - return this; + this.layers.mask = source.layers.mask; + this.visible = source.visible; - } + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - setStyle( style ) { + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - function handleAlpha( string ) { + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - if ( string === undefined ) return; + if ( recursive === true ) { - if ( parseFloat( string ) < 1 ) { + for ( let i = 0; i < source.children.length; i ++ ) { - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + const child = source.children[ i ]; + this.add( child.clone() ); } } + return this; - let m; + } - if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { +} - // rgb / hsl +Object3D.DefaultUp = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +Object3D.DefaultMatrixAutoUpdate = true; +Object3D.DefaultMatrixWorldAutoUpdate = true; - let color; - const name = m[ 1 ]; - const components = m[ 2 ]; +const _v0$1 = /*@__PURE__*/ new Vector3(); +const _v1$3 = /*@__PURE__*/ new Vector3(); +const _v2$2 = /*@__PURE__*/ new Vector3(); +const _v3$1 = /*@__PURE__*/ new Vector3(); - switch ( name ) { +const _vab = /*@__PURE__*/ new Vector3(); +const _vac = /*@__PURE__*/ new Vector3(); +const _vbc = /*@__PURE__*/ new Vector3(); +const _vap = /*@__PURE__*/ new Vector3(); +const _vbp = /*@__PURE__*/ new Vector3(); +const _vcp = /*@__PURE__*/ new Vector3(); - case 'rgb': - case 'rgba': +class Triangle { - if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { - // 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; + this.a = a; + this.b = b; + this.c = c; - handleAlpha( color[ 4 ] ); + } - return this; + static getNormal( a, b, c, target ) { - } + target.subVectors( c, b ); + _v0$1.subVectors( a, b ); + target.cross( _v0$1 ); - if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + const targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { - // 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; + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); - handleAlpha( color[ 4 ] ); + } - return this; + return target.set( 0, 0, 0 ); - } + } - break; + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + static getBarycoord( point, a, b, c, target ) { - case 'hsl': - case 'hsla': + _v0$1.subVectors( c, a ); + _v1$3.subVectors( b, a ); + _v2$2.subVectors( point, a ); - if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + const dot00 = _v0$1.dot( _v0$1 ); + const dot01 = _v0$1.dot( _v1$3 ); + const dot02 = _v0$1.dot( _v2$2 ); + const dot11 = _v1$3.dot( _v1$3 ); + const dot12 = _v1$3.dot( _v2$2 ); - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - const h = parseFloat( color[ 1 ] ) / 360; - const s = parseInt( color[ 2 ], 10 ) / 100; - const l = parseInt( color[ 3 ], 10 ) / 100; + const denom = ( dot00 * dot11 - dot01 * dot01 ); - handleAlpha( color[ 4 ] ); + // collinear or singular triangle + if ( denom === 0 ) { - return this.setHSL( h, s, l ); + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return target.set( - 2, - 1, - 1 ); - } + } - break; + const invDenom = 1 / denom; + const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - } + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); - } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { + } - // hex color + static containsPoint( point, a, b, c ) { - const hex = m[ 1 ]; - const size = hex.length; + this.getBarycoord( point, a, b, c, _v3$1 ); - if ( size === 3 ) { + return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); - // #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; + } - return this; + static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { - } else if ( size === 6 ) { + this.getBarycoord( point, p1, p2, p3, _v3$1 ); - // #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; + target.set( 0, 0 ); + target.addScaledVector( uv1, _v3$1.x ); + target.addScaledVector( uv2, _v3$1.y ); + target.addScaledVector( uv3, _v3$1.z ); - return this; + return target; - } + } - } + static isFrontFacing( a, b, c, direction ) { - if ( style && style.length > 0 ) { + _v0$1.subVectors( c, b ); + _v1$3.subVectors( a, b ); - return this.setColorName( style ); + // strictly front facing + return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; - } + } + + set( a, b, c ) { + + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); return this; } - setColorName( style ) { - - // color keywords - const hex = _colorKeywords[ style ]; + setFromPointsAndIndices( points, i0, i1, i2 ) { - if ( hex !== undefined ) { + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); - // red - this.setHex( hex ); + return this; - } else { + } - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + setFromAttributeAndIndices( attribute, i0, i1, i2 ) { - } + this.a.fromBufferAttribute( attribute, i0 ); + this.b.fromBufferAttribute( attribute, i1 ); + this.c.fromBufferAttribute( attribute, i2 ); return this; @@ -8569,631 +8482,813 @@ class Color { clone() { - return new this.constructor( this.r, this.g, this.b ); + return new this.constructor().copy( this ); } - copy( color ) { + copy( triangle ) { - this.r = color.r; - this.g = color.g; - this.b = color.b; + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); return this; } - copyGammaToLinear( color, gammaFactor = 2.0 ) { + getArea() { - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + _v0$1.subVectors( this.c, this.b ); + _v1$3.subVectors( this.a, this.b ); - return this; + return _v0$1.cross( _v1$3 ).length() * 0.5; } - copyLinearToGamma( color, gammaFactor = 2.0 ) { - - const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + getMidpoint( target ) { - return this; + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); } - convertGammaToLinear( gammaFactor ) { - - this.copyGammaToLinear( this, gammaFactor ); + getNormal( target ) { - return this; + return Triangle.getNormal( this.a, this.b, this.c, target ); } - convertLinearToGamma( gammaFactor ) { - - this.copyLinearToGamma( this, gammaFactor ); + getPlane( target ) { - return this; + return target.setFromCoplanarPoints( this.a, this.b, this.c ); } - copySRGBToLinear( color ) { - - this.r = SRGBToLinear( color.r ); - this.g = SRGBToLinear( color.g ); - this.b = SRGBToLinear( color.b ); + getBarycoord( point, target ) { - return this; + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); } - copyLinearToSRGB( color ) { - - this.r = LinearToSRGB( color.r ); - this.g = LinearToSRGB( color.g ); - this.b = LinearToSRGB( color.b ); + getUV( point, uv1, uv2, uv3, target ) { - return this; + return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); } - convertSRGBToLinear() { - - this.copySRGBToLinear( this ); + containsPoint( point ) { - return this; + return Triangle.containsPoint( point, this.a, this.b, this.c ); } - convertLinearToSRGB() { - - this.copyLinearToSRGB( this ); + isFrontFacing( direction ) { - return this; + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); } - getHex() { + intersectsBox( box ) { - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + return box.intersectsTriangle( this ); } - getHexString() { + closestPointToPoint( p, target ) { + + const a = this.a, b = this.b, c = this.c; + let v, w; - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. - } + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + const d1 = _vab.dot( _vap ); + const d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { - getHSL( target ) { + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); - // h,s,l ranges are in 0.0 - 1.0 + } - if ( target === undefined ) { + _vbp.subVectors( p, b ); + const d3 = _vab.dot( _vbp ); + const d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { - console.warn( 'THREE.Color: .getHSL() target is now required' ); - target = { h: 0, s: 0, l: 0 }; + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); } - const r = this.r, g = this.g, b = this.b; - - const max = Math.max( r, g, b ); - const min = Math.min( r, g, b ); + const vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { - let hue, saturation; - const lightness = ( min + max ) / 2.0; + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); - if ( min === max ) { + } - hue = 0; - saturation = 0; + _vcp.subVectors( p, c ); + const d5 = _vab.dot( _vcp ); + const d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { - } else { + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); - const delta = max - min; + } - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + const vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { - switch ( max ) { + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); - 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; + } - } + const va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { - hue /= 6; + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC } - target.h = hue; - target.s = saturation; - target.l = lightness; + // face region + const denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; - return target; + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); } - getStyle() { + equals( triangle ) { - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); } - offsetHSL( h, s, l ) { +} - this.getHSL( _hslA ); +let materialId = 0; - _hslA.h += h; _hslA.s += s; _hslA.l += l; +class Material extends EventDispatcher { - this.setHSL( _hslA.h, _hslA.s, _hslA.l ); + constructor() { - return this; + super(); - } + this.isMaterial = true; - add( color ) { + Object.defineProperty( this, 'id', { value: materialId ++ } ); - this.r += color.r; - this.g += color.g; - this.b += color.b; + this.uuid = generateUUID(); - return this; + this.name = ''; + this.type = 'Material'; - } + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; - addColors( color1, color2 ) { + this.opacity = 1; + this.transparent = false; - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - return this; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - } + this.stencilWriteMask = 0xff; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 0xff; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; - addScalar( s ) { + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; - this.r += s; - this.g += s; - this.b += s; + this.shadowSide = null; - return this; + this.colorWrite = true; - } + this.precision = null; // override the renderer's default precision for this material - sub( color ) { + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - 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 ); + this.dithering = false; - return this; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; - } + this.visible = true; - multiply( color ) { + this.toneMapped = true; - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + this.userData = {}; - return this; + this.version = 0; - } + this._alphaTest = 0; - multiplyScalar( s ) { + } - this.r *= s; - this.g *= s; - this.b *= s; + get alphaTest() { - return this; + return this._alphaTest; } - lerp( color, alpha ) { - - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; - - return this; + set alphaTest( value ) { - } + if ( this._alphaTest > 0 !== value > 0 ) { - lerpColors( color1, color2, alpha ) { + this.version ++; - this.r = color1.r + ( color2.r - color1.r ) * alpha; - this.g = color1.g + ( color2.g - color1.g ) * alpha; - this.b = color1.b + ( color2.b - color1.b ) * alpha; + } - return this; + this._alphaTest = value; } - lerpHSL( color, alpha ) { + onBuild( /* shaderobject, renderer */ ) {} - this.getHSL( _hslA ); - color.getHSL( _hslB ); + onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {} - const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha ); - const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha ); - const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha ); + onBeforeCompile( /* shaderobject, renderer */ ) {} - this.setHSL( h, s, l ); + customProgramCacheKey() { - return this; + return this.onBeforeCompile.toString(); } - equals( c ) { - - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - - } + setValues( values ) { - fromArray( array, offset = 0 ) { + if ( values === undefined ) return; - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + for ( const key in values ) { - return this; + const newValue = values[ key ]; - } + if ( newValue === undefined ) { - toArray( array = [], offset = 0 ) { + console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); + continue; - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + } - return array; + const currentValue = this[ key ]; - } + if ( currentValue === undefined ) { - fromBufferAttribute( attribute, index ) { + console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' ); + continue; - this.r = attribute.getX( index ); - this.g = attribute.getY( index ); - this.b = attribute.getZ( index ); + } - if ( attribute.normalized === true ) { + if ( currentValue && currentValue.isColor ) { - // assuming Uint8Array + currentValue.set( newValue ); - this.r /= 255; - this.g /= 255; - this.b /= 255; + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { - } + currentValue.copy( newValue ); - return this; + } else { - } + this[ key ] = newValue; - toJSON() { + } - return this.getHex(); + } } -} - -Color.NAMES = _colorKeywords; - -Color.prototype.isColor = true; -Color.prototype.r = 1; -Color.prototype.g = 1; -Color.prototype.b = 1; + toJSON( meta ) { -/** - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: - * } - */ + const isRootObject = ( meta === undefined || typeof meta === 'string' ); -class MeshBasicMaterial extends Material { + if ( isRootObject ) { - constructor( parameters ) { + meta = { + textures: {}, + images: {} + }; - super(); + } - this.type = 'MeshBasicMaterial'; + const data = { + metadata: { + version: 4.5, + type: 'Material', + generator: 'Material.toJSON' + } + }; - this.color = new Color( 0xffffff ); // emissive + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - this.map = null; + if ( this.name !== '' ) data.name = this.name; - this.lightMap = null; - this.lightMapIntensity = 1.0; + if ( this.color && this.color.isColor ) data.color = this.color.getHex(); - this.aoMap = null; - this.aoMapIntensity = 1.0; + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - this.specularMap = null; + if ( this.sheen !== undefined ) data.sheen = this.sheen; + if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); + if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; - this.alphaMap = null; + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; + if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; - this.skinning = false; - this.morphTargets = false; + } - this.setValues( parameters ); + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { - } + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; - copy( source ) { + } - super.copy( source ); + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { - this.color.copy( source.color ); + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); - this.map = source.map; + } - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { - this.specularMap = source.specularMap; + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; - this.alphaMap = source.alphaMap; + } - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + } - return this; + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.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; + data.lightMapIntensity = this.lightMapIntensity; -MeshBasicMaterial.prototype.isMeshBasicMaterial = true; + } -const _vector$3 = new Vector3(); -const _vector2$1 = new Vector2(); + if ( this.aoMap && this.aoMap.isTexture ) { -function BufferAttribute( array, itemSize, normalized ) { + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; - if ( Array.isArray( array ) ) { + } - throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + if ( this.bumpMap && this.bumpMap.isTexture ) { - } + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - this.name = ''; + } - this.array = array; - this.itemSize = itemSize; - this.count = array !== undefined ? array.length / itemSize : 0; - this.normalized = normalized === true; + if ( this.normalMap && this.normalMap.isTexture ) { - this.usage = StaticDrawUsage; - this.updateRange = { offset: 0, count: - 1 }; + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); - this.version = 0; + } -} + if ( this.displacementMap && this.displacementMap.isTexture ) { -Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', { + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; - set: function ( value ) { + } - if ( value === true ) this.version ++; + 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; + if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid; + if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid; -} ); + if ( this.envMap && this.envMap.isTexture ) { -Object.assign( BufferAttribute.prototype, { + data.envMap = this.envMap.toJSON( meta ).uuid; - isBufferAttribute: true, + if ( this.combine !== undefined ) data.combine = this.combine; - onUploadCallback: function () {}, + } - setUsage: function ( value ) { + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; + if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; - this.usage = value; + if ( this.gradientMap && this.gradientMap.isTexture ) { - return this; + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; - }, + } - copy: function ( source ) { + if ( this.transmission !== undefined ) data.transmission = this.transmission; + if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid; + if ( this.thickness !== undefined ) data.thickness = this.thickness; + if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid; + if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance; + if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex(); - this.name = source.name; - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; - this.count = source.count; - this.normalized = source.normalized; + if ( this.size !== undefined ) data.size = this.size; + if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - this.usage = source.usage; + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors ) data.vertexColors = true; - return this; + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; - }, + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; + data.colorWrite = this.colorWrite; - copyAt: function ( index1, attribute, index2 ) { + data.stencilWrite = this.stencilWrite; + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; - index1 *= this.itemSize; - index2 *= attribute.itemSize; + // rotation (SpriteMaterial) + if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation; - for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + if ( this.polygonOffset === true ) data.polygonOffset = true; + if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; + if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; - } + if ( this.dithering === true ) data.dithering = true; - return this; + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - }, + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; - copyArray: function ( array ) { + if ( this.flatShading === true ) data.flatShading = this.flatShading; - this.array.set( array ); + if ( this.visible === false ) data.visible = false; - return this; + if ( this.toneMapped === false ) data.toneMapped = false; - }, + if ( this.fog === false ) data.fog = false; - copyColorsArray: function ( colors ) { + if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; - const array = this.array; - let offset = 0; + // TODO: Copied from Object3D.toJSON - for ( let i = 0, l = colors.length; i < l; i ++ ) { + function extractFromCache( cache ) { - let color = colors[ i ]; + const values = []; - if ( color === undefined ) { + for ( const key in cache ) { - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new Color(); + const data = cache[ key ]; + delete data.metadata; + values.push( data ); } - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + return values; } - return this; - - }, + if ( isRootObject ) { - copyVector2sArray: function ( vectors ) { + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); - const array = this.array; - let offset = 0; + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - for ( let i = 0, l = vectors.length; i < l; i ++ ) { + } - let vector = vectors[ i ]; + return data; - if ( vector === undefined ) { + } - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new Vector2(); + clone() { - } + return new this.constructor().copy( this ); - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + } - } + copy( source ) { - return this; + this.name = source.name; - }, + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + + this.opacity = source.opacity; + this.transparent = source.transparent; + + 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; - copyVector3sArray: function ( vectors ) { + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; - const array = this.array; - let offset = 0; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; - for ( let i = 0, l = vectors.length; i < l; i ++ ) { + if ( srcPlanes !== null ) { - let vector = vectors[ i ]; + const n = srcPlanes.length; + dstPlanes = new Array( n ); - if ( vector === undefined ) { + for ( let i = 0; i !== n; ++ i ) { - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new Vector3(); + dstPlanes[ i ] = srcPlanes[ i ].clone(); } - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + } + + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + + this.shadowSide = source.shadowSide; + + this.colorWrite = source.colorWrite; + + this.precision = source.precision; + + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + + this.dithering = source.dithering; + + this.alphaTest = source.alphaTest; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + + this.visible = source.visible; + + this.toneMapped = source.toneMapped; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +class MeshBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshBasicMaterial = true; + + this.type = 'MeshBasicMaterial'; + + this.color = new Color( 0xffffff ); // emissive + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + 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.fog = source.fog; + + return this; + + } + +} + +const _vector$9 = /*@__PURE__*/ new Vector3(); +const _vector2$1 = /*@__PURE__*/ new Vector2(); + +class BufferAttribute { + + constructor( array, itemSize, normalized ) { + + if ( Array.isArray( array ) ) { + + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); } + this.isBufferAttribute = true; + + this.name = ''; + + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized === true; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + return this; - }, + } - copyVector4sArray: function ( vectors ) { + copy( source ) { - const array = this.array; - let offset = 0; + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; - for ( let i = 0, l = vectors.length; i < l; i ++ ) { + this.usage = source.usage; - let vector = vectors[ i ]; + return this; - if ( vector === undefined ) { + } - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new Vector4(); + copyAt( index1, attribute, index2 ) { - } + index1 *= this.itemSize; + index2 *= attribute.itemSize; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; } return this; - }, + } + + copyArray( array ) { + + this.array.set( array ); - applyMatrix3: function ( m ) { + return this; + + } + + applyMatrix3( m ) { if ( this.itemSize === 2 ) { @@ -9210,10 +9305,10 @@ Object.assign( BufferAttribute.prototype, { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.fromBufferAttribute( this, i ); - _vector$3.applyMatrix3( m ); + _vector$9.fromBufferAttribute( this, i ); + _vector$9.applyMatrix3( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } @@ -9221,153 +9316,196 @@ Object.assign( BufferAttribute.prototype, { return this; - }, + } - applyMatrix4: function ( m ) { + applyMatrix4( m ) { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.x = this.getX( i ); - _vector$3.y = this.getY( i ); - _vector$3.z = this.getZ( i ); + _vector$9.fromBufferAttribute( this, i ); - _vector$3.applyMatrix4( m ); + _vector$9.applyMatrix4( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } return this; - }, + } - applyNormalMatrix: function ( m ) { + applyNormalMatrix( m ) { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.x = this.getX( i ); - _vector$3.y = this.getY( i ); - _vector$3.z = this.getZ( i ); + _vector$9.fromBufferAttribute( this, i ); - _vector$3.applyNormalMatrix( m ); + _vector$9.applyNormalMatrix( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } return this; - }, + } - transformDirection: function ( m ) { + transformDirection( m ) { for ( let i = 0, l = this.count; i < l; i ++ ) { - _vector$3.x = this.getX( i ); - _vector$3.y = this.getY( i ); - _vector$3.z = this.getZ( i ); + _vector$9.fromBufferAttribute( this, i ); - _vector$3.transformDirection( m ); + _vector$9.transformDirection( m ); - this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); } return this; - }, + } - set: function ( value, offset = 0 ) { + set( value, offset = 0 ) { + // Matching BufferAttribute constructor, do not normalize the array. this.array.set( value, offset ); return this; - }, + } - getX: function ( index ) { + getX( index ) { - return this.array[ index * this.itemSize ]; + let x = this.array[ index * this.itemSize ]; - }, + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + setX( index, x ) { - setX: function ( index, x ) { + if ( this.normalized ) x = normalize( x, this.array ); this.array[ index * this.itemSize ] = x; return this; - }, + } - getY: function ( index ) { + getY( index ) { - return this.array[ index * this.itemSize + 1 ]; + let y = this.array[ index * this.itemSize + 1 ]; - }, + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + setY( index, y ) { - setY: function ( index, y ) { + if ( this.normalized ) y = normalize( y, this.array ); this.array[ index * this.itemSize + 1 ] = y; return this; - }, + } - getZ: function ( index ) { + getZ( index ) { - return this.array[ index * this.itemSize + 2 ]; + let z = this.array[ index * this.itemSize + 2 ]; - }, + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } - setZ: function ( index, z ) { + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); this.array[ index * this.itemSize + 2 ] = z; return this; - }, + } - getW: function ( index ) { + getW( index ) { - return this.array[ index * this.itemSize + 3 ]; + let w = this.array[ index * this.itemSize + 3 ]; - }, + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setW( index, w ) { - setW: function ( index, w ) { + if ( this.normalized ) w = normalize( w, this.array ); this.array[ index * this.itemSize + 3 ] = w; return this; - }, + } - setXY: function ( index, x, y ) { + setXY( index, x, y ) { index *= this.itemSize; + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; return this; - }, + } - setXYZ: function ( index, x, y, z ) { + setXYZ( index, x, y, z ) { index *= this.itemSize; + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; return this; - }, + } - setXYZW: function ( index, x, y, z, w ) { + setXYZW( index, x, y, z, w ) { index *= this.itemSize; + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; @@ -9375,221 +9513,224 @@ Object.assign( BufferAttribute.prototype, { return this; - }, + } - onUpload: function ( callback ) { + onUpload( callback ) { this.onUploadCallback = callback; return this; - }, + } - clone: function () { + clone() { return new this.constructor( this.array, this.itemSize ).copy( this ); - }, + } - toJSON: function () { + toJSON() { - return { + const data = { itemSize: this.itemSize, type: this.array.constructor.name, - array: Array.prototype.slice.call( this.array ), + array: Array.from( this.array ), normalized: this.normalized }; - } + if ( this.name !== '' ) data.name = this.name; + if ( this.usage !== StaticDrawUsage ) data.usage = this.usage; + if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange; -} ); + return data; -// + } -function Int8BufferAttribute( array, itemSize, normalized ) { + // @deprecated - BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized ); + copyColorsArray() { -} + console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' ); -Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Int8BufferAttribute.prototype.constructor = Int8BufferAttribute; + } + copyVector2sArray() { -function Uint8BufferAttribute( array, itemSize, normalized ) { + console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' ); - BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized ); + } -} + copyVector3sArray() { -Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute; + console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' ); + } + + copyVector4sArray() { -function Uint8ClampedBufferAttribute( array, itemSize, normalized ) { + console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' ); - BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized ); + } } -Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute; +// + +class Int8BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Int16BufferAttribute( array, itemSize, normalized ) { + super( new Int8Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized ); + } } -Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Int16BufferAttribute.prototype.constructor = Int16BufferAttribute; +class Uint8BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Uint16BufferAttribute( array, itemSize, normalized ) { + super( new Uint8Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); + } } -Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute; +class Uint8ClampedBufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Int32BufferAttribute( array, itemSize, normalized ) { + super( new Uint8ClampedArray( array ), itemSize, normalized ); - BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized ); + } } -Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Int32BufferAttribute.prototype.constructor = Int32BufferAttribute; +class Int16BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Uint32BufferAttribute( array, itemSize, normalized ) { + super( new Int16Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized ); + } } -Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute; +class Uint16BufferAttribute extends BufferAttribute { -function Float16BufferAttribute( array, itemSize, normalized ) { + constructor( array, itemSize, normalized ) { - BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); + super( new Uint16Array( array ), itemSize, normalized ); + + } } -Float16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Float16BufferAttribute.prototype.constructor = Float16BufferAttribute; -Float16BufferAttribute.prototype.isFloat16BufferAttribute = true; +class Int32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { -function Float32BufferAttribute( array, itemSize, normalized ) { + super( new Int32Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized ); + } } -Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; +class Uint32BufferAttribute extends BufferAttribute { + constructor( array, itemSize, normalized ) { -function Float64BufferAttribute( array, itemSize, normalized ) { + super( new Uint32Array( array ), itemSize, normalized ); - BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized ); + } } -Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); -Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; +class Float16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { -function arrayMax( array ) { + super( new Uint16Array( array ), itemSize, normalized ); - if ( array.length === 0 ) return - Infinity; + this.isFloat16BufferAttribute = true; - let max = array[ 0 ]; + } - for ( let i = 1, l = array.length; i < l; ++ i ) { +} - if ( array[ i ] > max ) max = array[ i ]; - } +class Float32BufferAttribute extends BufferAttribute { - return max; + constructor( array, itemSize, normalized ) { + + super( new Float32Array( array ), itemSize, normalized ); + + } } -const TYPED_ARRAYS = { - Int8Array: Int8Array, - Uint8Array: Uint8Array, - Uint8ClampedArray: Uint8ClampedArray, - Int16Array: Int16Array, - Uint16Array: Uint16Array, - Int32Array: Int32Array, - Uint32Array: Uint32Array, - Float32Array: Float32Array, - Float64Array: Float64Array -}; +class Float64BufferAttribute extends BufferAttribute { -function getTypedArray( type, buffer ) { + constructor( array, itemSize, normalized ) { - return new TYPED_ARRAYS[ type ]( buffer ); + super( new Float64Array( array ), itemSize, normalized ); + + } } -let _id = 0; +let _id$1 = 0; -const _m1$2 = new Matrix4(); -const _obj = new Object3D(); -const _offset = new Vector3(); -const _box$2 = new Box3(); -const _boxMorphTargets = new Box3(); -const _vector$4 = new Vector3(); +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); +const _box$1 = /*@__PURE__*/ new Box3(); +const _boxMorphTargets = /*@__PURE__*/ new Box3(); +const _vector$8 = /*@__PURE__*/ new Vector3(); -function BufferGeometry() { +class BufferGeometry extends EventDispatcher { - Object.defineProperty( this, 'id', { value: _id ++ } ); + constructor() { - this.uuid = MathUtils.generateUUID(); + super(); - this.name = ''; - this.type = 'BufferGeometry'; + this.isBufferGeometry = true; - this.index = null; - this.attributes = {}; + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); - this.morphAttributes = {}; - this.morphTargetsRelative = false; + this.uuid = generateUUID(); - this.groups = []; + this.name = ''; + this.type = 'BufferGeometry'; - this.boundingBox = null; - this.boundingSphere = null; + this.index = null; + this.attributes = {}; - this.drawRange = { start: 0, count: Infinity }; + this.morphAttributes = {}; + this.morphTargetsRelative = false; - this.userData = {}; + this.groups = []; -} + this.boundingBox = null; + this.boundingSphere = null; -BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + this.drawRange = { start: 0, count: Infinity }; - constructor: BufferGeometry, + this.userData = {}; - isBufferGeometry: true, + } - getIndex: function () { + getIndex() { return this.index; - }, + } - setIndex: function ( index ) { + setIndex( index ) { if ( Array.isArray( index ) ) { - this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); } else { @@ -9599,37 +9740,37 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - getAttribute: function ( name ) { + getAttribute( name ) { return this.attributes[ name ]; - }, + } - setAttribute: function ( name, attribute ) { + setAttribute( name, attribute ) { this.attributes[ name ] = attribute; return this; - }, + } - deleteAttribute: function ( name ) { + deleteAttribute( name ) { delete this.attributes[ name ]; return this; - }, + } - hasAttribute: function ( name ) { + hasAttribute( name ) { return this.attributes[ name ] !== undefined; - }, + } - addGroup: function ( start, count, materialIndex = 0 ) { + addGroup( start, count, materialIndex = 0 ) { this.groups.push( { @@ -9639,22 +9780,22 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } ); - }, + } - clearGroups: function () { + clearGroups() { this.groups = []; - }, + } - setDrawRange: function ( start, count ) { + setDrawRange( start, count ) { this.drawRange.start = start; this.drawRange.count = count; - }, + } - applyMatrix4: function ( matrix ) { + applyMatrix4( matrix ) { const position = this.attributes.position; @@ -9702,69 +9843,79 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } + + applyQuaternion( q ) { + + _m1.makeRotationFromQuaternion( q ); + + this.applyMatrix4( _m1 ); - rotateX: function ( angle ) { + return this; + + } + + rotateX( angle ) { // rotate geometry around world x-axis - _m1$2.makeRotationX( angle ); + _m1.makeRotationX( angle ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - rotateY: function ( angle ) { + rotateY( angle ) { // rotate geometry around world y-axis - _m1$2.makeRotationY( angle ); + _m1.makeRotationY( angle ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - rotateZ: function ( angle ) { + rotateZ( angle ) { // rotate geometry around world z-axis - _m1$2.makeRotationZ( angle ); + _m1.makeRotationZ( angle ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - translate: function ( x, y, z ) { + translate( x, y, z ) { // translate geometry - _m1$2.makeTranslation( x, y, z ); + _m1.makeTranslation( x, y, z ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - scale: function ( x, y, z ) { + scale( x, y, z ) { // scale geometry - _m1$2.makeScale( x, y, z ); + _m1.makeScale( x, y, z ); - this.applyMatrix4( _m1$2 ); + this.applyMatrix4( _m1 ); return this; - }, + } - lookAt: function ( vector ) { + lookAt( vector ) { _obj.lookAt( vector ); @@ -9774,9 +9925,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - center: function () { + center() { this.computeBoundingBox(); @@ -9786,9 +9937,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - setFromPoints: function ( points ) { + setFromPoints( points ) { const position = []; @@ -9803,9 +9954,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return this; - }, + } - computeBoundingBox: function () { + computeBoundingBox() { if ( this.boundingBox === null ) { @@ -9840,20 +9991,20 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { const morphAttribute = morphAttributesPosition[ i ]; - _box$2.setFromBufferAttribute( morphAttribute ); + _box$1.setFromBufferAttribute( morphAttribute ); if ( this.morphTargetsRelative ) { - _vector$4.addVectors( this.boundingBox.min, _box$2.min ); - this.boundingBox.expandByPoint( _vector$4 ); + _vector$8.addVectors( this.boundingBox.min, _box$1.min ); + this.boundingBox.expandByPoint( _vector$8 ); - _vector$4.addVectors( this.boundingBox.max, _box$2.max ); - this.boundingBox.expandByPoint( _vector$4 ); + _vector$8.addVectors( this.boundingBox.max, _box$1.max ); + this.boundingBox.expandByPoint( _vector$8 ); } else { - this.boundingBox.expandByPoint( _box$2.min ); - this.boundingBox.expandByPoint( _box$2.max ); + this.boundingBox.expandByPoint( _box$1.min ); + this.boundingBox.expandByPoint( _box$1.max ); } @@ -9873,9 +10024,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, + } - computeBoundingSphere: function () { + computeBoundingSphere() { if ( this.boundingSphere === null ) { @@ -9902,7 +10053,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const center = this.boundingSphere.center; - _box$2.setFromBufferAttribute( position ); + _box$1.setFromBufferAttribute( position ); // process morph attributes if present @@ -9915,16 +10066,16 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy if ( this.morphTargetsRelative ) { - _vector$4.addVectors( _box$2.min, _boxMorphTargets.min ); - _box$2.expandByPoint( _vector$4 ); + _vector$8.addVectors( _box$1.min, _boxMorphTargets.min ); + _box$1.expandByPoint( _vector$8 ); - _vector$4.addVectors( _box$2.max, _boxMorphTargets.max ); - _box$2.expandByPoint( _vector$4 ); + _vector$8.addVectors( _box$1.max, _boxMorphTargets.max ); + _box$1.expandByPoint( _vector$8 ); } else { - _box$2.expandByPoint( _boxMorphTargets.min ); - _box$2.expandByPoint( _boxMorphTargets.max ); + _box$1.expandByPoint( _boxMorphTargets.min ); + _box$1.expandByPoint( _boxMorphTargets.max ); } @@ -9932,7 +10083,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - _box$2.getCenter( center ); + _box$1.getCenter( center ); // second, try to find a boundingSphere with a radius smaller than the // boundingSphere of the boundingBox: sqrt(3) smaller in the best case @@ -9941,9 +10092,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let i = 0, il = position.count; i < il; i ++ ) { - _vector$4.fromBufferAttribute( position, i ); + _vector$8.fromBufferAttribute( position, i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); } @@ -9958,16 +10109,16 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) { - _vector$4.fromBufferAttribute( morphAttribute, j ); + _vector$8.fromBufferAttribute( morphAttribute, j ); if ( morphTargetsRelative ) { _offset.fromBufferAttribute( position, j ); - _vector$4.add( _offset ); + _vector$8.add( _offset ); } - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); } @@ -9985,15 +10136,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, - - computeFaceNormals: function () { - - // backwards compatibility - - }, + } - computeTangents: function () { + computeTangents() { const index = this.index; const attributes = this.attributes; @@ -10018,13 +10163,13 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const nVertices = positions.length / 3; - if ( attributes.tangent === undefined ) { + if ( this.hasAttribute( 'tangent' ) === false ) { this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); } - const tangents = attributes.tangent.array; + const tangents = this.getAttribute( 'tangent' ).array; const tan1 = [], tan2 = []; @@ -10156,9 +10301,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, + } - computeVertexNormals: function () { + computeVertexNormals() { const index = this.index; const positionAttribute = this.getAttribute( 'position' ); @@ -10248,72 +10393,34 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } - }, - - merge: function ( geometry, offset ) { - - if ( ! ( geometry && geometry.isBufferGeometry ) ) { - - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; - - } - - if ( offset === undefined ) { - - offset = 0; - - console.warn( - 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' - + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.' - ); - - } - - const attributes = this.attributes; - - for ( const key in attributes ) { - - if ( geometry.attributes[ key ] === undefined ) continue; - - const attribute1 = attributes[ key ]; - const attributeArray1 = attribute1.array; - - const attribute2 = geometry.attributes[ key ]; - const attributeArray2 = attribute2.array; - - const attributeOffset = attribute2.itemSize * offset; - const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset ); - - for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) { - - attributeArray1[ j ] = attributeArray2[ i ]; + } - } + // @deprecated since r144 - } + merge() { + console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' ); return this; - }, + } - normalizeNormals: function () { + normalizeNormals() { const normals = this.attributes.normal; for ( let i = 0, il = normals.count; i < il; i ++ ) { - _vector$4.fromBufferAttribute( normals, i ); + _vector$8.fromBufferAttribute( normals, i ); - _vector$4.normalize(); + _vector$8.normalize(); - normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); + normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); } - }, + } - toNonIndexed: function () { + toNonIndexed() { function convertBufferAttribute( attribute, indices ) { @@ -10327,7 +10434,15 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy for ( let i = 0, l = indices.length; i < l; i ++ ) { - index = indices[ i ] * itemSize; + if ( attribute.isInterleavedBufferAttribute ) { + + index = indices[ i ] * attribute.data.stride + attribute.offset; + + } else { + + index = indices[ i ] * itemSize; + + } for ( let j = 0; j < itemSize; j ++ ) { @@ -10405,9 +10520,9 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return geometry2; - }, + } - toJSON: function () { + toJSON() { const data = { metadata: { @@ -10438,6 +10553,8 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy } + // for simplicity the code assumes attributes are not shared across geometries, see #15811 + data.data = { attributes: {} }; const index = this.index; @@ -10457,11 +10574,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const attribute = attributes[ key ]; - const attributeData = attribute.toJSON( data.data ); - - if ( attribute.name !== '' ) attributeData.name = attribute.name; - - data.data.attributes[ key ] = attributeData; + data.data.attributes[ key ] = attribute.toJSON( data.data ); } @@ -10478,11 +10591,7 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy const attribute = attributeArray[ i ]; - const attributeData = attribute.toJSON( data.data ); - - if ( attribute.name !== '' ) attributeData.name = attribute.name; - - array.push( attributeData ); + array.push( attribute.toJSON( data.data ) ); } @@ -10524,39 +10633,15 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy return data; - }, - - clone: function () { - - /* - // Handle primitives - - const parameters = this.parameters; - - if ( parameters !== undefined ) { - - const values = []; - - for ( const key in parameters ) { - - values.push( parameters[ key ] ); - - } - - const geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + } - } + clone() { return new this.constructor().copy( this ); - */ - return new BufferGeometry().copy( this ); - - }, + } - copy: function ( source ) { + copy( source ) { // reset @@ -10657,63 +10742,65 @@ BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy this.userData = source.userData; + // geometry generator parameters + + if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters ); + return this; - }, + } - dispose: function () { + dispose() { this.dispatchEvent( { type: 'dispose' } ); } -} ); - -const _inverseMatrix = new Matrix4(); -const _ray = new Ray(); -const _sphere = new Sphere(); +} -const _vA = new Vector3(); -const _vB = new Vector3(); -const _vC = new Vector3(); +const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); +const _ray$2 = /*@__PURE__*/ new Ray(); +const _sphere$3 = /*@__PURE__*/ new Sphere(); -const _tempA = new Vector3(); -const _tempB = new Vector3(); -const _tempC = new Vector3(); +const _vA$1 = /*@__PURE__*/ new Vector3(); +const _vB$1 = /*@__PURE__*/ new Vector3(); +const _vC$1 = /*@__PURE__*/ new Vector3(); -const _morphA = new Vector3(); -const _morphB = new Vector3(); -const _morphC = new Vector3(); +const _tempA = /*@__PURE__*/ new Vector3(); +const _tempB = /*@__PURE__*/ new Vector3(); +const _tempC = /*@__PURE__*/ new Vector3(); -const _uvA = new Vector2(); -const _uvB = new Vector2(); -const _uvC = new Vector2(); +const _morphA = /*@__PURE__*/ new Vector3(); +const _morphB = /*@__PURE__*/ new Vector3(); +const _morphC = /*@__PURE__*/ new Vector3(); -const _intersectionPoint = new Vector3(); -const _intersectionPointWorld = new Vector3(); +const _uvA$1 = /*@__PURE__*/ new Vector2(); +const _uvB$1 = /*@__PURE__*/ new Vector2(); +const _uvC$1 = /*@__PURE__*/ new Vector2(); -function Mesh( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { +const _intersectionPoint = /*@__PURE__*/ new Vector3(); +const _intersectionPointWorld = /*@__PURE__*/ new Vector3(); - Object3D.call( this ); +class Mesh extends Object3D { - this.type = 'Mesh'; + constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { - this.geometry = geometry; - this.material = material; + super(); - this.updateMorphTargets(); + this.isMesh = true; -} + this.type = 'Mesh'; -Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.geometry = geometry; + this.material = material; - constructor: Mesh, + this.updateMorphTargets(); - isMesh: true, + } - copy: function ( source ) { + copy( source, recursive ) { - Object3D.prototype.copy.call( this, source ); + super.copy( source, recursive ); if ( source.morphTargetInfluences !== undefined ) { @@ -10732,54 +10819,40 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { return this; - }, + } - updateMorphTargets: function () { + updateMorphTargets() { const geometry = this.geometry; - if ( geometry.isBufferGeometry ) { - - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); - - if ( keys.length > 0 ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + if ( keys.length > 0 ) { - if ( morphAttribute !== undefined ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( morphAttribute !== undefined ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - const name = morphAttribute[ m ].name || String( m ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { - - const morphTargets = geometry.morphTargets; - - if ( morphTargets !== undefined && morphTargets.length > 0 ) { - - console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - - } - } - }, + } - raycast: function ( raycaster, intersects ) { + raycast( raycaster, intersects ) { const geometry = this.geometry; const material = this.material; @@ -10791,148 +10864,144 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - _sphere.copy( geometry.boundingSphere ); - _sphere.applyMatrix4( matrixWorld ); + _sphere$3.copy( geometry.boundingSphere ); + _sphere$3.applyMatrix4( matrixWorld ); - if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; + if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; // - _inverseMatrix.copy( matrixWorld ).invert(); - _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); + _inverseMatrix$2.copy( matrixWorld ).invert(); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); // Check boundingBox before continuing if ( geometry.boundingBox !== null ) { - if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return; + if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return; } let intersection; - if ( geometry.isBufferGeometry ) { - - const index = geometry.index; - const position = geometry.attributes.position; - const morphPosition = geometry.morphAttributes.position; - const morphTargetsRelative = geometry.morphTargetsRelative; - const uv = geometry.attributes.uv; - const uv2 = geometry.attributes.uv2; - const groups = geometry.groups; - const drawRange = geometry.drawRange; - - if ( index !== null ) { + const index = geometry.index; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + const uv = geometry.attributes.uv; + const uv2 = geometry.attributes.uv2; + const groups = geometry.groups; + const drawRange = geometry.drawRange; - // indexed buffer geometry + if ( index !== null ) { - if ( Array.isArray( material ) ) { + // indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = index.getX( j ); - const b = index.getX( j + 1 ); - const c = index.getX( j + 2 ); + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const a = index.getX( i ); - const b = index.getX( i + 1 ); - const c = index.getX( i + 2 ); + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); } } - } else if ( position !== undefined ) { + } - // non-indexed buffer geometry + } else if ( position !== undefined ) { - if ( Array.isArray( material ) ) { + // non-indexed buffer geometry - for ( let i = 0, il = groups.length; i < il; i ++ ) { + if ( Array.isArray( material ) ) { - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + for ( let i = 0, il = groups.length; i < il; i ++ ) { - const start = Math.max( group.start, drawRange.start ); - const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - for ( let j = start, jl = end; j < jl; j += 3 ) { + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); - const a = j; - const b = j + 1; - const c = j + 2; + for ( let j = start, jl = end; j < jl; j += 3 ) { - intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = j; + const b = j + 1; + const c = j + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); } } - } else { + } - const start = Math.max( 0, drawRange.start ); - const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + } else { - for ( let i = start, il = end; i < il; i += 3 ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); - const a = i; - const b = i + 1; - const c = i + 2; + for ( let i = start, il = end; i < il; i += 3 ) { - intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + const a = i; + const b = i + 1; + const c = i + 2; - if ( intersection ) { + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics - intersects.push( intersection ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); } @@ -10940,15 +11009,11 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { } - } else if ( geometry.isGeometry ) { - - console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } } -} ); +} function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { @@ -10983,13 +11048,13 @@ function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) { - _vA.fromBufferAttribute( position, a ); - _vB.fromBufferAttribute( position, b ); - _vC.fromBufferAttribute( position, c ); + _vA$1.fromBufferAttribute( position, a ); + _vB$1.fromBufferAttribute( position, b ); + _vC$1.fromBufferAttribute( position, c ); const morphInfluences = object.morphTargetInfluences; - if ( material.morphTargets && morphPosition && morphInfluences ) { + if ( morphPosition && morphInfluences ) { _morphA.set( 0, 0, 0 ); _morphB.set( 0, 0, 0 ); @@ -11014,49 +11079,49 @@ function checkBufferGeometryIntersection( object, material, raycaster, ray, posi } else { - _morphA.addScaledVector( _tempA.sub( _vA ), influence ); - _morphB.addScaledVector( _tempB.sub( _vB ), influence ); - _morphC.addScaledVector( _tempC.sub( _vC ), influence ); + _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence ); + _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence ); + _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence ); } } - _vA.add( _morphA ); - _vB.add( _morphB ); - _vC.add( _morphC ); + _vA$1.add( _morphA ); + _vB$1.add( _morphB ); + _vC$1.add( _morphC ); } - if ( object.isSkinnedMesh && material.skinning ) { + if ( object.isSkinnedMesh ) { - object.boneTransform( a, _vA ); - object.boneTransform( b, _vB ); - object.boneTransform( c, _vC ); + object.boneTransform( a, _vA$1 ); + object.boneTransform( b, _vB$1 ); + object.boneTransform( c, _vC$1 ); } - const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint ); + const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint ); if ( intersection ) { if ( uv ) { - _uvA.fromBufferAttribute( uv, a ); - _uvB.fromBufferAttribute( uv, b ); - _uvC.fromBufferAttribute( uv, c ); + _uvA$1.fromBufferAttribute( uv, a ); + _uvB$1.fromBufferAttribute( uv, b ); + _uvC$1.fromBufferAttribute( uv, c ); - intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); + intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); } if ( uv2 ) { - _uvA.fromBufferAttribute( uv2, a ); - _uvB.fromBufferAttribute( uv2, b ); - _uvC.fromBufferAttribute( uv2, c ); + _uvA$1.fromBufferAttribute( uv2, a ); + _uvB$1.fromBufferAttribute( uv2, b ); + _uvC$1.fromBufferAttribute( uv2, c ); - intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); + intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); } @@ -11068,7 +11133,7 @@ function checkBufferGeometryIntersection( object, material, raycaster, ray, posi materialIndex: 0 }; - Triangle.getNormal( _vA, _vB, _vC, face.normal ); + Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal ); intersection.face = face; @@ -11235,6 +11300,12 @@ class BoxGeometry extends BufferGeometry { } + static fromJSON( data ) { + + return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); + + } + } /** @@ -11298,241 +11369,223 @@ function mergeUniforms( uniforms ) { } -// Legacy +function cloneUniformsGroups( src ) { -const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + const dst = []; -var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + for ( let u = 0; u < src.length; u ++ ) { -var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + dst.push( src[ u ].clone() ); -/** - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + } -function ShaderMaterial( parameters ) { + return dst; - Material.call( this ); +} - this.type = 'ShaderMaterial'; +// Legacy - this.defines = {}; - this.uniforms = {}; +const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; - this.vertexShader = default_vertex; - this.fragmentShader = default_fragment; +var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; - this.linewidth = 1; +var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; - this.wireframe = false; - this.wireframeLinewidth = 1; +class ShaderMaterial extends Material { - 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 + constructor( parameters ) { - 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 + super(); - 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 - }; + this.isShaderMaterial = true; - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [ 1, 1, 1 ], - 'uv': [ 0, 0 ], - 'uv2': [ 0, 0 ] - }; + this.type = 'ShaderMaterial'; - this.index0AttributeName = undefined; - this.uniformsNeedUpdate = false; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; - this.glslVersion = null; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; - if ( parameters !== undefined ) { + this.linewidth = 1; - if ( parameters.attributes !== undefined ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + 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 - } + 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 + }; - this.setValues( parameters ); + // 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; + this.uniformsNeedUpdate = false; -} + this.glslVersion = null; -ShaderMaterial.prototype = Object.create( Material.prototype ); -ShaderMaterial.prototype.constructor = ShaderMaterial; + if ( parameters !== undefined ) { -ShaderMaterial.prototype.isShaderMaterial = true; + this.setValues( parameters ); -ShaderMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + } - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + copy( source ) { - this.uniforms = cloneUniforms( source.uniforms ); + super.copy( source ); - this.defines = Object.assign( {}, source.defines ); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + this.uniforms = cloneUniforms( source.uniforms ); + this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups ); - this.lights = source.lights; - this.clipping = source.clipping; + this.defines = Object.assign( {}, source.defines ); - this.skinning = source.skinning; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; - this.extensions = Object.assign( {}, source.extensions ); + this.extensions = Object.assign( {}, source.extensions ); - this.glslVersion = source.glslVersion; + this.glslVersion = source.glslVersion; - return this; + return this; -}; + } -ShaderMaterial.prototype.toJSON = function ( meta ) { + toJSON( meta ) { - const data = Material.prototype.toJSON.call( this, meta ); + const data = super.toJSON( meta ); - data.glslVersion = this.glslVersion; - data.uniforms = {}; + data.glslVersion = this.glslVersion; + data.uniforms = {}; - for ( const name in this.uniforms ) { + for ( const name in this.uniforms ) { - const uniform = this.uniforms[ name ]; - const value = uniform.value; + const uniform = this.uniforms[ name ]; + const value = uniform.value; - if ( value && value.isTexture ) { + if ( value && value.isTexture ) { - data.uniforms[ name ] = { - type: 't', - value: value.toJSON( meta ).uuid - }; + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; - } else if ( value && value.isColor ) { + } else if ( value && value.isColor ) { - data.uniforms[ name ] = { - type: 'c', - value: value.getHex() - }; + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; - } else if ( value && value.isVector2 ) { + } else if ( value && value.isVector2 ) { - data.uniforms[ name ] = { - type: 'v2', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; - } else if ( value && value.isVector3 ) { + } else if ( value && value.isVector3 ) { - data.uniforms[ name ] = { - type: 'v3', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; - } else if ( value && value.isVector4 ) { + } else if ( value && value.isVector4 ) { - data.uniforms[ name ] = { - type: 'v4', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; - } else if ( value && value.isMatrix3 ) { + } else if ( value && value.isMatrix3 ) { - data.uniforms[ name ] = { - type: 'm3', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; - } else if ( value && value.isMatrix4 ) { + } else if ( value && value.isMatrix4 ) { - data.uniforms[ name ] = { - type: 'm4', - value: value.toArray() - }; + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; - } else { + } else { - data.uniforms[ name ] = { - value: value - }; + data.uniforms[ name ] = { + value: value + }; - // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far - } + } - } + } - if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - const extensions = {}; + const extensions = {}; - for ( const key in this.extensions ) { + for ( const key in this.extensions ) { - if ( this.extensions[ key ] === true ) extensions[ key ] = true; + if ( this.extensions[ key ] === true ) extensions[ key ] = true; - } + } - if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; - return data; + return data; -}; + } -function Camera() { +} - Object3D.call( this ); +class Camera extends Object3D { - this.type = 'Camera'; + constructor() { - this.matrixWorldInverse = new Matrix4(); + super(); - this.projectionMatrix = new Matrix4(); - this.projectionMatrixInverse = new Matrix4(); + this.isCamera = true; -} + this.type = 'Camera'; -Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.matrixWorldInverse = new Matrix4(); - constructor: Camera, + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); - isCamera: true, + } - copy: function ( source, recursive ) { + copy( source, recursive ) { - Object3D.prototype.copy.call( this, source, recursive ); + super.copy( source, recursive ); this.matrixWorldInverse.copy( source.matrixWorldInverse ); @@ -11541,16 +11594,9 @@ Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { return this; - }, - - getWorldDirection: function ( target ) { - - if ( target === undefined ) { - - console.warn( 'THREE.Camera: .getWorldDirection() target is now required' ); - target = new Vector3(); + } - } + getWorldDirection( target ) { this.updateWorldMatrix( true, false ); @@ -11558,64 +11604,62 @@ Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); - }, + } - updateMatrixWorld: function ( force ) { + updateMatrixWorld( force ) { - Object3D.prototype.updateMatrixWorld.call( this, force ); + super.updateMatrixWorld( force ); this.matrixWorldInverse.copy( this.matrixWorld ).invert(); - }, + } - updateWorldMatrix: function ( updateParents, updateChildren ) { + updateWorldMatrix( updateParents, updateChildren ) { - Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren ); + super.updateWorldMatrix( updateParents, updateChildren ); this.matrixWorldInverse.copy( this.matrixWorld ).invert(); - }, + } - clone: function () { + clone() { return new this.constructor().copy( this ); } -} ); - -function PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { +} - Camera.call( this ); +class PerspectiveCamera extends Camera { - this.type = 'PerspectiveCamera'; + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { - this.fov = fov; - this.zoom = 1; + super(); - this.near = near; - this.far = far; - this.focus = 10; + this.isPerspectiveCamera = true; - this.aspect = aspect; - this.view = null; + this.type = 'PerspectiveCamera'; - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + this.fov = fov; + this.zoom = 1; - this.updateProjectionMatrix(); + this.near = near; + this.far = far; + this.focus = 10; -} + this.aspect = aspect; + this.view = null; -PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - constructor: PerspectiveCamera, + this.updateProjectionMatrix(); - isPerspectiveCamera: true, + } - copy: function ( source, recursive ) { + copy( source, recursive ) { - Camera.prototype.copy.call( this, source, recursive ); + super.copy( source, recursive ); this.fov = source.fov; this.zoom = source.zoom; @@ -11632,7 +11676,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), return this; - }, + } /** * Sets the FOV by focal length in respect to the current .filmGauge. @@ -11642,47 +11686,47 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), * * Values for focal length and film gauge must have the same unit. */ - setFocalLength: function ( focalLength ) { + setFocalLength( focalLength ) { /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); this.updateProjectionMatrix(); - }, + } /** * Calculates the focal length from the current .fov and .filmGauge. */ - getFocalLength: function () { + getFocalLength() { - const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ); + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); return 0.5 * this.getFilmHeight() / vExtentSlope; - }, + } - getEffectiveFOV: function () { + getEffectiveFOV() { - return MathUtils.RAD2DEG * 2 * Math.atan( - Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); - }, + } - getFilmWidth: function () { + getFilmWidth() { // film not completely covered in portrait format (aspect < 1) return this.filmGauge * Math.min( this.aspect, 1 ); - }, + } - getFilmHeight: function () { + getFilmHeight() { // film not completely covered in landscape format (aspect > 1) return this.filmGauge / Math.max( this.aspect, 1 ); - }, + } /** * Sets an offset in a larger frustum. This is useful for multi-window or @@ -11719,7 +11763,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), * * Note there is no reason monitors have to be the same size or in a grid. */ - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { this.aspect = fullWidth / fullHeight; @@ -11747,9 +11791,9 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), this.updateProjectionMatrix(); - }, + } - clearViewOffset: function () { + clearViewOffset() { if ( this.view !== null ) { @@ -11759,12 +11803,12 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), this.updateProjectionMatrix(); - }, + } - updateProjectionMatrix: function () { + updateProjectionMatrix() { const near = this.near; - let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom; + let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom; let height = 2 * top; let width = this.aspect * height; let left = - 0.5 * width; @@ -11789,11 +11833,11 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); - }, + } - toJSON: function ( meta ) { + toJSON( meta ) { - const data = Object3D.prototype.toJSON.call( this, meta ); + const data = super.toJSON( meta ); data.object.fov = this.fov; data.object.zoom = this.zoom; @@ -11813,7 +11857,7 @@ PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), } -} ); +} const fov = 90, aspect = 1; @@ -11825,13 +11869,6 @@ class CubeCamera extends Object3D { this.type = 'CubeCamera'; - if ( renderTarget.isWebGLCubeRenderTarget !== true ) { - - console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' ); - return; - - } - this.renderTarget = renderTarget; const cameraPX = new PerspectiveCamera( fov, aspect, near, far ); @@ -11880,9 +11917,12 @@ class CubeCamera extends Object3D { const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children; - const currentXrEnabled = renderer.xr.enabled; const currentRenderTarget = renderer.getRenderTarget(); + const currentToneMapping = renderer.toneMapping; + const currentXrEnabled = renderer.xr.enabled; + + renderer.toneMapping = NoToneMapping; renderer.xr.enabled = false; const generateMipmaps = renderTarget.texture.generateMipmaps; @@ -11911,8 +11951,11 @@ class CubeCamera extends Object3D { renderer.setRenderTarget( currentRenderTarget ); + renderer.toneMapping = currentToneMapping; renderer.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } } @@ -11923,21 +11966,10 @@ class CubeTexture extends Texture { images = images !== undefined ? images : []; mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - format = format !== undefined ? format : RGBFormat; super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - // Why CubeTexture._needsFlipEnvMap is necessary: - // - // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) - // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, - // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. - - // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped - // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false) - // when using WebGLCubeRenderTarget.texture as a cube texture. - - this._needsFlipEnvMap = true; + this.isCubeTexture = true; this.flipY = false; @@ -11957,37 +11989,37 @@ class CubeTexture extends Texture { } -CubeTexture.prototype.isCubeTexture = true; - class WebGLCubeRenderTarget extends WebGLRenderTarget { - constructor( size, options, dummy ) { + constructor( size, options = {} ) { - if ( Number.isInteger( options ) ) { + super( size, size, options ); - console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' ); + this.isWebGLCubeRenderTarget = true; - options = dummy; + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; - } + this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - super( size, size, options ); + // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) + // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, + // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. - options = options || {}; + // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped + // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture + // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). - this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture.isRenderTargetTexture = true; this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; - this.texture._needsFlipEnvMap = false; - } fromEquirectangularTexture( renderer, texture ) { this.texture.type = texture.type; - this.texture.format = RGBAFormat; // see #18859 this.texture.encoding = texture.encoding; this.texture.generateMipmaps = texture.generateMipmaps; @@ -12093,33 +12125,209 @@ class WebGLCubeRenderTarget extends WebGLRenderTarget { } -WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true; +const _vector1 = /*@__PURE__*/ new Vector3(); +const _vector2 = /*@__PURE__*/ new Vector3(); +const _normalMatrix = /*@__PURE__*/ new Matrix3(); -class DataTexture extends Texture { +class Plane { - constructor( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { - super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.isPlane = true; - this.image = { data: data || null, width: width || 1, height: height || 1 }; + // normal is assumed to be normalized - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + this.normal = normal; + this.constant = constant; - this.generateMipmaps = false; - this.flipY = false; - this.unpackAlignment = 1; + } - this.needsUpdate = true; + set( normal, constant ) { + + this.normal.copy( normal ); + this.constant = constant; + + return this; } -} + setComponents( x, y, z, w ) { + + this.normal.set( x, y, z ); + this.constant = w; -DataTexture.prototype.isDataTexture = true; + return this; -const _sphere$1 = /*@__PURE__*/ new Sphere(); -const _vector$5 = /*@__PURE__*/ new Vector3(); + } + + setFromNormalAndCoplanarPoint( normal, point ) { + + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); + + return this; + + } + + setFromCoplanarPoints( a, b, c ) { + + const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); + + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + + this.setFromNormalAndCoplanarPoint( normal, a ); + + return this; + + } + + copy( plane ) { + + this.normal.copy( plane.normal ); + this.constant = plane.constant; + + return this; + + } + + normalize() { + + // Note: will lead to a divide by zero if the plane is invalid. + + const inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; + + return this; + + } + + negate() { + + this.constant *= - 1; + this.normal.negate(); + + return this; + + } + + distanceToPoint( point ) { + + return this.normal.dot( point ) + this.constant; + + } + + distanceToSphere( sphere ) { + + return this.distanceToPoint( sphere.center ) - sphere.radius; + + } + + projectPoint( point, target ) { + + return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + + } + + intersectLine( line, target ) { + + const direction = line.delta( _vector1 ); + + const denominator = this.normal.dot( direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { + + return target.copy( line.start ); + + } + + // Unsure if this is the correct method to handle this case. + return null; + + } + + const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + + if ( t < 0 || t > 1 ) { + + return null; + + } + + return target.copy( direction ).multiplyScalar( t ).add( line.start ); + + } + + intersectsLine( line ) { + + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + + const startSign = this.distanceToPoint( line.start ); + const endSign = this.distanceToPoint( line.end ); + + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + + } + + intersectsBox( box ) { + + return box.intersectsPlane( this ); + + } + + intersectsSphere( sphere ) { + + return sphere.intersectsPlane( this ); + + } + + coplanarPoint( target ) { + + return target.copy( this.normal ).multiplyScalar( - this.constant ); + + } + + applyMatrix4( matrix, optionalNormalMatrix ) { + + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + + const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + + const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + + this.constant = - referencePoint.dot( normal ); + + return this; + + } + + translate( offset ) { + + this.constant -= offset.dot( this.normal ); + + return this; + + } + + equals( plane ) { + + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _sphere$2 = /*@__PURE__*/ new Sphere(); +const _vector$7 = /*@__PURE__*/ new Vector3(); class Frustum { @@ -12184,19 +12392,19 @@ class Frustum { if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); + _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); - return this.intersectsSphere( _sphere$1 ); + return this.intersectsSphere( _sphere$2 ); } intersectsSprite( sprite ) { - _sphere$1.center.set( 0, 0, 0 ); - _sphere$1.radius = 0.7071067811865476; - _sphere$1.applyMatrix4( sprite.matrixWorld ); + _sphere$2.center.set( 0, 0, 0 ); + _sphere$2.radius = 0.7071067811865476; + _sphere$2.applyMatrix4( sprite.matrixWorld ); - return this.intersectsSphere( _sphere$1 ); + return this.intersectsSphere( _sphere$2 ); } @@ -12232,11 +12440,11 @@ class Frustum { // corner at max distance - _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x; - _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y; - _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z; + _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z; - if ( plane.distanceToPoint( _vector$5 ) < 0 ) { + if ( plane.distanceToPoint( _vector$7 ) < 0 ) { return false; @@ -12344,16 +12552,12 @@ function WebGLAttributes( gl, capabilities ) { attribute.onUploadCallback(); - let type = 5126; + let type; if ( array instanceof Float32Array ) { type = 5126; - } else if ( array instanceof Float64Array ) { - - console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' ); - } else if ( array instanceof Uint16Array ) { if ( attribute.isFloat16BufferAttribute ) { @@ -12364,7 +12568,7 @@ function WebGLAttributes( gl, capabilities ) { } else { - console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); + throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); } @@ -12394,6 +12598,14 @@ function WebGLAttributes( gl, capabilities ) { type = 5121; + } else if ( array instanceof Uint8ClampedArray ) { + + type = 5121; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); + } return { @@ -12518,6 +12730,7 @@ class PlaneGeometry extends BufferGeometry { constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) { super(); + this.type = 'PlaneGeometry'; this.parameters = { @@ -12588,15 +12801,23 @@ class PlaneGeometry extends BufferGeometry { } + static fromJSON( data ) { + + return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); + + } + } var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; -var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif"; +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; -var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif"; +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; @@ -12604,9 +12825,11 @@ var begin_vertex = "vec3 transformed = vec3( position );"; var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; -var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn 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\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif"; +var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; -var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; @@ -12616,17 +12839,17 @@ var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 v var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; -var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; +var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; -var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; +var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; -var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; +var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; -var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; +var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; -var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(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\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; -var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; @@ -12634,59 +12857,61 @@ var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; -var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; -var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn 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.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn 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\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn 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\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}"; +var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}"; -var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; -var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; -var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; -var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; -var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif"; +var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; -var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif"; +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; -var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; -var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; -var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}"; +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; -var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif"; +var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; -var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif"; +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert\n#define Material_LightProbeLOD( material )\t(0)"; -var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif"; +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; -var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif"; +var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif"; var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; -var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)"; +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)"; var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; -var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\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}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; -var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif"; +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; -var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\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\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; -var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; -var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif"; +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; @@ -12698,11 +12923,11 @@ var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_ var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; -var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif"; +var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; -var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; @@ -12710,25 +12935,37 @@ var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_META var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; -var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif"; +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; -var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; -var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif"; +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\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#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; -var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; +var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + +var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; -var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; +var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; -var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; +var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\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\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; + +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif"; var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; -var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + +var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; @@ -12742,17 +12979,17 @@ var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUG var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; -var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\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\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\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\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; -var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; -var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif"; +var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif"; -var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; var skinbase_vertex = "#ifdef USE_SKINNING\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#endif"; -var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\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\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif"; +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; @@ -12764,11 +13001,11 @@ var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D spe var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; -var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; -var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif"; +var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif"; -var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif"; +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif"; var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; @@ -12782,81 +13019,83 @@ var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tat var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; -var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; -var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; +const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; -var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; +const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include \n\t#include \n}"; -var cube_frag = "#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; +const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; -var cube_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; +const fragment$f = "#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; -var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; +const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; -var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; +const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; -var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; +const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; -var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; +const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; -var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; +const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; -var equirect_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; +const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; -var 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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}"; -var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\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}"; -var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\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}"; +const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\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 \nvoid main() {\n\t#include \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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\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 \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying 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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; -var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\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\tvViewPosition = - mvPosition.xyz;\n}"; +const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; -var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying 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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; +const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; -var 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 \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying 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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$6 = "#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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; -var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}"; +const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; -var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; +const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; +const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; -var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; +const vertex$2 = "#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n}"; -var shadow_vert = "#include \n#include \n#include \nvoid main() {\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}"; +const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; -var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n}"; +const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; -var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; +const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; const ShaderChunk = { alphamap_fragment: alphamap_fragment, alphamap_pars_fragment: alphamap_pars_fragment, alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, aomap_fragment: aomap_fragment, aomap_pars_fragment: aomap_pars_fragment, begin_vertex: begin_vertex, beginnormal_vertex: beginnormal_vertex, bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, bumpmap_pars_fragment: bumpmap_pars_fragment, clipping_planes_fragment: clipping_planes_fragment, clipping_planes_pars_fragment: clipping_planes_pars_fragment, @@ -12888,7 +13127,8 @@ const ShaderChunk = { gradientmap_pars_fragment: gradientmap_pars_fragment, lightmap_fragment: lightmap_fragment, lightmap_pars_fragment: lightmap_pars_fragment, - lights_lambert_vertex: lights_lambert_vertex, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, lights_pars_begin: lights_pars_begin, lights_toon_fragment: lights_toon_fragment, lights_toon_pars_fragment: lights_toon_pars_fragment, @@ -12909,15 +13149,21 @@ const ShaderChunk = { map_particle_pars_fragment: map_particle_pars_fragment, metalnessmap_fragment: metalnessmap_fragment, metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphcolor_vertex: morphcolor_vertex, morphnormal_vertex: morphnormal_vertex, morphtarget_pars_vertex: morphtarget_pars_vertex, morphtarget_vertex: morphtarget_vertex, normal_fragment_begin: normal_fragment_begin, normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, normalmap_pars_fragment: normalmap_pars_fragment, clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + output_fragment: output_fragment, packing: packing, premultiplied_alpha_fragment: premultiplied_alpha_fragment, project_vertex: project_vertex, @@ -12937,8 +13183,8 @@ const ShaderChunk = { specularmap_pars_fragment: specularmap_pars_fragment, tonemapping_fragment: tonemapping_fragment, tonemapping_pars_fragment: tonemapping_pars_fragment, - transmissionmap_fragment: transmissionmap_fragment, - transmissionmap_pars_fragment: transmissionmap_pars_fragment, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_pars_fragment, uv_pars_fragment: uv_pars_fragment, uv_pars_vertex: uv_pars_vertex, uv_vertex: uv_vertex, @@ -12947,38 +13193,38 @@ const ShaderChunk = { uv2_vertex: uv2_vertex, worldpos_vertex: worldpos_vertex, - background_frag: background_frag, - background_vert: background_vert, - 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, - meshmatcap_frag: meshmatcap_frag, - meshmatcap_vert: meshmatcap_vert, - meshtoon_frag: meshtoon_frag, - meshtoon_vert: meshtoon_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, - sprite_frag: sprite_frag, - sprite_vert: sprite_vert + background_vert: vertex$g, + background_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 }; /** @@ -12989,14 +13235,15 @@ const UniformsLib = { common: { - diffuse: { value: new Color( 0xeeeeee ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, map: { value: null }, - uvTransform: { value: new Matrix3() }, - uv2Transform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + uv2Transform: { value: /*@__PURE__*/ new Matrix3() }, alphaMap: { value: null }, + alphaTest: { value: 0 } }, @@ -13010,9 +13257,9 @@ const UniformsLib = { envMap: { value: null }, flipEnvMap: { value: - 1 }, - reflectivity: { value: 1.0 }, - refractionRatio: { value: 0.98 }, - maxMipLevel: { value: 0 } + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 } // basic, lambert, phong }, @@ -13046,7 +13293,7 @@ const UniformsLib = { normalmap: { normalMap: { value: null }, - normalScale: { value: new Vector2( 1, 1 ) } + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } }, @@ -13081,7 +13328,7 @@ const UniformsLib = { fogDensity: { value: 0.00025 }, fogNear: { value: 1 }, fogFar: { value: 2000 }, - fogColor: { value: new Color( 0xffffff ) } + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } }, @@ -13123,8 +13370,9 @@ const UniformsLib = { shadowMapSize: {} } }, + spotLightMap: { value: [] }, spotShadowMap: { value: [] }, - spotShadowMatrix: { value: [] }, + spotLightMatrix: { value: [] }, pointLights: { value: [], properties: { color: {}, @@ -13166,25 +13414,27 @@ const UniformsLib = { points: { - diffuse: { value: new Color( 0xeeeeee ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, size: { value: 1.0 }, scale: { value: 1.0 }, map: { value: null }, alphaMap: { value: null }, - uvTransform: { value: new Matrix3() } + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } }, sprite: { - diffuse: { value: new Color( 0xeeeeee ) }, + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, opacity: { value: 1.0 }, - center: { value: new Vector2( 0.5, 0.5 ) }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, rotation: { value: 0.0 }, map: { value: null }, alphaMap: { value: null }, - uvTransform: { value: new Matrix3() } + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } } @@ -13194,7 +13444,7 @@ const ShaderLib = { basic: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13210,17 +13460,20 @@ const ShaderLib = { lambert: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13231,7 +13484,7 @@ const ShaderLib = { phong: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, @@ -13244,8 +13497,8 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, - specular: { value: new Color( 0x111111 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, shininess: { value: 30 } } ] ), @@ -13257,7 +13510,7 @@ const ShaderLib = { standard: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, @@ -13271,7 +13524,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) }, + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, roughness: { value: 1.0 }, metalness: { value: 0.0 }, envMapIntensity: { value: 1 } // temporary @@ -13285,7 +13538,7 @@ const ShaderLib = { toon: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, @@ -13297,7 +13550,7 @@ const ShaderLib = { UniformsLib.fog, UniformsLib.lights, { - emissive: { value: new Color( 0x000000 ) } + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } } ] ), @@ -13308,7 +13561,7 @@ const ShaderLib = { matcap: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -13326,7 +13579,7 @@ const ShaderLib = { points: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.points, UniformsLib.fog ] ), @@ -13338,7 +13591,7 @@ const ShaderLib = { dashed: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.fog, { @@ -13355,7 +13608,7 @@ const ShaderLib = { depth: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap ] ), @@ -13367,7 +13620,7 @@ const ShaderLib = { normal: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, @@ -13377,14 +13630,14 @@ const ShaderLib = { } ] ), - vertexShader: ShaderChunk.normal_vert, - fragmentShader: ShaderChunk.normal_frag + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag }, sprite: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.sprite, UniformsLib.fog ] ), @@ -13397,7 +13650,7 @@ const ShaderLib = { background: { uniforms: { - uvTransform: { value: new Matrix3() }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, t2D: { value: null }, }, @@ -13405,13 +13658,10 @@ const ShaderLib = { fragmentShader: ShaderChunk.background_frag }, - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ cube: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.envmap, { opacity: { value: 1.0 } @@ -13436,11 +13686,11 @@ const ShaderLib = { distanceRGBA: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap, { - referencePosition: { value: new Vector3() }, + referencePosition: { value: /*@__PURE__*/ new Vector3() }, nearDistance: { value: 1 }, farDistance: { value: 1000 } } @@ -13453,11 +13703,11 @@ const ShaderLib = { shadow: { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ UniformsLib.lights, UniformsLib.fog, { - color: { value: new Color( 0x00000 ) }, + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, opacity: { value: 1.0 } }, ] ), @@ -13471,18 +13721,38 @@ const ShaderLib = { ShaderLib.physical = { - uniforms: mergeUniforms( [ + uniforms: /*@__PURE__*/ mergeUniforms( [ ShaderLib.standard.uniforms, { clearcoat: { value: 0 }, clearcoatMap: { value: null }, clearcoatRoughness: { value: 0 }, clearcoatRoughnessMap: { value: null }, - clearcoatNormalScale: { value: new Vector2( 1, 1 ) }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, clearcoatNormalMap: { value: null }, - sheen: { value: new Color( 0x000000 ) }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, transmission: { value: 0 }, transmissionMap: { value: null }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, } ] ), @@ -13491,10 +13761,10 @@ ShaderLib.physical = { }; -function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) { +function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) { const clearColor = new Color( 0x000000 ); - let clearAlpha = 0; + let clearAlpha = alpha === true ? 0 : 1; let planeMesh; let boxMesh; @@ -13503,8 +13773,9 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha let currentBackgroundVersion = 0; let currentTonemapping = null; - function render( renderList, scene, camera, forceClear ) { + function render( renderList, scene ) { + let forceClear = false; let background = scene.isScene === true ? scene.background : null; if ( background && background.isTexture ) { @@ -13542,7 +13813,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } - if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) { + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { if ( boxMesh === undefined ) { @@ -13569,7 +13840,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha }; - // enable code injection for non-built-in material + // add "envMap" material property so the renderer can evaluate it like for built-in materials Object.defineProperty( boxMesh.material, 'envMap', { get: function () { @@ -13584,16 +13855,8 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } - if ( background.isWebGLCubeRenderTarget ) { - - // TODO Deprecate - - background = background.texture; - - } - boxMesh.material.uniforms.envMap.value = background; - boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1; + boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; if ( currentBackground !== background || currentBackgroundVersion !== background.version || @@ -13607,6 +13870,8 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } + boxMesh.layers.enableAll(); + // push to the pre-sorted opaque render list renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); @@ -13630,7 +13895,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha planeMesh.geometry.deleteAttribute( 'normal' ); - // enable code injection for non-built-in material + // add "map" material property so the renderer can evaluate it like for built-in materials Object.defineProperty( planeMesh.material, 'map', { get: function () { @@ -13667,6 +13932,7 @@ function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha } + planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); @@ -13723,6 +13989,7 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { const defaultState = createBindingState( null ); let currentState = defaultState; + let forceUpdate = false; function setup( object, material, program, geometry, index ) { @@ -13739,9 +14006,9 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - updateBuffers = needsUpdate( geometry, index ); + updateBuffers = needsUpdate( object, geometry, program, index ); - if ( updateBuffers ) saveCache( geometry, index ); + if ( updateBuffers ) saveCache( object, geometry, program, index ); } else { @@ -13761,19 +14028,15 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - if ( object.isInstancedMesh === true ) { - - updateBuffers = true; - - } - if ( index !== null ) { attributes.update( index, 34963 ); } - if ( updateBuffers ) { + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; setupVertexAttributes( object, material, program, geometry ); @@ -13878,25 +14141,40 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function needsUpdate( geometry, index ) { + function needsUpdate( object, geometry, program, index ) { const cachedAttributes = currentState.attributes; const geometryAttributes = geometry.attributes; let attributesNum = 0; - for ( const key in geometryAttributes ) { + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } - const cachedAttribute = cachedAttributes[ key ]; - const geometryAttribute = geometryAttributes[ key ]; + if ( cachedAttribute === undefined ) return true; - if ( cachedAttribute === undefined ) return true; + if ( cachedAttribute.attribute !== geometryAttribute ) return true; - if ( cachedAttribute.attribute !== geometryAttribute ) return true; + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; - if ( cachedAttribute.data !== geometryAttribute.data ) return true; + attributesNum ++; - attributesNum ++; + } } @@ -13908,28 +14186,43 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - function saveCache( geometry, index ) { + function saveCache( object, geometry, program, index ) { const cache = {}; const attributes = geometry.attributes; let attributesNum = 0; - for ( const key in attributes ) { + const programAttributes = program.getAttributes(); - const attribute = attributes[ key ]; + for ( const name in programAttributes ) { - const data = {}; - data.attribute = attribute; + const programAttribute = programAttributes[ name ]; - if ( attribute.data ) { + if ( programAttribute.location >= 0 ) { - data.data = attribute.data; + let attribute = attributes[ name ]; - } + if ( attribute === undefined ) { - cache[ key ] = data; + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; - attributesNum ++; + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } } @@ -14036,9 +14329,16 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { const programAttribute = programAttributes[ name ]; - if ( programAttribute >= 0 ) { + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { - const geometryAttribute = geometryAttributes[ name ]; + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } if ( geometryAttribute !== undefined ) { @@ -14061,87 +14361,87 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { const stride = data.stride; const offset = geometryAttribute.offset; - if ( data && data.isInstancedInterleavedBuffer ) { + if ( data.isInstancedInterleavedBuffer ) { - enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - if ( geometry._maxInstanceCount === undefined ) { - - geometry._maxInstanceCount = data.meshPerAttribute * data.count; + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); } - } else { - - enableAttribute( programAttribute ); + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { - } + geometry._maxInstanceCount = data.meshPerAttribute * data.count; - gl.bindBuffer( 34962, buffer ); - vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement ); + } - } else { + } else { - if ( geometryAttribute.isInstancedBufferAttribute ) { + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); + enableAttribute( programAttribute.location + i ); - if ( geometry._maxInstanceCount === undefined ) { + } - geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } - } + gl.bindBuffer( 34962, buffer ); - } else { + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - enableAttribute( programAttribute ); + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement + ); } - gl.bindBuffer( 34962, buffer ); - vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 ); + } else { - } + if ( geometryAttribute.isInstancedBufferAttribute ) { - } else if ( name === 'instanceMatrix' ) { + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - const attribute = attributes.get( object.instanceMatrix ); + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); - // TODO Attribute may not be available on context restore + } - if ( attribute === undefined ) continue; + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { - const buffer = attribute.buffer; - const type = attribute.type; + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - enableAttributeAndDivisor( programAttribute + 0, 1 ); - enableAttributeAndDivisor( programAttribute + 1, 1 ); - enableAttributeAndDivisor( programAttribute + 2, 1 ); - enableAttributeAndDivisor( programAttribute + 3, 1 ); + } - gl.bindBuffer( 34962, buffer ); + } else { - gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 ); - gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 ); - gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 ); - gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 ); + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - } else if ( name === 'instanceColor' ) { + enableAttribute( programAttribute.location + i ); - const attribute = attributes.get( object.instanceColor ); + } - // TODO Attribute may not be available on context restore + } - if ( attribute === undefined ) continue; + gl.bindBuffer( 34962, buffer ); - const buffer = attribute.buffer; - const type = attribute.type; + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { - enableAttributeAndDivisor( programAttribute, 1 ); + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement + ); - gl.bindBuffer( 34962, buffer ); + } - gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 ); + } } else if ( materialDefaultAttributeValues !== undefined ) { @@ -14152,19 +14452,19 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { switch ( value.length ) { case 2: - gl.vertexAttrib2fv( programAttribute, value ); + gl.vertexAttrib2fv( programAttribute.location, value ); break; case 3: - gl.vertexAttrib3fv( programAttribute, value ); + gl.vertexAttrib3fv( programAttribute.location, value ); break; case 4: - gl.vertexAttrib4fv( programAttribute, value ); + gl.vertexAttrib4fv( programAttribute.location, value ); break; default: - gl.vertexAttrib1fv( programAttribute, value ); + gl.vertexAttrib1fv( programAttribute.location, value ); } @@ -14263,6 +14563,7 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { function reset() { resetDefaultState(); + forceUpdate = true; if ( currentState === defaultState ) return; @@ -14271,7 +14572,7 @@ function WebGLBindingStates( gl, extensions, attributes, capabilities ) { } - // for backward-compatilibity + // for backward-compatibility function resetDefaultState() { @@ -14411,10 +14712,8 @@ function WebGLCapabilities( gl, extensions, parameters ) { } - /* eslint-disable no-undef */ const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) || ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext ); - /* eslint-enable no-undef */ let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; const maxPrecision = getMaxPrecision( precision ); @@ -14426,6 +14725,8 @@ function WebGLCapabilities( gl, extensions, parameters ) { } + const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ); + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; const maxTextures = gl.getParameter( 34930 ); @@ -14448,6 +14749,8 @@ function WebGLCapabilities( gl, extensions, parameters ) { isWebGL2: isWebGL2, + drawBuffers: drawBuffers, + getMaxAnisotropy: getMaxAnisotropy, getMaxPrecision: getMaxPrecision, @@ -14658,7 +14961,7 @@ function WebGLCubeMaps( renderer ) { function get( texture ) { - if ( texture && texture.isTexture ) { + if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) { const mapping = texture.mapping; @@ -14675,14 +14978,10 @@ function WebGLCubeMaps( renderer ) { if ( image && image.height > 0 ) { - const currentRenderTarget = renderer.getRenderTarget(); - const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); renderTarget.fromEquirectangularTexture( renderer, texture ); cubemaps.set( texture, renderTarget ); - renderer.setRenderTarget( currentRenderTarget ); - texture.addEventListener( 'dispose', onTextureDispose ); return mapTextureMapping( renderTarget.texture, texture.mapping ); @@ -14735,3135 +15034,4809 @@ function WebGLCubeMaps( renderer ) { } -function WebGLExtensions( gl ) { - - const extensions = {}; +class OrthographicCamera extends Camera { - function getExtension( name ) { + constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { - if ( extensions[ name ] !== undefined ) { + super(); - return extensions[ name ]; + this.isOrthographicCamera = true; - } + this.type = 'OrthographicCamera'; - let extension; + this.zoom = 1; + this.view = null; - switch ( name ) { + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; + this.near = near; + this.far = far; - 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; + this.updateProjectionMatrix(); - 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; + copy( source, recursive ) { - default: - extension = gl.getExtension( name ); + super.copy( source, recursive ); - } + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - extensions[ name ] = extension; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - return extension; + return this; } - return { + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { - has: function ( name ) { + if ( this.view === null ) { - return getExtension( name ) !== null; + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; - }, + } - init: function ( capabilities ) { + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; - if ( capabilities.isWebGL2 ) { + this.updateProjectionMatrix(); - getExtension( 'EXT_color_buffer_float' ); + } - } else { + clearViewOffset() { - getExtension( 'WEBGL_depth_texture' ); - getExtension( 'OES_texture_float' ); - getExtension( 'OES_texture_half_float' ); - getExtension( 'OES_texture_half_float_linear' ); - getExtension( 'OES_standard_derivatives' ); - getExtension( 'OES_element_index_uint' ); - getExtension( 'OES_vertex_array_object' ); - getExtension( 'ANGLE_instanced_arrays' ); + if ( this.view !== null ) { - } + this.view.enabled = false; - getExtension( 'OES_texture_float_linear' ); - getExtension( 'EXT_color_buffer_half_float' ); + } - }, + this.updateProjectionMatrix(); - get: function ( name ) { + } - const extension = getExtension( name ); + updateProjectionMatrix() { - if ( extension === null ) { + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; - } + if ( this.view !== null && this.view.enabled ) { - return extension; + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; - } + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; - }; + } -} + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); -function WebGLGeometries( gl, attributes, info, bindingStates ) { + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); - const geometries = {}; - const wireframeAttributes = new WeakMap(); + } - function onGeometryDispose( event ) { + toJSON( meta ) { - const geometry = event.target; + const data = super.toJSON( meta ); - if ( geometry.index !== null ) { + 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; - attributes.remove( geometry.index ); + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - } + return data; - for ( const name in geometry.attributes ) { + } - attributes.remove( geometry.attributes[ name ] ); +} - } +const LOD_MIN = 4; - geometry.removeEventListener( 'dispose', onGeometryDispose ); +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; - delete geometries[ geometry.id ]; +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; - const attribute = wireframeAttributes.get( geometry ); +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; - if ( attribute ) { +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; - attributes.remove( attribute ); - wireframeAttributes.delete( geometry ); +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( 1, 1, 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; - } +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view +*/ - bindingStates.releaseStatesOfGeometry( geometry ); +class PMREMGenerator { - if ( geometry.isInstancedBufferGeometry === true ) { + constructor( renderer ) { - delete geometry._maxInstanceCount; + this._renderer = renderer; + this._pingPongRenderTarget = null; - } + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; - // + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; - info.memory.geometries --; + this._compileMaterial( this._blurMaterial ); } - function get( object, geometry ) { + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { - if ( geometries[ geometry.id ] === true ) return geometry; + _oldTarget = this._renderer.getRenderTarget(); - geometry.addEventListener( 'dispose', onGeometryDispose ); + this._setSize( 256 ); - geometries[ geometry.id ] = true; + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; - info.memory.geometries ++; + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); - return geometry; + if ( sigma > 0 ) { - } + this._blur( cubeUVRenderTarget, 0, 0, sigma ); - function update( geometry ) { + } - const geometryAttributes = geometry.attributes; + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - // Updating index buffer in VAO now. See WebGLBindingStates. + return cubeUVRenderTarget; - for ( const name in geometryAttributes ) { + } - attributes.update( geometryAttributes[ name ], 34962 ); + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { - } + return this._fromTexture( equirectangular, renderTarget ); - // morph targets + } - const morphAttributes = geometry.morphAttributes; + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { - for ( const name in morphAttributes ) { + return this._fromTexture( cubemap, renderTarget ); - const array = morphAttributes[ name ]; + } - for ( let i = 0, l = array.length; i < l; i ++ ) { + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { - attributes.update( array[ i ], 34962 ); + if ( this._cubemapMaterial === null ) { - } + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); } } - function updateWireframeAttribute( geometry ) { - - const indices = []; + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { - const geometryIndex = geometry.index; - const geometryPosition = geometry.attributes.position; - let version = 0; + if ( this._equirectMaterial === null ) { - if ( geometryIndex !== null ) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); - const array = geometryIndex.array; - version = geometryIndex.version; + } - for ( let i = 0, l = array.length; i < l; i += 3 ) { + } - const a = array[ i + 0 ]; - const b = array[ i + 1 ]; - const c = array[ i + 2 ]; + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { - indices.push( a, b, b, c, c, a ); + this._dispose(); - } + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); - } else { + } - const array = geometryPosition.array; - version = geometryPosition.version; + // private interface - for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + _setSize( cubeSize ) { - const a = i + 0; - const b = i + 1; - const c = i + 2; + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); - indices.push( a, b, b, c, c, a ); + } - } + _dispose() { - } + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); - const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); - attribute.version = version; + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); - // Updating index buffer in VAO now. See WebGLBindingStates + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { - // + this._lodPlanes[ i ].dispose(); - const previousAttribute = wireframeAttributes.get( geometry ); + } - if ( previousAttribute ) attributes.remove( previousAttribute ); + } - // + _cleanup( outputTarget ) { - wireframeAttributes.set( geometry, attribute ); + this._renderer.setRenderTarget( _oldTarget ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); } - function getWireframeAttribute( geometry ) { - - const currentAttribute = wireframeAttributes.get( geometry ); - - if ( currentAttribute ) { + _fromTexture( texture, renderTarget ) { - const geometryIndex = geometry.index; + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { - if ( geometryIndex !== null ) { + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); - // if the attribute is obsolete, create a new one + } else { // Equirectangular - if ( currentAttribute.version < geometryIndex.version ) { + this._setSize( texture.image.width / 4 ); - updateWireframeAttribute( geometry ); + } - } + _oldTarget = this._renderer.getRenderTarget(); - } + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - } else { + return cubeUVRenderTarget; - updateWireframeAttribute( geometry ); + } - } + _allocateTargets() { - return wireframeAttributes.get( geometry ); + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; - } + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + encoding: LinearEncoding, + depthBuffer: false + }; - return { + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); - get: get, - update: update, + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width ) { - getWireframeAttribute: getWireframeAttribute + if ( this._pingPongRenderTarget !== null ) { - }; + this._dispose(); -} + } -function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); - const isWebGL2 = capabilities.isWebGL2; + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) ); - let mode; + this._blurMaterial = _getBlurShader( _lodMax, width, height ); - function setMode( value ) { + } - mode = value; + return cubeUVRenderTarget; } - let type, bytesPerElement; - - function setIndex( value ) { + _compileMaterial( material ) { - type = value.type; - bytesPerElement = value.bytesPerElement; + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); } - function render( start, count ) { - - gl.drawElements( mode, count, type, start * bytesPerElement ); + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { - info.update( count, mode, 1 ); + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, - 1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; + const renderer = this._renderer; - } + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); - function renderInstances( start, count, primcount ) { + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; - if ( primcount === 0 ) return; + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ); - let extension, methodName; + const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); - if ( isWebGL2 ) { + let useSolidColor = false; + const background = scene.background; - extension = gl; - methodName = 'drawElementsInstanced'; + if ( background ) { - } else { + if ( background.isColor ) { - extension = extensions.get( 'ANGLE_instanced_arrays' ); - methodName = 'drawElementsInstancedANGLE'; + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; - if ( extension === null ) { + } - console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + } else { - } + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; } - extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); + for ( let i = 0; i < 6; i ++ ) { - info.update( count, mode, primcount ); + const col = i % 3; - } + if ( col === 0 ) { - // + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + } else if ( col === 1 ) { -} + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); -function WebGLInfo( gl ) { + } else { - const memory = { - geometries: 0, - textures: 0 - }; - - const render = { - frame: 0, - calls: 0, - triangles: 0, - points: 0, - lines: 0 - }; - - function update( count, mode, instanceCount ) { + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); - render.calls ++; + } - switch ( mode ) { + const size = this._cubeSize; - case 4: - render.triangles += instanceCount * ( count / 3 ); - break; + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); - case 1: - render.lines += instanceCount * ( count / 2 ); - break; + renderer.setRenderTarget( cubeUVRenderTarget ); - case 3: - render.lines += instanceCount * ( count - 1 ); - break; + if ( useSolidColor ) { - case 2: - render.lines += instanceCount * count; - break; + renderer.render( backgroundBox, cubeCamera ); - case 0: - render.points += instanceCount * count; - break; + } - default: - console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); - break; + renderer.render( scene, cubeCamera ); } - } - - function reset() { + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); - render.frame ++; - render.calls = 0; - render.triangles = 0; - render.points = 0; - render.lines = 0; + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; } - return { - memory: memory, - render: render, - programs: null, - autoReset: true, - reset: reset, - update: update - }; + _textureToCubeUV( texture, cubeUVRenderTarget ) { -} + const renderer = this._renderer; -function numericalSort( a, b ) { + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); - return a[ 0 ] - b[ 0 ]; + if ( isCubeTexture ) { -} + if ( this._cubemapMaterial === null ) { -function absNumericalSort( a, b ) { + this._cubemapMaterial = _getCubemapMaterial(); - return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); + } -} + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1; -function WebGLMorphtargets( gl ) { + } else { - const influencesList = {}; - const morphInfluences = new Float32Array( 8 ); + if ( this._equirectMaterial === null ) { - const workInfluences = []; + this._equirectMaterial = _getEquirectMaterial(); - for ( let i = 0; i < 8; i ++ ) { + } - workInfluences[ i ] = [ i, 0 ]; + } - } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh( this._lodPlanes[ 0 ], material ); - function update( object, geometry, material, program ) { + const uniforms = material.uniforms; - const objectInfluences = object.morphTargetInfluences; + uniforms[ 'envMap' ].value = texture; - // When object doesn't have morph target influences defined, we treat it as a 0-length array - // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences + const size = this._cubeSize; - const length = objectInfluences === undefined ? 0 : objectInfluences.length; + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); - let influences = influencesList[ geometry.id ]; + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); - if ( influences === undefined ) { + } - // initialise list + _applyPMREM( cubeUVRenderTarget ) { - influences = []; + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; - for ( let i = 0; i < length; i ++ ) { + for ( let i = 1; i < this._lodPlanes.length; i ++ ) { - influences[ i ] = [ i, 0 ]; + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); - } + const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; - influencesList[ geometry.id ] = influences; + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); } - // Collect influences - - for ( let i = 0; i < length; i ++ ) { + renderer.autoClear = autoClear; - const influence = influences[ i ]; + } - influence[ 0 ] = i; - influence[ 1 ] = objectInfluences[ i ]; + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { - } + const pingPongRenderTarget = this._pingPongRenderTarget; - influences.sort( absNumericalSort ); + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); - for ( let i = 0; i < 8; i ++ ) { + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); - if ( i < length && influences[ i ][ 1 ] ) { + } - workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; - workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { - } else { + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; - workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; - workInfluences[ i ][ 1 ] = 0; + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { - } + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); } - workInfluences.sort( numericalSort ); - - const morphTargets = material.morphTargets && geometry.morphAttributes.position; - const morphNormals = material.morphNormals && geometry.morphAttributes.normal; + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; - let morphInfluencesSum = 0; + const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial ); + const blurUniforms = blurMaterial.uniforms; - for ( let i = 0; i < 8; i ++ ) { + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; - const influence = workInfluences[ i ]; - const index = influence[ 0 ]; - const value = influence[ 1 ]; + if ( samples > MAX_SAMPLES ) { - if ( index !== Number.MAX_SAFE_INTEGER && value ) { + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); - if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { + } - geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); + const weights = []; + let sum = 0; - } + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { - if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); - geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); + if ( i === 0 ) { - } + sum += weight; - morphInfluences[ i ] = value; - morphInfluencesSum += value; + } else if ( i < samples ) { - } else { + sum += 2 * weight; - if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { + } - geometry.deleteAttribute( 'morphTarget' + i ); + } - } + for ( let i = 0; i < weights.length; i ++ ) { - if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { + weights[ i ] = weights[ i ] / sum; - geometry.deleteAttribute( 'morphNormal' + i ); + } - } + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; - morphInfluences[ i ] = 0; + if ( poleAxis ) { - } + blurUniforms[ 'poleAxis' ].value = poleAxis; } - // GLSL shader uses formula baseinfluence * base + sum(target * influence) - // This allows us to switch between absolute morphs and relative morphs without changing shader code - // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) - const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const { _lodMax } = this; + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = _lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); - program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); - program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); } - return { +} - update: update - }; -} +function _createPlanes( lodMax ) { -function WebGLObjects( gl, geometries, attributes, info ) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; - let updateMap = new WeakMap(); + let lod = lodMax; - function update( object ) { + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; - const frame = info.render.frame; + for ( let i = 0; i < totalLods; i ++ ) { - const geometry = object.geometry; - const buffergeometry = geometries.get( object, geometry ); + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; - // Update once per frame + if ( i > lodMax - LOD_MIN ) { - if ( updateMap.get( buffergeometry ) !== frame ) { + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; - geometries.update( buffergeometry ); + } else if ( i === 0 ) { - updateMap.set( buffergeometry, frame ); + sigma = 0; } - if ( object.isInstancedMesh ) { - - if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { - - object.addEventListener( 'dispose', onInstancedMeshDispose ); + sigmas.push( sigma ); - } + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; - attributes.update( object.instanceMatrix, 34962 ); + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; - if ( object.instanceColor !== null ) { + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); - attributes.update( object.instanceColor, 34962 ); + for ( let face = 0; face < cubeFaces; face ++ ) { - } + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + const fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); } - return buffergeometry; + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); - } + if ( lod > LOD_MIN ) { - function dispose() { + lod --; - updateMap = new WeakMap(); + } } - function onInstancedMeshDispose( event ) { - - const instancedMesh = event.target; - - instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); - - attributes.remove( instancedMesh.instanceMatrix ); - - if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); - - } + return { lodPlanes, sizeLods, sigmas }; - return { +} - update: update, - dispose: dispose +function _createRenderTarget( width, height, params ) { - }; + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; } -class DataTexture2DArray extends Texture { +function _setViewport( target, x, y, width, height ) { - constructor( data = null, width = 1, height = 1, depth = 1 ) { + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); - super( null ); +} - this.image = { data, width, height, depth }; +function _getBlurShader( lodMax, width, height ) { - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; + const weights = new Float32Array( MAX_SAMPLES ); + const poleAxis = new Vector3( 0, 1, 0 ); + const shaderMaterial = new ShaderMaterial( { - this.wrapR = ClampToEdgeWrapping; + name: 'SphericalGaussianBlur', - this.generateMipmaps = false; - this.flipY = false; + defines: { + 'n': MAX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, - this.needsUpdate = true; + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis } + }, - } + vertexShader: _getCommonVertexShader(), -} + fragmentShader: /* glsl */` -DataTexture2DArray.prototype.isDataTexture2DArray = true; + precision mediump float; + precision mediump int; -class DataTexture3D extends Texture { + varying vec3 vOutputDirection; - constructor( data = null, width = 1, height = 1, depth = 1 ) { + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; - // We're going to add .setXXX() methods for setting properties later. - // Users can still set in DataTexture3D directly. - // - // const texture = new THREE.DataTexture3D( data, width, height, depth ); - // texture.anisotropy = 16; - // - // See #14839 + #define ENVMAP_TYPE_CUBE_UV + #include - super( null ); + vec3 getSample( float theta, vec3 axis ) { - this.image = { data, width, height, depth }; + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; + return bilinearCubeUV( envMap, sampleDirection, mipInt ); - this.wrapR = ClampToEdgeWrapping; + } - this.generateMipmaps = false; - this.flipY = false; + void main() { - this.needsUpdate = true; + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - } + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { -} + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); -DataTexture3D.prototype.isDataTexture3D = true; + } -/** - * 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 )'. - * - * - * 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, [textures] ) - * - * uploads a uniform value(s) - * the 'textures' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (textures factorizations): - * - * .upload( gl, seq, values, textures ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * - * Methods of the top-level container (textures factorizations): - * - * .setValue( gl, name, value, textures ) - * - * sets uniform with name 'name' to 'value' - * - * .setOptional( gl, obj, prop ) - * - * like .set for an optional property of the object - * - */ + axis = normalize( axis ); -const emptyTexture = new Texture(); -const emptyTexture2dArray = new DataTexture2DArray(); -const emptyTexture3d = new DataTexture3D(); -const emptyCubeTexture = new CubeTexture(); + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); -// --- Utilities --- + for ( int i = 1; i < n; i++ ) { -// Array Caches (provide typed arrays for temporary by size) + if ( i >= samples ) { -const arrayCacheF32 = []; -const arrayCacheI32 = []; + break; -// Float32Array caches used for uploading Matrix uniforms + } -const mat4array = new Float32Array( 16 ); -const mat3array = new Float32Array( 9 ); -const mat2array = new Float32Array( 4 ); + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); -// Flattening for arrays of vectors and matrices + } -function flatten( array, nBlocks, blockSize ) { + } + `, - const firstElem = array[ 0 ]; + blending: NoBlending, + depthTest: false, + depthWrite: false - if ( firstElem <= 0 || firstElem > 0 ) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + } ); - const n = nBlocks * blockSize; - let r = arrayCacheF32[ n ]; + return shaderMaterial; - if ( r === undefined ) { +} - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; +function _getEquirectMaterial() { - } + return new ShaderMaterial( { - if ( nBlocks !== 0 ) { + name: 'EquirectangularToCubeUV', - firstElem.toArray( r, 0 ); + uniforms: { + 'envMap': { value: null } + }, - for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + vertexShader: _getCommonVertexShader(), - offset += blockSize; - array[ i ].toArray( r, offset ); + fragmentShader: /* glsl */` - } + precision mediump float; + precision mediump int; - } + varying vec3 vOutputDirection; - return r; + uniform sampler2D envMap; -} + #include -function arraysEqual( a, b ) { + void main() { - if ( a.length !== b.length ) return false; + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); - for ( let i = 0, l = a.length; i < l; i ++ ) { + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - if ( a[ i ] !== b[ i ] ) return false; + } + `, - } + blending: NoBlending, + depthTest: false, + depthWrite: false - return true; + } ); } -function copyArray( a, b ) { +function _getCubemapMaterial() { - for ( let i = 0, l = b.length; i < l; i ++ ) { + return new ShaderMaterial( { - a[ i ] = b[ i ]; + name: 'CubemapToCubeUV', - } + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: - 1 } + }, -} + vertexShader: _getCommonVertexShader(), -// Texture unit allocation + fragmentShader: /* glsl */` -function allocTexUnits( textures, n ) { + precision mediump float; + precision mediump int; - let r = arrayCacheI32[ n ]; + uniform float flipEnvMap; - if ( r === undefined ) { + varying vec3 vOutputDirection; - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + uniform samplerCube envMap; - } + void main() { - for ( let i = 0; i !== n; ++ i ) { + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - r[ i ] = textures.allocateTextureUnit(); + } + `, - } + blending: NoBlending, + depthTest: false, + depthWrite: false - return r; + } ); } -// --- Setters --- +function _getCommonVertexShader() { -// Note: Defining these methods externally, because they come in a bunch -// and this way their names minify. + return /* glsl */` -// Single scalar + precision mediump float; + precision mediump int; -function setValueV1f( gl, v ) { + attribute float faceIndex; - const cache = this.cache; + varying vec3 vOutputDirection; - if ( cache[ 0 ] === v ) return; + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { - gl.uniform1f( this.addr, v ); + uv = 2.0 * uv - 1.0; - cache[ 0 ] = v; + vec3 direction = vec3( uv, 1.0 ); -} + if ( face == 0.0 ) { -// Single float vector (from flat array or THREE.VectorN) + direction = direction.zyx; // ( 1, v, u ) pos x -function setValueV2f( gl, v ) { + } else if ( face == 1.0 ) { - const cache = this.cache; + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y - if ( v.x !== undefined ) { + } else if ( face == 2.0 ) { - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + direction.x *= -1.0; // ( -u, v, 1 ) pos z - gl.uniform2f( this.addr, v.x, v.y ); - - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - - } - - } else { - - if ( arraysEqual( cache, v ) ) return; + } else if ( face == 3.0 ) { - gl.uniform2fv( this.addr, v ); + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x - copyArray( cache, v ); + } else if ( face == 4.0 ) { - } + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y -} + } else if ( face == 5.0 ) { -function setValueV3f( gl, v ) { + direction.z *= -1.0; // ( u, v, -1 ) neg z - const cache = this.cache; + } - if ( v.x !== undefined ) { + return direction; - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + } - gl.uniform3f( this.addr, v.x, v.y, v.z ); + void main() { - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - cache[ 2 ] = v.z; + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); } + `; - } else if ( v.r !== undefined ) { - - if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { +} - gl.uniform3f( this.addr, v.r, v.g, v.b ); +function WebGLCubeUVMaps( renderer ) { - cache[ 0 ] = v.r; - cache[ 1 ] = v.g; - cache[ 2 ] = v.b; + let cubeUVmaps = new WeakMap(); - } + let pmremGenerator = null; - } else { + function get( texture ) { - if ( arraysEqual( cache, v ) ) return; + if ( texture && texture.isTexture ) { - gl.uniform3fv( this.addr, v ); + const mapping = texture.mapping; - copyArray( cache, v ); + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); - } + // equirect/cube map to cubeUV conversion -} + if ( isEquirectMap || isCubeMap ) { -function setValueV4f( gl, v ) { + if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) { - const cache = this.cache; + texture.needsPMREMUpdate = false; - if ( v.x !== undefined ) { + let renderTarget = cubeUVmaps.get( texture ); - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); - gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + cubeUVmaps.set( texture, renderTarget ); - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - cache[ 2 ] = v.z; - cache[ 3 ] = v.w; + return renderTarget.texture; - } + } else { - } else { + if ( cubeUVmaps.has( texture ) ) { - if ( arraysEqual( cache, v ) ) return; + return cubeUVmaps.get( texture ).texture; - gl.uniform4fv( this.addr, v ); + } else { - copyArray( cache, v ); + const image = texture.image; - } + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { -} + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); -// Single matrix (from flat array or MatrixN) + const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + cubeUVmaps.set( texture, renderTarget ); -function setValueM2( gl, v ) { + texture.addEventListener( 'dispose', onTextureDispose ); - const cache = this.cache; - const elements = v.elements; + return renderTarget.texture; - if ( elements === undefined ) { + } else { - if ( arraysEqual( cache, v ) ) return; + // image not yet ready. try the conversion next frame - gl.uniformMatrix2fv( this.addr, false, v ); + return null; - copyArray( cache, v ); + } - } else { + } - if ( arraysEqual( cache, elements ) ) return; + } - mat2array.set( elements ); + } - gl.uniformMatrix2fv( this.addr, false, mat2array ); + } - copyArray( cache, elements ); + return texture; } -} - -function setValueM3( gl, v ) { + function isCubeTextureComplete( image ) { - const cache = this.cache; - const elements = v.elements; + let count = 0; + const length = 6; - if ( elements === undefined ) { + for ( let i = 0; i < length; i ++ ) { - if ( arraysEqual( cache, v ) ) return; + if ( image[ i ] !== undefined ) count ++; - gl.uniformMatrix3fv( this.addr, false, v ); + } - copyArray( cache, v ); + return count === length; - } else { - if ( arraysEqual( cache, elements ) ) return; + } - mat3array.set( elements ); + function onTextureDispose( event ) { - gl.uniformMatrix3fv( this.addr, false, mat3array ); + const texture = event.target; - copyArray( cache, elements ); + texture.removeEventListener( 'dispose', onTextureDispose ); - } + const cubemapUV = cubeUVmaps.get( texture ); -} + if ( cubemapUV !== undefined ) { -function setValueM4( gl, v ) { + cubeUVmaps.delete( texture ); + cubemapUV.dispose(); - const cache = this.cache; - const elements = v.elements; + } - if ( elements === undefined ) { + } - if ( arraysEqual( cache, v ) ) return; + function dispose() { - gl.uniformMatrix4fv( this.addr, false, v ); + cubeUVmaps = new WeakMap(); - copyArray( cache, v ); + if ( pmremGenerator !== null ) { - } else { + pmremGenerator.dispose(); + pmremGenerator = null; - if ( arraysEqual( cache, elements ) ) return; + } - mat4array.set( elements ); + } - gl.uniformMatrix4fv( this.addr, false, mat4array ); + return { + get: get, + dispose: dispose + }; - copyArray( cache, elements ); +} - } +function WebGLExtensions( gl ) { -} + const extensions = {}; -// Single texture (2D / Cube) + function getExtension( name ) { -function setValueT1( gl, v, textures ) { + if ( extensions[ name ] !== undefined ) { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + return extensions[ name ]; - if ( cache[ 0 ] !== unit ) { + } - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + let extension; - } + switch ( name ) { - textures.safeSetTexture2D( v || emptyTexture, unit ); + 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; -function setValueT2DArray1( gl, v, textures ) { + 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; - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - if ( cache[ 0 ] !== unit ) { + default: + extension = gl.getExtension( name ); - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + } - } + extensions[ name ] = extension; - textures.setTexture2DArray( v || emptyTexture2dArray, unit ); + return extension; -} + } -function setValueT3D1( gl, v, textures ) { + return { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + has: function ( name ) { - if ( cache[ 0 ] !== unit ) { + return getExtension( name ) !== null; - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + }, - } + init: function ( capabilities ) { - textures.setTexture3D( v || emptyTexture3d, unit ); + if ( capabilities.isWebGL2 ) { -} + getExtension( 'EXT_color_buffer_float' ); -function setValueT6( gl, v, textures ) { + } else { - const cache = this.cache; - const unit = textures.allocateTextureUnit(); + getExtension( 'WEBGL_depth_texture' ); + getExtension( 'OES_texture_float' ); + getExtension( 'OES_texture_half_float' ); + getExtension( 'OES_texture_half_float_linear' ); + getExtension( 'OES_standard_derivatives' ); + getExtension( 'OES_element_index_uint' ); + getExtension( 'OES_vertex_array_object' ); + getExtension( 'ANGLE_instanced_arrays' ); - if ( cache[ 0 ] !== unit ) { + } - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); - } + }, - textures.safeSetTextureCube( v || emptyCubeTexture, unit ); + get: function ( name ) { -} + const extension = getExtension( name ); -// Integer / Boolean vectors or arrays thereof (always flat arrays) + if ( extension === null ) { -function setValueV1i( gl, v ) { + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - const cache = this.cache; + } - if ( cache[ 0 ] === v ) return; + return extension; - gl.uniform1i( this.addr, v ); + } - cache[ 0 ] = v; + }; } -function setValueV2i( gl, v ) { +function WebGLGeometries( gl, attributes, info, bindingStates ) { - const cache = this.cache; + const geometries = {}; + const wireframeAttributes = new WeakMap(); - if ( arraysEqual( cache, v ) ) return; + function onGeometryDispose( event ) { - gl.uniform2iv( this.addr, v ); + const geometry = event.target; - copyArray( cache, v ); + if ( geometry.index !== null ) { -} + attributes.remove( geometry.index ); -function setValueV3i( gl, v ) { + } - const cache = this.cache; + for ( const name in geometry.attributes ) { - if ( arraysEqual( cache, v ) ) return; + attributes.remove( geometry.attributes[ name ] ); - gl.uniform3iv( this.addr, v ); + } - copyArray( cache, v ); + geometry.removeEventListener( 'dispose', onGeometryDispose ); -} + delete geometries[ geometry.id ]; -function setValueV4i( gl, v ) { + const attribute = wireframeAttributes.get( geometry ); - const cache = this.cache; + if ( attribute ) { - if ( arraysEqual( cache, v ) ) return; + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); - gl.uniform4iv( this.addr, v ); + } - copyArray( cache, v ); + bindingStates.releaseStatesOfGeometry( geometry ); -} + if ( geometry.isInstancedBufferGeometry === true ) { -// uint + delete geometry._maxInstanceCount; -function setValueV1ui( gl, v ) { + } - const cache = this.cache; + // - if ( cache[ 0 ] === v ) return; + info.memory.geometries --; - gl.uniform1ui( this.addr, v ); + } - cache[ 0 ] = v; + function get( object, geometry ) { -} + if ( geometries[ geometry.id ] === true ) return geometry; -// Helper to pick the right setter for the singular case + geometry.addEventListener( 'dispose', onGeometryDispose ); -function getSingularSetter( type ) { + geometries[ geometry.id ] = true; - switch ( type ) { + info.memory.geometries ++; - case 0x1406: return setValueV1f; // FLOAT - case 0x8b50: return setValueV2f; // _VEC2 - case 0x8b51: return setValueV3f; // _VEC3 - case 0x8b52: return setValueV4f; // _VEC4 + return geometry; - case 0x8b5a: return setValueM2; // _MAT2 - case 0x8b5b: return setValueM3; // _MAT3 - case 0x8b5c: return setValueM4; // _MAT4 + } - case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL - case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 - case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 - case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + function update( geometry ) { - case 0x1405: return setValueV1ui; // UINT + const geometryAttributes = geometry.attributes; - case 0x8b5e: // SAMPLER_2D - case 0x8d66: // SAMPLER_EXTERNAL_OES - case 0x8dca: // INT_SAMPLER_2D - case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D - case 0x8b62: // SAMPLER_2D_SHADOW - return setValueT1; + // Updating index buffer in VAO now. See WebGLBindingStates. - case 0x8b5f: // SAMPLER_3D - case 0x8dcb: // INT_SAMPLER_3D - case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D - return setValueT3D1; + for ( const name in geometryAttributes ) { - case 0x8b60: // SAMPLER_CUBE - case 0x8dcc: // INT_SAMPLER_CUBE - case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE - case 0x8dc5: // SAMPLER_CUBE_SHADOW - return setValueT6; + attributes.update( geometryAttributes[ name ], 34962 ); - case 0x8dc1: // SAMPLER_2D_ARRAY - case 0x8dcf: // INT_SAMPLER_2D_ARRAY - case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY - case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW - return setValueT2DArray1; + } - } + // morph targets -} + const morphAttributes = geometry.morphAttributes; -// Array of scalars -function setValueV1fArray( gl, v ) { + for ( const name in morphAttributes ) { - gl.uniform1fv( this.addr, v ); + const array = morphAttributes[ name ]; -} + for ( let i = 0, l = array.length; i < l; i ++ ) { -// Integer / Boolean vectors or arrays thereof (always flat arrays) -function setValueV1iArray( gl, v ) { + attributes.update( array[ i ], 34962 ); - gl.uniform1iv( this.addr, v ); + } -} + } -function setValueV2iArray( gl, v ) { + } - gl.uniform2iv( this.addr, v ); + function updateWireframeAttribute( geometry ) { -} + const indices = []; -function setValueV3iArray( gl, v ) { + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; - gl.uniform3iv( this.addr, v ); + if ( geometryIndex !== null ) { -} + const array = geometryIndex.array; + version = geometryIndex.version; -function setValueV4iArray( gl, v ) { + for ( let i = 0, l = array.length; i < l; i += 3 ) { - gl.uniform4iv( this.addr, v ); + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; -} + indices.push( a, b, b, c, c, a ); + } -// Array of vectors (flat or from THREE classes) + } else { -function setValueV2fArray( gl, v ) { + const array = geometryPosition.array; + version = geometryPosition.version; - const data = flatten( v, this.size, 2 ); + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - gl.uniform2fv( this.addr, data ); + const a = i + 0; + const b = i + 1; + const c = i + 2; -} + indices.push( a, b, b, c, c, a ); -function setValueV3fArray( gl, v ) { + } - const data = flatten( v, this.size, 3 ); + } - gl.uniform3fv( this.addr, data ); + const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; -} + // Updating index buffer in VAO now. See WebGLBindingStates -function setValueV4fArray( gl, v ) { + // - const data = flatten( v, this.size, 4 ); + const previousAttribute = wireframeAttributes.get( geometry ); - gl.uniform4fv( this.addr, data ); + if ( previousAttribute ) attributes.remove( previousAttribute ); -} + // -// Array of matrices (flat or from THREE clases) + wireframeAttributes.set( geometry, attribute ); -function setValueM2Array( gl, v ) { + } - const data = flatten( v, this.size, 4 ); + function getWireframeAttribute( geometry ) { - gl.uniformMatrix2fv( this.addr, false, data ); + const currentAttribute = wireframeAttributes.get( geometry ); -} + if ( currentAttribute ) { -function setValueM3Array( gl, v ) { + const geometryIndex = geometry.index; - const data = flatten( v, this.size, 9 ); + if ( geometryIndex !== null ) { - gl.uniformMatrix3fv( this.addr, false, data ); + // if the attribute is obsolete, create a new one -} + if ( currentAttribute.version < geometryIndex.version ) { -function setValueM4Array( gl, v ) { + updateWireframeAttribute( geometry ); - const data = flatten( v, this.size, 16 ); + } - gl.uniformMatrix4fv( this.addr, false, data ); + } -} + } else { -// Array of textures (2D / Cube) + updateWireframeAttribute( geometry ); -function setValueT1Array( gl, v, textures ) { + } - const n = v.length; + return wireframeAttributes.get( geometry ); - const units = allocTexUnits( textures, n ); + } - gl.uniform1iv( this.addr, units ); + return { - for ( let i = 0; i !== n; ++ i ) { + get: get, + update: update, - textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] ); + getWireframeAttribute: getWireframeAttribute - } + }; } -function setValueT6Array( gl, v, textures ) { - - const n = v.length; +function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { - const units = allocTexUnits( textures, n ); + const isWebGL2 = capabilities.isWebGL2; - gl.uniform1iv( this.addr, units ); + let mode; - for ( let i = 0; i !== n; ++ i ) { + function setMode( value ) { - textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + mode = value; } -} - -// Helper to pick the right setter for a pure (bottom-level) array - -function getPureArraySetter( type ) { + let type, bytesPerElement; - switch ( type ) { + function setIndex( value ) { - case 0x1406: return setValueV1fArray; // FLOAT - case 0x8b50: return setValueV2fArray; // _VEC2 - case 0x8b51: return setValueV3fArray; // _VEC3 - case 0x8b52: return setValueV4fArray; // _VEC4 + type = value.type; + bytesPerElement = value.bytesPerElement; - case 0x8b5a: return setValueM2Array; // _MAT2 - case 0x8b5b: return setValueM3Array; // _MAT3 - case 0x8b5c: return setValueM4Array; // _MAT4 + } - case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL - case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 - case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 - case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + function render( start, count ) { - case 0x8b5e: // SAMPLER_2D - case 0x8d66: // SAMPLER_EXTERNAL_OES - case 0x8dca: // INT_SAMPLER_2D - case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D - case 0x8b62: // SAMPLER_2D_SHADOW - return setValueT1Array; + gl.drawElements( mode, count, type, start * bytesPerElement ); - case 0x8b60: // SAMPLER_CUBE - case 0x8dcc: // INT_SAMPLER_CUBE - case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE - case 0x8dc5: // SAMPLER_CUBE_SHADOW - return setValueT6Array; + info.update( count, mode, 1 ); } -} - -// --- Uniform Classes --- + function renderInstances( start, count, primcount ) { -function SingleUniform( id, activeInfo, addr ) { + if ( primcount === 0 ) return; - this.id = id; - this.addr = addr; - this.cache = []; - this.setValue = getSingularSetter( activeInfo.type ); + let extension, methodName; - // this.path = activeInfo.name; // DEBUG + if ( isWebGL2 ) { -} + extension = gl; + methodName = 'drawElementsInstanced'; -function PureArrayUniform( id, activeInfo, addr ) { + } else { - this.id = id; - this.addr = addr; - this.cache = []; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawElementsInstancedANGLE'; - // this.path = activeInfo.name; // DEBUG + if ( extension === null ) { -} + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; -PureArrayUniform.prototype.updateCache = function ( data ) { + } - const cache = this.cache; + } - if ( data instanceof Float32Array && cache.length !== data.length ) { + extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); - this.cache = new Float32Array( data.length ); + info.update( count, mode, primcount ); } - copyArray( cache, data ); + // -}; + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; -function StructuredUniform( id ) { +} - this.id = id; +function WebGLInfo( gl ) { - this.seq = []; - this.map = {}; - -} - -StructuredUniform.prototype.setValue = function ( gl, value, textures ) { + const memory = { + geometries: 0, + textures: 0 + }; - const seq = this.seq; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + function update( count, mode, instanceCount ) { - const u = seq[ i ]; - u.setValue( gl, value[ u.id ], textures ); + render.calls ++; - } + switch ( mode ) { -}; + case 4: + render.triangles += instanceCount * ( count / 3 ); + break; -// --- Top-level --- + case 1: + render.lines += instanceCount * ( count / 2 ); + break; -// Parser - builds up the property tree from the path strings + case 3: + render.lines += instanceCount * ( count - 1 ); + break; -const RePathPart = /(\w+)(\])?(\[|\.)?/g; + case 2: + render.lines += instanceCount * count; + break; -// 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. + case 0: + render.points += instanceCount * count; + break; -function addUniform( container, uniformObject ) { + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + } -} + } -function parseUniform( activeInfo, addr, container ) { + function reset() { - const path = activeInfo.name, - pathLength = path.length; + render.frame ++; + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + } - while ( true ) { + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; - const match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex; +} - let id = match[ 1 ]; - const idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; +function numericalSort( a, b ) { - if ( idIsIndex ) id = id | 0; // convert to integer + return a[ 0 ] - b[ 0 ]; - if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { +} - // bare name or "pure" bottom-level array "[0]" suffix +function absNumericalSort( a, b ) { - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); - break; +} - } else { +function WebGLMorphtargets( gl, capabilities, textures ) { - // step into inner node / create it in case it doesn't exist + const influencesList = {}; + const morphInfluences = new Float32Array( 8 ); + const morphTextures = new WeakMap(); + const morph = new Vector4(); - const map = container.map; - let next = map[ id ]; + const workInfluences = []; - if ( next === undefined ) { + for ( let i = 0; i < 8; i ++ ) { - next = new StructuredUniform( id ); - addUniform( container, next ); + workInfluences[ i ] = [ i, 0 ]; - } + } - container = next; + function update( object, geometry, material, program ) { - } + const objectInfluences = object.morphTargetInfluences; - } + if ( capabilities.isWebGL2 === true ) { -} + // instead of using attributes, the WebGL 2 code path encodes morph targets + // into an array of data textures. Each layer represents a single morph target. -// Root Container + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; -function WebGLUniforms( gl, program ) { + let entry = morphTextures.get( geometry ); - this.seq = []; - this.map = {}; + if ( entry === undefined || entry.count !== morphTargetsCount ) { - const n = gl.getProgramParameter( program, 35718 ); + if ( entry !== undefined ) entry.texture.dispose(); - for ( let i = 0; i < n; ++ i ) { + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; - const info = gl.getActiveUniform( program, i ), - addr = gl.getUniformLocation( program, info.name ); + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; - parseUniform( info, addr, this ); + let vertexDataCount = 0; - } + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; -} + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; -WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) { + if ( width > capabilities.maxTextureSize ) { - const u = this.map[ name ]; + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; - if ( u !== undefined ) u.setValue( gl, value, textures ); + } -}; + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); -WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; - const v = object[ name ]; + // fill buffer - if ( v !== undefined ) this.setValue( gl, name, v ); + const vertexDataStride = vertexDataCount * 4; -}; + for ( let i = 0; i < morphTargetsCount; i ++ ) { + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; -// Static interface + const offset = width * height * 4 * i; -WebGLUniforms.upload = function ( gl, seq, values, textures ) { + for ( let j = 0; j < morphTarget.count; j ++ ) { - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + const stride = j * vertexDataStride; - const u = seq[ i ], - v = values[ u.id ]; + if ( hasMorphPosition === true ) { - if ( v.needsUpdate !== false ) { + morph.fromBufferAttribute( morphTarget, j ); - // note: always updating when .needsUpdate is undefined - u.setValue( gl, v.value, textures ); + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; - } + } - } + if ( hasMorphNormals === true ) { -}; + morph.fromBufferAttribute( morphNormal, j ); -WebGLUniforms.seqWithValue = function ( seq, values ) { + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; - const r = []; + } - for ( let i = 0, n = seq.length; i !== n; ++ i ) { + if ( hasMorphColors === true ) { - const u = seq[ i ]; - if ( u.id in values ) r.push( u ); + morph.fromBufferAttribute( morphColor, j ); - } + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; - return r; + } -}; + } -function WebGLShader( gl, type, string ) { + } - const shader = gl.createShader( type ); + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; - gl.shaderSource( shader, string ); - gl.compileShader( shader ); + morphTextures.set( geometry, entry ); - return shader; + function disposeTexture() { -} + texture.dispose(); -let programIdCount = 0; + morphTextures.delete( geometry ); -function addLineNumbers( string ) { + geometry.removeEventListener( 'dispose', disposeTexture ); - const lines = string.split( '\n' ); + } - for ( let i = 0; i < lines.length; i ++ ) { + geometry.addEventListener( 'dispose', disposeTexture ); - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; + } - } + // - return lines.join( '\n' ); + let morphInfluencesSum = 0; -} + for ( let i = 0; i < objectInfluences.length; i ++ ) { -function getEncodingComponents( encoding ) { + morphInfluencesSum += objectInfluences[ i ]; - switch ( encoding ) { + } - 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 ) )' ]; - case LogLuvEncoding: - return [ 'LogLuv', '( value )' ]; - default: - console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding ); - return [ 'Linear', '( value )' ]; + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - } + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); -} + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); -function getShaderErrors( gl, shader, type ) { - const status = gl.getShaderParameter( shader, 35713 ); - const log = gl.getShaderInfoLog( shader ).trim(); + } else { - if ( status && log === '' ) return ''; + // When object doesn't have morph target influences defined, we treat it as a 0-length array + // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences - // --enable-privileged-webgl-extension - // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + const length = objectInfluences === undefined ? 0 : objectInfluences.length; - const source = gl.getShaderSource( shader ); + let influences = influencesList[ geometry.id ]; - return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source ); + if ( influences === undefined || influences.length !== length ) { -} + // initialise list -function getTexelDecodingFunction( functionName, encoding ) { + influences = []; - const components = getEncodingComponents( encoding ); - return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }'; + for ( let i = 0; i < length; i ++ ) { -} + influences[ i ] = [ i, 0 ]; -function getTexelEncodingFunction( functionName, encoding ) { + } - const components = getEncodingComponents( encoding ); - return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; + influencesList[ geometry.id ] = influences; -} + } -function getToneMappingFunction( functionName, toneMapping ) { + // Collect influences - let toneMappingName; + for ( let i = 0; i < length; i ++ ) { - switch ( toneMapping ) { + const influence = influences[ i ]; - case LinearToneMapping: - toneMappingName = 'Linear'; - break; + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; - case ReinhardToneMapping: - toneMappingName = 'Reinhard'; - break; + } - case CineonToneMapping: - toneMappingName = 'OptimizedCineon'; - break; + influences.sort( absNumericalSort ); - case ACESFilmicToneMapping: - toneMappingName = 'ACESFilmic'; - break; + for ( let i = 0; i < 8; i ++ ) { - case CustomToneMapping: - toneMappingName = 'Custom'; - break; + if ( i < length && influences[ i ][ 1 ] ) { - default: - console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); - toneMappingName = 'Linear'; + workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; + workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; - } + } else { - return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; + workInfluences[ i ][ 1 ] = 0; -} + } -function generateExtensions( parameters ) { + } - const chunks = [ - ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', - ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', - ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', - ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' - ]; + workInfluences.sort( numericalSort ); - return chunks.filter( filterEmptyLine ).join( '\n' ); + const morphTargets = geometry.morphAttributes.position; + const morphNormals = geometry.morphAttributes.normal; -} + let morphInfluencesSum = 0; -function generateDefines( defines ) { + for ( let i = 0; i < 8; i ++ ) { - const chunks = []; + const influence = workInfluences[ i ]; + const index = influence[ 0 ]; + const value = influence[ 1 ]; - for ( const name in defines ) { + if ( index !== Number.MAX_SAFE_INTEGER && value ) { - const value = defines[ name ]; + if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { - if ( value === false ) continue; + geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); - chunks.push( '#define ' + name + ' ' + value ); + } - } + if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { - return chunks.join( '\n' ); + geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); -} + } -function fetchAttributeLocations( gl, program ) { + morphInfluences[ i ] = value; + morphInfluencesSum += value; - const attributes = {}; + } else { - const n = gl.getProgramParameter( program, 35721 ); + if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { - for ( let i = 0; i < n; i ++ ) { + geometry.deleteAttribute( 'morphTarget' + i ); - const info = gl.getActiveAttrib( program, i ); - const name = info.name; + } - // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { - attributes[ name ] = gl.getAttribLocation( program, name ); + geometry.deleteAttribute( 'morphNormal' + i ); - } + } - return attributes; + morphInfluences[ i ] = 0; -} + } -function filterEmptyLine( string ) { + } - return string !== ''; + // GLSL shader uses formula baseinfluence * base + sum(target * influence) + // This allows us to switch between absolute morphs and relative morphs without changing shader code + // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; -} + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); -function replaceLightNums( string, parameters ) { + } - return string - .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) - .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) - .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) - .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) - .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) - .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) - .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) - .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + } -} + return { -function replaceClippingPlaneNums( string, parameters ) { + update: update - return string - .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) - .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + }; } -// Resolve Includes - -const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; +function WebGLObjects( gl, geometries, attributes, info ) { -function resolveIncludes( string ) { + let updateMap = new WeakMap(); - return string.replace( includePattern, includeReplacer ); + function update( object ) { -} + const frame = info.render.frame; -function includeReplacer( match, include ) { + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); - const string = ShaderChunk[ include ]; + // Update once per frame - if ( string === undefined ) { + if ( updateMap.get( buffergeometry ) !== frame ) { - throw new Error( 'Can not resolve #include <' + include + '>' ); + geometries.update( buffergeometry ); - } + updateMap.set( buffergeometry, frame ); - return resolveIncludes( string ); + } -} + if ( object.isInstancedMesh ) { -// Unroll Loops + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { -const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; -const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + object.addEventListener( 'dispose', onInstancedMeshDispose ); -function unrollLoops( string ) { + } - return string - .replace( unrollLoopPattern, loopReplacer ) - .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer ); + attributes.update( object.instanceMatrix, 34962 ); -} + if ( object.instanceColor !== null ) { -function deprecatedLoopReplacer( match, start, end, snippet ) { + attributes.update( object.instanceColor, 34962 ); - console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' ); - return loopReplacer( match, start, end, snippet ); + } -} + } -function loopReplacer( match, start, end, snippet ) { + return buffergeometry; - let string = ''; + } - for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + function dispose() { - string += snippet - .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) - .replace( /UNROLLED_LOOP_INDEX/g, i ); + updateMap = new WeakMap(); } - return string; - -} - -// + function onInstancedMeshDispose( event ) { -function generatePrecision( parameters ) { + const instancedMesh = event.target; - let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); - if ( parameters.precision === 'highp' ) { + attributes.remove( instancedMesh.instanceMatrix ); - precisionstring += '\n#define HIGH_PRECISION'; + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); - } else if ( parameters.precision === 'mediump' ) { + } - precisionstring += '\n#define MEDIUM_PRECISION'; + return { - } else if ( parameters.precision === 'lowp' ) { + update: update, + dispose: dispose - precisionstring += '\n#define LOW_PRECISION'; + }; - } +} - return precisionstring; +/** + * 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 )'. + * + * + * 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, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ -} +const emptyTexture = /*@__PURE__*/ new Texture(); +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); -function generateShadowMapTypeDefine( parameters ) { +// --- Utilities --- - let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; +// Array Caches (provide typed arrays for temporary by size) - if ( parameters.shadowMapType === PCFShadowMap ) { +const arrayCacheF32 = []; +const arrayCacheI32 = []; - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; +// Float32Array caches used for uploading Matrix uniforms - } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { +const mat4array = new Float32Array( 16 ); +const mat3array = new Float32Array( 9 ); +const mat2array = new Float32Array( 4 ); - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; +// Flattening for arrays of vectors and matrices - } else if ( parameters.shadowMapType === VSMShadowMap ) { +function flatten( array, nBlocks, blockSize ) { - shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + const firstElem = array[ 0 ]; - } + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - return shadowMapTypeDefine; + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; -} + if ( r === undefined ) { -function generateEnvMapTypeDefine( parameters ) { + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + } - if ( parameters.envMap ) { + if ( nBlocks !== 0 ) { - switch ( parameters.envMapMode ) { + firstElem.toArray( r, 0 ); - case CubeReflectionMapping: - case CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { - case CubeUVReflectionMapping: - case CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; + offset += blockSize; + array[ i ].toArray( r, offset ); } } - return envMapTypeDefine; + return r; } -function generateEnvMapModeDefine( parameters ) { +function arraysEqual( a, b ) { - let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + if ( a.length !== b.length ) return false; - if ( parameters.envMap ) { + for ( let i = 0, l = a.length; i < l; i ++ ) { - switch ( parameters.envMapMode ) { + if ( a[ i ] !== b[ i ] ) return false; - case CubeRefractionMapping: - case CubeUVRefractionMapping: + } - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; + return true; - } +} - } +function copyArray( a, b ) { - return envMapModeDefine; + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } } -function generateEnvMapBlendingDefine( parameters ) { +// Texture unit allocation - let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; +function allocTexUnits( textures, n ) { - if ( parameters.envMap ) { + let r = arrayCacheI32[ n ]; - switch ( parameters.combine ) { + if ( r === undefined ) { - case MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - case MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; + } - case AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; + for ( let i = 0; i !== n; ++ i ) { - } + r[ i ] = textures.allocateTextureUnit(); } - return envMapBlendingDefine; + return r; } -function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { - - const gl = renderer.getContext(); +// --- Setters --- - const defines = parameters.defines; +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. - let vertexShader = parameters.vertexShader; - let fragmentShader = parameters.fragmentShader; +// Single scalar - const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); - const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); - const envMapModeDefine = generateEnvMapModeDefine( parameters ); - const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); +function setValueV1f( gl, v ) { + const cache = this.cache; - const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + if ( cache[ 0 ] === v ) return; - const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + gl.uniform1f( this.addr, v ); - const customDefines = generateDefines( defines ); + cache[ 0 ] = v; - const program = gl.createProgram(); +} - let prefixVertex, prefixFragment; - let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; +// Single float vector (from flat array or THREE.VectorN) - if ( parameters.isRawShaderMaterial ) { +function setValueV2f( gl, v ) { - prefixVertex = [ + const cache = this.cache; - customDefines + if ( v.x !== undefined ) { - ].filter( filterEmptyLine ).join( '\n' ); + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { - if ( prefixVertex.length > 0 ) { + gl.uniform2f( this.addr, v.x, v.y ); - prefixVertex += '\n'; + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; } - prefixFragment = [ + } else { - customExtensions, - customDefines + if ( arraysEqual( cache, v ) ) return; - ].filter( filterEmptyLine ).join( '\n' ); + gl.uniform2fv( this.addr, v ); - if ( prefixFragment.length > 0 ) { + copyArray( cache, v ); - prefixFragment += '\n'; + } - } +} - } else { +function setValueV3f( gl, v ) { - prefixVertex = [ + const cache = this.cache; - generatePrecision( parameters ), + if ( v.x !== undefined ) { - '#define SHADER_NAME ' + parameters.shaderName, + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { - customDefines, + gl.uniform3f( this.addr, v.x, v.y, v.z ); - parameters.instancing ? '#define USE_INSTANCING' : '', - parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + } - '#define GAMMA_FACTOR ' + gammaFactorDefine, + } else if ( v.r !== undefined ) { - '#define MAX_BONES ' + parameters.maxBones, - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { - 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', - ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + gl.uniform3f( this.addr, v.r, v.g, v.b ); - parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', - parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', - parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_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.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; - parameters.vertexTangents ? '#define USE_TANGENT' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', - parameters.vertexUvs ? '#define USE_UV' : '', - parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + } - parameters.flatShading ? '#define FLAT_SHADED' : '', + } else { - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', + if ( arraysEqual( cache, v ) ) return; - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + gl.uniform3fv( this.addr, v ); - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + copyArray( cache, v ); - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + } - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', +} - 'uniform mat4 modelMatrix;', - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;', - 'uniform vec3 cameraPosition;', - 'uniform bool isOrthographic;', +function setValueV4f( gl, v ) { - '#ifdef USE_INSTANCING', + const cache = this.cache; - ' attribute mat4 instanceMatrix;', + if ( v.x !== undefined ) { - '#endif', + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { - '#ifdef USE_INSTANCING_COLOR', + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - ' attribute vec3 instanceColor;', + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; - '#endif', + } - 'attribute vec3 position;', - 'attribute vec3 normal;', - 'attribute vec2 uv;', + } else { - '#ifdef USE_TANGENT', + if ( arraysEqual( cache, v ) ) return; - ' attribute vec4 tangent;', + gl.uniform4fv( this.addr, v ); - '#endif', + copyArray( cache, v ); - '#ifdef USE_COLOR', + } - ' attribute vec3 color;', +} - '#endif', +// Single matrix (from flat array or THREE.MatrixN) - '#ifdef USE_MORPHTARGETS', +function setValueM2( gl, v ) { - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + const cache = this.cache; + const elements = v.elements; - ' #ifdef USE_MORPHNORMALS', + if ( elements === undefined ) { - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + if ( arraysEqual( cache, v ) ) return; - ' #else', + gl.uniformMatrix2fv( this.addr, false, v ); - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', + copyArray( cache, v ); - ' #endif', + } else { - '#endif', + if ( arraysEqual( cache, elements ) ) return; - '#ifdef USE_SKINNING', + mat2array.set( elements ); - ' attribute vec4 skinIndex;', - ' attribute vec4 skinWeight;', + gl.uniformMatrix2fv( this.addr, false, mat2array ); - '#endif', + copyArray( cache, elements ); - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); +} - prefixFragment = [ +function setValueM3( gl, v ) { - customExtensions, + const cache = this.cache; + const elements = v.elements; - generatePrecision( parameters ), + if ( elements === undefined ) { - '#define SHADER_NAME ' + parameters.shaderName, + if ( arraysEqual( cache, v ) ) return; - customDefines, + gl.uniformMatrix3fv( this.addr, false, v ); - parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer + copyArray( cache, v ); - '#define GAMMA_FACTOR ' + gammaFactorDefine, + } else { - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + if ( arraysEqual( cache, elements ) ) return; - parameters.map ? '#define USE_MAP' : '', - parameters.matcap ? '#define USE_MATCAP' : '', - 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', - ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', - parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', - parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', - parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + mat3array.set( elements ); - parameters.sheen ? '#define USE_SHEEN' : '', - parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + gl.uniformMatrix3fv( this.addr, false, mat3array ); - parameters.vertexTangents ? '#define USE_TANGENT' : '', - parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', - parameters.vertexUvs ? '#define USE_UV' : '', - parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + copyArray( cache, elements ); - parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + } - parameters.flatShading ? '#define FLAT_SHADED' : '', +} - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', +function setValueM4( gl, v ) { - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + const cache = this.cache; + const elements = v.elements; - parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + if ( elements === undefined ) { - parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', + if ( arraysEqual( cache, v ) ) return; - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + gl.uniformMatrix4fv( this.addr, false, v ); - ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '', + copyArray( cache, v ); - 'uniform mat4 viewMatrix;', - 'uniform vec3 cameraPosition;', - 'uniform bool isOrthographic;', + } else { - ( 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 ) : '', + if ( arraysEqual( cache, elements ) ) return; - parameters.dithering ? '#define DITHERING' : '', + mat4array.set( elements ); - ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below - parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', - parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '', - parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', - parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', - parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '', - getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), + gl.uniformMatrix4fv( this.addr, false, mat4array ); - parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + copyArray( cache, elements ); - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); +} - } +// Single integer / boolean - vertexShader = resolveIncludes( vertexShader ); - vertexShader = replaceLightNums( vertexShader, parameters ); - vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); +function setValueV1i( gl, v ) { - fragmentShader = resolveIncludes( fragmentShader ); - fragmentShader = replaceLightNums( fragmentShader, parameters ); - fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + const cache = this.cache; - vertexShader = unrollLoops( vertexShader ); - fragmentShader = unrollLoops( fragmentShader ); + if ( cache[ 0 ] === v ) return; - if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + gl.uniform1i( this.addr, v ); - // GLSL 3.0 conversion for built-in materials and ShaderMaterial + cache[ 0 ] = v; - versionString = '#version 300 es\n'; +} - prefixVertex = [ - '#define attribute in', - '#define varying out', - '#define texture2D texture' - ].join( '\n' ) + '\n' + prefixVertex; +// Single integer / boolean vector (from flat array) - prefixFragment = [ - '#define varying in', - ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;', - ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', - '#define gl_FragDepthEXT gl_FragDepth', - '#define texture2D texture', - '#define textureCube texture', - '#define texture2DProj textureProj', - '#define texture2DLodEXT textureLod', - '#define texture2DProjLodEXT textureProjLod', - '#define textureCubeLodEXT textureLod', - '#define texture2DGradEXT textureGrad', - '#define texture2DProjGradEXT textureProjGrad', - '#define textureCubeGradEXT textureGrad' - ].join( '\n' ) + '\n' + prefixFragment; +function setValueV2i( gl, v ) { - } + const cache = this.cache; - const vertexGlsl = versionString + prefixVertex + vertexShader; - const fragmentGlsl = versionString + prefixFragment + fragmentShader; + if ( arraysEqual( cache, v ) ) return; - // console.log( '*VERTEX*', vertexGlsl ); - // console.log( '*FRAGMENT*', fragmentGlsl ); + gl.uniform2iv( this.addr, v ); - const glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); - const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); + copyArray( cache, v ); - gl.attachShader( program, glVertexShader ); - gl.attachShader( program, glFragmentShader ); +} - // Force a particular attribute to index 0. +function setValueV3i( gl, v ) { - if ( parameters.index0AttributeName !== undefined ) { + const cache = this.cache; - gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + if ( arraysEqual( cache, v ) ) return; - } else if ( parameters.morphTargets === true ) { + gl.uniform3iv( this.addr, v ); - // programs with morphTargets displace position out of attribute 0 - gl.bindAttribLocation( program, 0, 'position' ); + copyArray( cache, v ); - } +} - gl.linkProgram( program ); +function setValueV4i( gl, v ) { - // check for link errors - if ( renderer.debug.checkShaderErrors ) { + const cache = this.cache; - const programLog = gl.getProgramInfoLog( program ).trim(); - const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); - const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + if ( arraysEqual( cache, v ) ) return; - let runnable = true; - let haveDiagnostics = true; + gl.uniform4iv( this.addr, v ); - if ( gl.getProgramParameter( program, 35714 ) === false ) { + copyArray( cache, v ); - runnable = false; +} - const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); - const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); +// Single unsigned integer - console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors ); +function setValueV1ui( gl, v ) { - } else if ( programLog !== '' ) { + const cache = this.cache; - console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); + if ( cache[ 0 ] === v ) return; - } else if ( vertexLog === '' || fragmentLog === '' ) { + gl.uniform1ui( this.addr, v ); - haveDiagnostics = false; + cache[ 0 ] = v; - } +} - if ( haveDiagnostics ) { +// Single unsigned integer vector (from flat array) - this.diagnostics = { +function setValueV2ui( gl, v ) { - runnable: runnable, + const cache = this.cache; - programLog: programLog, + if ( arraysEqual( cache, v ) ) return; - vertexShader: { + gl.uniform2uiv( this.addr, v ); - log: vertexLog, - prefix: prefixVertex + copyArray( cache, v ); - }, +} - fragmentShader: { +function setValueV3ui( gl, v ) { - log: fragmentLog, - prefix: prefixFragment + const cache = this.cache; - } + if ( arraysEqual( cache, v ) ) return; - }; + gl.uniform3uiv( this.addr, v ); - } + copyArray( cache, v ); - } +} - // Clean up +function setValueV4ui( gl, v ) { - // Crashes in iOS9 and iOS10. #18402 - // gl.detachShader( program, glVertexShader ); - // gl.detachShader( program, glFragmentShader ); + const cache = this.cache; - gl.deleteShader( glVertexShader ); - gl.deleteShader( glFragmentShader ); + if ( arraysEqual( cache, v ) ) return; - // set up caching for uniform locations + gl.uniform4uiv( this.addr, v ); - let cachedUniforms; + copyArray( cache, v ); - this.getUniforms = function () { +} - if ( cachedUniforms === undefined ) { - cachedUniforms = new WebGLUniforms( gl, program ); +// Single texture (2D / Cube) - } +function setValueT1( gl, v, textures ) { - return cachedUniforms; + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - }; + if ( cache[ 0 ] !== unit ) { - // set up caching for attribute locations + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - let cachedAttributes; + } - this.getAttributes = function () { + textures.setTexture2D( v || emptyTexture, unit ); - if ( cachedAttributes === undefined ) { +} - cachedAttributes = fetchAttributeLocations( gl, program ); +function setValueT3D1( gl, v, textures ) { - } + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - return cachedAttributes; + if ( cache[ 0 ] !== unit ) { - }; + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - // free resource + } - this.destroy = function () { + textures.setTexture3D( v || empty3dTexture, unit ); - bindingStates.releaseStatesOfProgram( this ); +} - gl.deleteProgram( program ); - this.program = undefined; +function setValueT6( gl, v, textures ) { - }; + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - // + if ( cache[ 0 ] !== unit ) { - this.name = parameters.shaderName; - this.id = programIdCount ++; - this.cacheKey = cacheKey; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - return this; + } -} + textures.setTextureCube( v || emptyCubeTexture, unit ); -function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) { +} - const programs = []; +function setValueT2DArray1( gl, v, textures ) { - const isWebGL2 = capabilities.isWebGL2; - const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; - const floatVertexTextures = capabilities.floatVertexTextures; - const maxVertexUniforms = capabilities.maxVertexUniforms; - const vertexTextures = capabilities.vertexTextures; + const cache = this.cache; + const unit = textures.allocateTextureUnit(); - let precision = capabilities.precision; + if ( cache[ 0 ] !== unit ) { - const shaderIDs = { - MeshDepthMaterial: 'depth', - MeshDistanceMaterial: 'distanceRGBA', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshToonMaterial: 'toon', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - MeshMatcapMaterial: 'matcap', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points', - ShadowMaterial: 'shadow', - SpriteMaterial: 'sprite' - }; + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - const parameterNames = [ - 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', - 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', - 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', - 'roughnessMap', 'metalnessMap', 'gradientMap', - 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', - 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', - 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', - 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha', - 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', - 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', - 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', - 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', - 'sheen', 'transmissionMap' - ]; + } - function getMaxBones( object ) { + textures.setTexture2DArray( v || emptyArrayTexture, unit ); - const skeleton = object.skeleton; - const bones = skeleton.bones; +} - if ( floatVertexTextures ) { +// Helper to pick the right setter for the singular case - return 1024; +function getSingularSetter( type ) { - } else { + switch ( type ) { - // 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) + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 - const nVertexUniforms = maxVertexUniforms; - const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 - const maxBones = Math.min( nVertexMatrices, bones.length ); + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 - if ( maxBones < bones.length ) { + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 - console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' ); - return 0; + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; - } + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; - return maxBones; + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; - } + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; } - function getTextureEncodingFromMap( map ) { +} - let encoding; - if ( map && map.isTexture ) { +// Array of scalars - encoding = map.encoding; +function setValueV1fArray( gl, v ) { - } else if ( map && map.isWebGLRenderTarget ) { + gl.uniform1fv( this.addr, v ); - console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' ); - encoding = map.texture.encoding; +} - } else { +// Array of vectors (from flat array or array of THREE.VectorN) - encoding = LinearEncoding; +function setValueV2fArray( gl, v ) { - } + const data = flatten( v, this.size, 2 ); - return encoding; + gl.uniform2fv( this.addr, data ); - } +} - function getParameters( material, lights, shadows, scene, object ) { +function setValueV3fArray( gl, v ) { - const fog = scene.fog; - const environment = material.isMeshStandardMaterial ? scene.environment : null; + const data = flatten( v, this.size, 3 ); - const envMap = cubemaps.get( material.envMap || environment ); + gl.uniform3fv( this.addr, data ); - const shaderID = shaderIDs[ material.type ]; +} - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) +function setValueV4fArray( gl, v ) { - const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0; + const data = flatten( v, this.size, 4 ); - if ( material.precision !== null ) { + gl.uniform4fv( this.addr, data ); - precision = capabilities.getMaxPrecision( material.precision ); - - if ( precision !== material.precision ) { +} - console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); +// Array of matrices (from flat array or array of THREE.MatrixN) - } +function setValueM2Array( gl, v ) { - } + const data = flatten( v, this.size, 4 ); - let vertexShader, fragmentShader; + gl.uniformMatrix2fv( this.addr, false, data ); - if ( shaderID ) { +} - const shader = ShaderLib[ shaderID ]; +function setValueM3Array( gl, v ) { - vertexShader = shader.vertexShader; - fragmentShader = shader.fragmentShader; + const data = flatten( v, this.size, 9 ); - } else { + gl.uniformMatrix3fv( this.addr, false, data ); - vertexShader = material.vertexShader; - fragmentShader = material.fragmentShader; +} - } +function setValueM4Array( gl, v ) { - const currentRenderTarget = renderer.getRenderTarget(); + const data = flatten( v, this.size, 16 ); - const parameters = { + gl.uniformMatrix4fv( this.addr, false, data ); - isWebGL2: isWebGL2, +} - shaderID: shaderID, - shaderName: material.type, +// Array of integer / boolean - vertexShader: vertexShader, - fragmentShader: fragmentShader, - defines: material.defines, +function setValueV1iArray( gl, v ) { - isRawShaderMaterial: material.isRawShaderMaterial === true, - glslVersion: material.glslVersion, + gl.uniform1iv( this.addr, v ); - precision: precision, +} - instancing: object.isInstancedMesh === true, - instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, +// Array of integer / boolean vectors (from flat array) - supportsVertexTextures: vertexTextures, - outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding, - map: !! material.map, - mapEncoding: getTextureEncodingFromMap( material.map ), - matcap: !! material.matcap, - matcapEncoding: getTextureEncodingFromMap( material.matcap ), - envMap: !! envMap, - envMapMode: envMap && envMap.mapping, - envMapEncoding: getTextureEncodingFromMap( envMap ), - envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ), - lightMap: !! material.lightMap, - lightMapEncoding: getTextureEncodingFromMap( material.lightMap ), - aoMap: !! material.aoMap, - emissiveMap: !! material.emissiveMap, - emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ), - bumpMap: !! material.bumpMap, - normalMap: !! material.normalMap, - objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, - tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, - clearcoatMap: !! material.clearcoatMap, - clearcoatRoughnessMap: !! material.clearcoatRoughnessMap, - clearcoatNormalMap: !! material.clearcoatNormalMap, - displacementMap: !! material.displacementMap, - roughnessMap: !! material.roughnessMap, - metalnessMap: !! material.metalnessMap, - specularMap: !! material.specularMap, - alphaMap: !! material.alphaMap, +function setValueV2iArray( gl, v ) { - gradientMap: !! material.gradientMap, + gl.uniform2iv( this.addr, v ); - sheen: !! material.sheen, +} - transmissionMap: !! material.transmissionMap, +function setValueV3iArray( gl, v ) { - combine: material.combine, + gl.uniform3iv( this.addr, v ); - vertexTangents: ( material.normalMap && material.vertexTangents ), - vertexColors: material.vertexColors, - vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap, - uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap, +} - fog: !! fog, - useFog: material.fog, - fogExp2: ( fog && fog.isFogExp2 ), +function setValueV4iArray( gl, v ) { - flatShading: !! material.flatShading, + gl.uniform4iv( this.addr, v ); - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: logarithmicDepthBuffer, +} - skinning: material.skinning && maxBones > 0, - maxBones: maxBones, - useVertexTexture: floatVertexTextures, +// Array of unsigned integer - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: renderer.maxMorphTargets, - maxMorphNormals: renderer.maxMorphNormals, +function setValueV1uiArray( gl, v ) { - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numRectAreaLights: lights.rectArea.length, - numHemiLights: lights.hemi.length, + gl.uniform1uiv( this.addr, v ); - numDirLightShadows: lights.directionalShadowMap.length, - numPointLightShadows: lights.pointShadowMap.length, - numSpotLightShadows: lights.spotShadowMap.length, +} - numClippingPlanes: clipping.numPlanes, - numClipIntersection: clipping.numIntersection, +// Array of unsigned integer vectors (from flat array) - dithering: material.dithering, +function setValueV2uiArray( gl, v ) { - shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, - shadowMapType: renderer.shadowMap.type, + gl.uniform2uiv( this.addr, v ); - toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, +} - premultipliedAlpha: material.premultipliedAlpha, +function setValueV3uiArray( gl, v ) { - alphaTest: material.alphaTest, - doubleSided: material.side === DoubleSide, - flipSided: material.side === BackSide, + gl.uniform3uiv( this.addr, v ); - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false, +} - index0AttributeName: material.index0AttributeName, +function setValueV4uiArray( gl, v ) { - extensionDerivatives: material.extensions && material.extensions.derivatives, - extensionFragDepth: material.extensions && material.extensions.fragDepth, - extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, - extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, + gl.uniform4uiv( this.addr, v ); - rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ), - rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ), - rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ), +} - customProgramCacheKey: material.customProgramCacheKey() - }; +// Array of textures (2D / 3D / Cube / 2DArray) - return parameters; +function setValueT1Array( gl, v, textures ) { - } + const n = v.length; - function getProgramCacheKey( parameters ) { + const units = allocTexUnits( textures, n ); - const array = []; + gl.uniform1iv( this.addr, units ); - if ( parameters.shaderID ) { + for ( let i = 0; i !== n; ++ i ) { - array.push( parameters.shaderID ); + textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - } else { + } - array.push( parameters.fragmentShader ); - array.push( parameters.vertexShader ); +} - } +function setValueT3DArray( gl, v, textures ) { - if ( parameters.defines !== undefined ) { + const n = v.length; - for ( const name in parameters.defines ) { + const units = allocTexUnits( textures, n ); - array.push( name ); - array.push( parameters.defines[ name ] ); + gl.uniform1iv( this.addr, units ); - } + for ( let i = 0; i !== n; ++ i ) { - } + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); - if ( parameters.isRawShaderMaterial === false ) { + } - for ( let i = 0; i < parameterNames.length; i ++ ) { +} - array.push( parameters[ parameterNames[ i ] ] ); +function setValueT6Array( gl, v, textures ) { - } + const n = v.length; - array.push( renderer.outputEncoding ); - array.push( renderer.gammaFactor ); + const units = allocTexUnits( textures, n ); - } + gl.uniform1iv( this.addr, units ); - array.push( parameters.customProgramCacheKey ); + for ( let i = 0; i !== n; ++ i ) { - return array.join(); + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); } - function getUniforms( material ) { - - const shaderID = shaderIDs[ material.type ]; - let uniforms; +} - if ( shaderID ) { +function setValueT2DArrayArray( gl, v, textures ) { - const shader = ShaderLib[ shaderID ]; - uniforms = UniformsUtils.clone( shader.uniforms ); + const n = v.length; - } else { + const units = allocTexUnits( textures, n ); - uniforms = material.uniforms; + gl.uniform1iv( this.addr, units ); - } + for ( let i = 0; i !== n; ++ i ) { - return uniforms; + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); } - function acquireProgram( parameters, cacheKey ) { +} - let program; - // Check if code has been already compiled - for ( let p = 0, pl = programs.length; p < pl; p ++ ) { +// Helper to pick the right setter for a pure (bottom-level) array - const preexistingProgram = programs[ p ]; +function getPureArraySetter( type ) { - if ( preexistingProgram.cacheKey === cacheKey ) { + switch ( type ) { - program = preexistingProgram; - ++ program.usedTimes; + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 - break; + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 - } + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 - } + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 - if ( program === undefined ) { + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; - program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); - programs.push( program ); + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; - } + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; - return program; + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; } - function releaseProgram( program ) { +} - if ( -- program.usedTimes === 0 ) { +// --- Uniform Classes --- - // Remove from unordered set - const i = programs.indexOf( program ); - programs[ i ] = programs[ programs.length - 1 ]; - programs.pop(); +class SingleUniform { - // Free WebGL resources - program.destroy(); + constructor( id, activeInfo, addr ) { - } + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); - } + // this.path = activeInfo.name; // DEBUG - return { - getParameters: getParameters, - getProgramCacheKey: getProgramCacheKey, - getUniforms: getUniforms, - acquireProgram: acquireProgram, - releaseProgram: releaseProgram, - // Exposed for resource monitoring & error feedback via renderer.info: - programs: programs - }; + } } -function WebGLProperties() { - - let properties = new WeakMap(); +class PureArrayUniform { - function get( object ) { + constructor( id, activeInfo, addr ) { - let map = properties.get( object ); + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - if ( map === undefined ) { + // this.path = activeInfo.name; // DEBUG - map = {}; - properties.set( object, map ); + } - } +} - return map; +class StructuredUniform { - } + constructor( id ) { - function remove( object ) { + this.id = id; - properties.delete( object ); + this.seq = []; + this.map = {}; } - function update( object, key, value ) { + setValue( gl, value, textures ) { - properties.get( object )[ key ] = value; + const seq = this.seq; - } + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - function dispose() { + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); - properties = new WeakMap(); + } } - return { - get: get, - remove: remove, - update: update, - dispose: dispose - }; - } -function painterSortStable( a, b ) { +// --- Top-level --- - if ( a.groupOrder !== b.groupOrder ) { +// Parser - builds up the property tree from the path strings - return a.groupOrder - b.groupOrder; +const RePathPart = /(\w+)(\])?(\[|\.)?/g; - } else if ( a.renderOrder !== b.renderOrder ) { +// 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 a.renderOrder - b.renderOrder; +function addUniform( container, uniformObject ) { - } else if ( a.program !== b.program ) { + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - return a.program.id - b.program.id; +} - } else if ( a.material.id !== b.material.id ) { +function parseUniform( activeInfo, addr, container ) { - return a.material.id - b.material.id; + const path = activeInfo.name, + pathLength = path.length; - } else if ( a.z !== b.z ) { + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - return a.z - b.z; + while ( true ) { - } else { + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; - return a.id - b.id; + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - } + if ( idIsIndex ) id = id | 0; // convert to integer -} + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { -function reversePainterSortStable( a, b ) { + // bare name or "pure" bottom-level array "[0]" suffix - if ( a.groupOrder !== b.groupOrder ) { + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - return a.groupOrder - b.groupOrder; + break; - } else if ( a.renderOrder !== b.renderOrder ) { + } else { - return a.renderOrder - b.renderOrder; + // step into inner node / create it in case it doesn't exist - } else if ( a.z !== b.z ) { + const map = container.map; + let next = map[ id ]; - return b.z - a.z; + if ( next === undefined ) { - } else { + next = new StructuredUniform( id ); + addUniform( container, next ); - return a.id - b.id; + } + + container = next; + + } } } +// Root Container -function WebGLRenderList( properties ) { +class WebGLUniforms { - const renderItems = []; - let renderItemsIndex = 0; + constructor( gl, program ) { - const opaque = []; - const transparent = []; + this.seq = []; + this.map = {}; - const defaultProgram = { id: - 1 }; + const n = gl.getProgramParameter( program, 35718 ); - function init() { + for ( let i = 0; i < n; ++ i ) { - renderItemsIndex = 0; + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); - opaque.length = 0; - transparent.length = 0; + parseUniform( info, addr, this ); + + } } - function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + setValue( gl, name, value, textures ) { - let renderItem = renderItems[ renderItemsIndex ]; - const materialProperties = properties.get( material ); + const u = this.map[ name ]; - if ( renderItem === undefined ) { + if ( u !== undefined ) u.setValue( gl, value, textures ); - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - program: materialProperties.program || defaultProgram, - groupOrder: groupOrder, - renderOrder: object.renderOrder, - z: z, - group: group - }; + } - renderItems[ renderItemsIndex ] = renderItem; + setOptional( gl, object, name ) { - } else { + const v = object[ name ]; - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.program = materialProperties.program || defaultProgram; - renderItem.groupOrder = groupOrder; - renderItem.renderOrder = object.renderOrder; - renderItem.z = z; - renderItem.group = group; + if ( v !== undefined ) this.setValue( gl, name, v ); - } + } - renderItemsIndex ++; + static upload( gl, seq, values, textures ) { - return renderItem; + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - } + const u = seq[ i ], + v = values[ u.id ]; - function push( object, geometry, material, groupOrder, z, group ) { + if ( v.needsUpdate !== false ) { - const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); - ( material.transparent === true ? transparent : opaque ).push( renderItem ); + } + + } } - function unshift( object, geometry, material, groupOrder, z, group ) { + static seqWithValue( seq, values ) { - const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + const r = []; - ( material.transparent === true ? transparent : opaque ).unshift( renderItem ); + for ( let i = 0, n = seq.length; i !== n; ++ i ) { - } + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); - function sort( customOpaqueSort, customTransparentSort ) { + } - if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); - if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + return r; } - function finish() { +} - // Clear references from inactive renderItems in the list +function WebGLShader( gl, type, string ) { - for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + const shader = gl.createShader( type ); - const renderItem = renderItems[ i ]; + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - if ( renderItem.id === null ) break; + return shader; - renderItem.id = null; - renderItem.object = null; - renderItem.geometry = null; - renderItem.material = null; - renderItem.program = null; - renderItem.group = null; +} - } +let programIdCount = 0; + +function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); } - return { + return lines2.join( '\n' ); - opaque: opaque, - transparent: transparent, +} - init: init, - push: push, - unshift: unshift, - finish: finish, +function getEncodingComponents( encoding ) { - sort: sort - }; + switch ( encoding ) { + + case LinearEncoding: + return [ 'Linear', '( value )' ]; + case sRGBEncoding: + return [ 'sRGB', '( value )' ]; + default: + console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding ); + return [ 'Linear', '( value )' ]; + + } } -function WebGLRenderLists( properties ) { +function getShaderErrors( gl, shader, type ) { - let lists = new WeakMap(); + const status = gl.getShaderParameter( shader, 35713 ); + const errors = gl.getShaderInfoLog( shader ).trim(); - function get( scene, renderCallDepth ) { + if ( status && errors === '' ) return ''; - let list; + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { - if ( lists.has( scene ) === false ) { + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - list = new WebGLRenderList( properties ); - lists.set( scene, [ list ] ); + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); - } else { + } else { - if ( renderCallDepth >= lists.get( scene ).length ) { + return errors; - list = new WebGLRenderList( properties ); - lists.get( scene ).push( list ); + } - } else { +} - list = lists.get( scene )[ renderCallDepth ]; +function getTexelEncodingFunction( functionName, encoding ) { - } + const components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; - } +} - return list; +function getToneMappingFunction( functionName, toneMapping ) { - } + let toneMappingName; - function dispose() { + switch ( toneMapping ) { - lists = new WeakMap(); + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; + + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; + + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; + + case CustomToneMapping: + toneMappingName = 'Custom'; + break; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); + toneMappingName = 'Linear'; } - return { - get: get, - dispose: dispose - }; + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; } -function UniformsCache() { +function generateExtensions( parameters ) { - const lights = {}; + const chunks = [ + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', + ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; - return { + return chunks.filter( filterEmptyLine ).join( '\n' ); - get: function ( light ) { +} - if ( lights[ light.id ] !== undefined ) { +function generateDefines( defines ) { - return lights[ light.id ]; + const chunks = []; - } + for ( const name in defines ) { - let uniforms; + const value = defines[ name ]; - switch ( light.type ) { + if ( value === false ) continue; - case 'DirectionalLight': - uniforms = { - direction: new Vector3(), - color: new Color() - }; - break; + chunks.push( '#define ' + name + ' ' + value ); - case 'SpotLight': - uniforms = { - position: new Vector3(), + } + + return chunks.join( '\n' ); + +} + +function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, 35721 ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === 35674 ) locationSize = 2; + if ( info.type === 35675 ) locationSize = 3; + if ( info.type === 35676 ) locationSize = 4; + + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + +} + +function filterEmptyLine( string ) { + + return string !== ''; + +} + +function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + +} + +function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + +} + +// Resolve Includes + +const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + +function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + +} + +function includeReplacer( match, include ) { + + const string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + throw new Error( 'Can not resolve #include <' + include + '>' ); + + } + + return resolveIncludes( string ); + +} + +// Unroll Loops + +const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + +function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + +} + +function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + +} + +// + +function generatePrecision( parameters ) { + + let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + +} + +function generateShadowMapTypeDefine( parameters ) { + + let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + + if ( parameters.shadowMapType === PCFShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + + } else if ( parameters.shadowMapType === VSMShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + + } + + return shadowMapTypeDefine; + +} + +function generateEnvMapTypeDefine( parameters ) { + + let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; + + case CubeUVReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; + + } + + } + + return envMapTypeDefine; + +} + +function generateEnvMapModeDefine( parameters ) { + + let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeRefractionMapping: + + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; + + } + + } + + return envMapModeDefine; + +} + +function generateEnvMapBlendingDefine( parameters ) { + + let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; + + if ( parameters.envMap ) { + + switch ( parameters.combine ) { + + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; + + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; + + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; + + } + + } + + return envMapBlendingDefine; + +} + +function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + +} + +function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // console.log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + customExtensions, + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', + + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', + + ' #ifdef USE_MORPHNORMALS', + + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', + + ' #else', + + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', + + ' #endif', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + customExtensions, + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + + parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( 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.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + 'precision mediump sampler2DArray;', + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.morphTargets === true ) { + + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programLog = gl.getProgramInfoLog( program ).trim(); + const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, 35714 ) === false ) { + + runnable = false; + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + console.error( + 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } else if ( programLog !== '' ) { + + console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + this.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + cachedUniforms = new WebGLUniforms( gl, program ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + return cachedAttributes; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +let _id = 0; + +class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material ) { + + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + + const vertexShaderStage = this._getShaderStage( vertexShader ); + const fragmentShaderStage = this._getShaderStage( fragmentShader ); + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderID( material ) { + + return this._getShaderStage( material.vertexShader ).id; + + } + + getFragmentShaderID( material ) { + + return this._getShaderStage( material.fragmentShader ).id; + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + +} + +class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + +} + +function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const programs = []; + + const isWebGL2 = capabilities.isWebGL2; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const vertexTextures = capabilities.vertexTextures; + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getParameters( material, lights, shadows, scene, object ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + _customShaders.update( material ); + + customVertexShaderID = _customShaders.getVertexShaderID( material ); + customFragmentShaderID = _customShaders.getFragmentShaderID( material ); + + } + + const currentRenderTarget = renderer.getRenderTarget(); + + const useAlphaTest = material.alphaTest > 0; + const useClearcoat = material.clearcoat > 0; + const useIridescence = material.iridescence > 0; + + const parameters = { + + isWebGL2: isWebGL2, + + shaderID: shaderID, + shaderName: material.type, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + instancing: object.isInstancedMesh === true, + instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, + + supportsVertexTextures: vertexTextures, + outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ), + map: !! material.map, + matcap: !! material.matcap, + envMap: !! envMap, + envMapMode: envMap && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, + tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, + + decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ), + + clearcoat: useClearcoat, + clearcoatMap: useClearcoat && !! material.clearcoatMap, + clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap, + clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap, + + iridescence: useIridescence, + iridescenceMap: useIridescence && !! material.iridescenceMap, + iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap, + + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + specularIntensityMap: !! material.specularIntensityMap, + specularColorMap: !! material.specularColorMap, + + opaque: material.transparent === false && material.blending === NormalBlending, + + alphaMap: !! material.alphaMap, + alphaTest: useAlphaTest, + + gradientMap: !! material.gradientMap, + + sheen: material.sheen > 0, + sheenColorMap: !! material.sheenColorMap, + sheenRoughnessMap: !! material.sheenRoughnessMap, + + transmission: material.transmission > 0, + transmissionMap: !! material.transmissionMap, + thicknessMap: !! material.thicknessMap, + + combine: material.combine, + + vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( fog && fog.isFogExp2 ), + + flatShading: !! material.flatShading, + + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: !! material.depthPacking, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionDerivatives: material.extensions && material.extensions.derivatives, + extensionFragDepth: material.extensions && material.extensions.fragDepth, + extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, + extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, + + rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ), + rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ), + rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputEncoding ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputEncoding ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.combine ); + array.push( parameters.vertexUvs ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.isWebGL2 ) + _programLayers.enable( 0 ); + if ( parameters.supportsVertexTextures ) + _programLayers.enable( 1 ); + if ( parameters.instancing ) + _programLayers.enable( 2 ); + if ( parameters.instancingColor ) + _programLayers.enable( 3 ); + if ( parameters.map ) + _programLayers.enable( 4 ); + if ( parameters.matcap ) + _programLayers.enable( 5 ); + if ( parameters.envMap ) + _programLayers.enable( 6 ); + if ( parameters.lightMap ) + _programLayers.enable( 7 ); + if ( parameters.aoMap ) + _programLayers.enable( 8 ); + if ( parameters.emissiveMap ) + _programLayers.enable( 9 ); + if ( parameters.bumpMap ) + _programLayers.enable( 10 ); + if ( parameters.normalMap ) + _programLayers.enable( 11 ); + if ( parameters.objectSpaceNormalMap ) + _programLayers.enable( 12 ); + if ( parameters.tangentSpaceNormalMap ) + _programLayers.enable( 13 ); + if ( parameters.clearcoat ) + _programLayers.enable( 14 ); + if ( parameters.clearcoatMap ) + _programLayers.enable( 15 ); + if ( parameters.clearcoatRoughnessMap ) + _programLayers.enable( 16 ); + if ( parameters.clearcoatNormalMap ) + _programLayers.enable( 17 ); + if ( parameters.iridescence ) + _programLayers.enable( 18 ); + if ( parameters.iridescenceMap ) + _programLayers.enable( 19 ); + if ( parameters.iridescenceThicknessMap ) + _programLayers.enable( 20 ); + if ( parameters.displacementMap ) + _programLayers.enable( 21 ); + if ( parameters.specularMap ) + _programLayers.enable( 22 ); + if ( parameters.roughnessMap ) + _programLayers.enable( 23 ); + if ( parameters.metalnessMap ) + _programLayers.enable( 24 ); + if ( parameters.gradientMap ) + _programLayers.enable( 25 ); + if ( parameters.alphaMap ) + _programLayers.enable( 26 ); + if ( parameters.alphaTest ) + _programLayers.enable( 27 ); + if ( parameters.vertexColors ) + _programLayers.enable( 28 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 29 ); + if ( parameters.vertexUvs ) + _programLayers.enable( 30 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 31 ); + if ( parameters.uvsVertexOnly ) + _programLayers.enable( 32 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.skinning ) + _programLayers.enable( 4 ); + if ( parameters.morphTargets ) + _programLayers.enable( 5 ); + if ( parameters.morphNormals ) + _programLayers.enable( 6 ); + if ( parameters.morphColors ) + _programLayers.enable( 7 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 8 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 9 ); + if ( parameters.physicallyCorrectLights ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.specularIntensityMap ) + _programLayers.enable( 15 ); + if ( parameters.specularColorMap ) + _programLayers.enable( 16 ); + if ( parameters.transmission ) + _programLayers.enable( 17 ); + if ( parameters.transmissionMap ) + _programLayers.enable( 18 ); + if ( parameters.thicknessMap ) + _programLayers.enable( 19 ); + if ( parameters.sheen ) + _programLayers.enable( 20 ); + if ( parameters.sheenColorMap ) + _programLayers.enable( 21 ); + if ( parameters.sheenRoughnessMap ) + _programLayers.enable( 22 ); + if ( parameters.decodeVideoTexture ) + _programLayers.enable( 23 ); + if ( parameters.opaque ) + _programLayers.enable( 24 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program; + + // Check if code has been already compiled + for ( let p = 0, pl = programs.length; p < pl; p ++ ) { + + const preexistingProgram = programs[ p ]; + + if ( preexistingProgram.cacheKey === cacheKey ) { + + program = preexistingProgram; + ++ program.usedTimes; + + break; + + } + + } + + if ( program === undefined ) { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + +} + +function WebGLProperties() { + + let properties = new WeakMap(); + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; + +} + +function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + +} + +function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + +} + + +function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + +} + +function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), direction: new Vector3(), color: new Color(), distance: 0, @@ -17976,9 +19949,9 @@ function ShadowUniformsCache() { let nextVersion = 0; -function shadowCastingLightsFirst( lightA, lightB ) { +function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { - return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 ); + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); } @@ -18001,7 +19974,8 @@ function WebGLLights( extensions, capabilities ) { numDirectionalShadows: - 1, numPointShadows: - 1, - numSpotShadows: - 1 + numSpotShadows: - 1, + numSpotMaps: - 1 }, ambient: [ 0, 0, 0 ], @@ -18011,9 +19985,10 @@ function WebGLLights( extensions, capabilities ) { directionalShadowMap: [], directionalShadowMatrix: [], spot: [], + spotLightMap: [], spotShadow: [], spotShadowMap: [], - spotShadowMatrix: [], + spotLightMatrix: [], rectArea: [], rectAreaLTC1: null, rectAreaLTC2: null, @@ -18021,7 +19996,8 @@ function WebGLLights( extensions, capabilities ) { pointShadow: [], pointShadowMap: [], pointShadowMatrix: [], - hemi: [] + hemi: [], + numSpotLightShadowsWithMaps: 0 }; @@ -18031,7 +20007,7 @@ function WebGLLights( extensions, capabilities ) { const matrix4 = new Matrix4(); const matrix42 = new Matrix4(); - function setup( lights ) { + function setup( lights, physicallyCorrectLights ) { let r = 0, g = 0, b = 0; @@ -18046,8 +20022,14 @@ function WebGLLights( extensions, capabilities ) { let numDirectionalShadows = 0; let numPointShadows = 0; let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; - lights.sort( shadowCastingLightsFirst ); + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + // artist-friendly light intensity scaling factor + const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1; for ( let i = 0, l = lights.length; i < l; i ++ ) { @@ -18061,9 +20043,9 @@ function WebGLLights( extensions, capabilities ) { if ( light.isAmbientLight ) { - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + r += color.r * intensity * scaleFactor; + g += color.g * intensity * scaleFactor; + b += color.b * intensity * scaleFactor; } else if ( light.isLightProbe ) { @@ -18077,7 +20059,7 @@ function WebGLLights( extensions, capabilities ) { const uniforms = cache.get( light ); - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); if ( light.castShadow ) { @@ -18108,16 +20090,33 @@ function WebGLLights( extensions, capabilities ) { uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor ); uniforms.distance = distance; uniforms.coneCos = Math.cos( light.angle ); uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); uniforms.decay = light.decay; - if ( light.castShadow ) { + state.spot[ spotLength ] = uniforms; - const shadow = light.shadow; + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { const shadowUniforms = shadowCache.get( light ); @@ -18128,14 +20127,11 @@ function WebGLLights( extensions, capabilities ) { state.spotShadow[ spotLength ] = shadowUniforms; state.spotShadowMap[ spotLength ] = shadowMap; - state.spotShadowMatrix[ spotLength ] = light.shadow.matrix; numSpotShadows ++; } - state.spot[ spotLength ] = uniforms; - spotLength ++; } else if ( light.isRectAreaLight ) { @@ -18159,7 +20155,7 @@ function WebGLLights( extensions, capabilities ) { const uniforms = cache.get( light ); - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); uniforms.distance = light.distance; uniforms.decay = light.decay; @@ -18192,8 +20188,8 @@ function WebGLLights( extensions, capabilities ) { const uniforms = cache.get( light ); - uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); - uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor ); state.hemi[ hemiLength ] = uniforms; @@ -18249,7 +20245,8 @@ function WebGLLights( extensions, capabilities ) { hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || - hash.numSpotShadows !== numSpotShadows ) { + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps ) { state.directional.length = directionalLength; state.spot.length = spotLength; @@ -18265,7 +20262,9 @@ function WebGLLights( extensions, capabilities ) { state.spotShadowMap.length = numSpotShadows; state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadowMatrix.length = numPointShadows; - state.spotShadowMatrix.length = numSpotShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; hash.directionalLength = directionalLength; hash.pointLength = pointLength; @@ -18276,6 +20275,7 @@ function WebGLLights( extensions, capabilities ) { hash.numDirectionalShadows = numDirectionalShadows; hash.numPointShadows = numPointShadows; hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; state.version = nextVersion ++; @@ -18358,7 +20358,6 @@ function WebGLLights( extensions, capabilities ) { uniforms.direction.setFromMatrixPosition( light.matrixWorld ); uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); hemiLength ++; @@ -18402,9 +20401,9 @@ function WebGLRenderState( extensions, capabilities ) { } - function setupLights() { + function setupLights( physicallyCorrectLights ) { - lights.setup( lightsArray ); + lights.setup( lightsArray, physicallyCorrectLights ); } @@ -18439,23 +20438,24 @@ function WebGLRenderStates( extensions, capabilities ) { function get( scene, renderCallDepth = 0 ) { + const renderStateArray = renderStates.get( scene ); let renderState; - if ( renderStates.has( scene ) === false ) { + if ( renderStateArray === undefined ) { renderState = new WebGLRenderState( extensions, capabilities ); renderStates.set( scene, [ renderState ] ); } else { - if ( renderCallDepth >= renderStates.get( scene ).length ) { + if ( renderCallDepth >= renderStateArray.length ) { renderState = new WebGLRenderState( extensions, capabilities ); - renderStates.get( scene ).push( renderState ); + renderStateArray.push( renderState ); } else { - renderState = renderStates.get( scene )[ renderCallDepth ]; + renderState = renderStateArray[ renderCallDepth ]; } @@ -18478,37 +20478,18 @@ function WebGLRenderStates( extensions, capabilities ) { } -/** - * parameters = { - * - * opacity: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ - class MeshDepthMaterial extends Material { constructor( parameters ) { super(); + this.isMeshDepthMaterial = true; + this.type = 'MeshDepthMaterial'; this.depthPacking = BasicDepthPacking; - this.skinning = false; - this.morphTargets = false; - this.map = null; this.alphaMap = null; @@ -18520,8 +20501,6 @@ class MeshDepthMaterial extends Material { this.wireframe = false; this.wireframeLinewidth = 1; - this.fog = false; - this.setValues( parameters ); } @@ -18532,9 +20511,6 @@ class MeshDepthMaterial extends Material { this.depthPacking = source.depthPacking; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.map = source.map; this.alphaMap = source.alphaMap; @@ -18552,44 +20528,20 @@ class MeshDepthMaterial extends Material { } -MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - -/** - * parameters = { - * - * referencePosition: , - * nearDistance: , - * farDistance: , - * - * skinning: , - * morphTargets: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: - * - * } - */ - class MeshDistanceMaterial extends Material { constructor( parameters ) { super(); + this.isMeshDistanceMaterial = true; + this.type = 'MeshDistanceMaterial'; this.referencePosition = new Vector3(); this.nearDistance = 1; this.farDistance = 1000; - this.skinning = false; - this.morphTargets = false; - this.map = null; this.alphaMap = null; @@ -18598,8 +20550,6 @@ class MeshDistanceMaterial extends Material { this.displacementScale = 1; this.displacementBias = 0; - this.fog = false; - this.setValues( parameters ); } @@ -18612,9 +20562,6 @@ class MeshDistanceMaterial extends Material { this.nearDistance = source.nearDistance; this.farDistance = source.farDistance; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.map = source.map; this.alphaMap = source.alphaMap; @@ -18629,13 +20576,11 @@ class MeshDistanceMaterial extends Material { } -MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; +const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; -var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; +const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; -var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; - -function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { +function WebGLShadowMap( _renderer, _objects, _capabilities ) { let _frustum = new Frustum(); @@ -18644,29 +20589,27 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { _viewport = new Vector4(), - _depthMaterials = [], - _distanceMaterials = [], + _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, - _materialCache = {}; + _maxTextureSize = _capabilities.maxTextureSize; const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide }; const shadowMaterialVertical = new ShaderMaterial( { - defines: { - SAMPLE_RATE: 2.0 / 8.0, - HALF_SAMPLE_RATE: 1.0 / 8.0 + VSM_SAMPLES: 8 }, - uniforms: { shadow_pass: { value: null }, resolution: { value: new Vector2() }, radius: { value: 4.0 } }, - vertexShader: vsm_vert, - - fragmentShader: vsm_frag + vertexShader: vertex, + fragmentShader: fragment } ); @@ -18736,19 +20679,19 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { _viewportSize.copy( shadow.mapSize ); - if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) { + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { - if ( _shadowMapSize.x > maxTextureSize ) { + if ( _shadowMapSize.x > _maxTextureSize ) { - _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x ); + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; shadow.mapSize.x = _viewportSize.x; } - if ( _shadowMapSize.y > maxTextureSize ) { + if ( _shadowMapSize.y > _maxTextureSize ) { - _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y ); + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; shadow.mapSize.y = _viewportSize.y; @@ -18756,22 +20699,9 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } - if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { - - const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; - - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - shadow.map.texture.name = light.name + '.shadowMap'; - - shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - - shadow.camera.updateProjectionMatrix(); - - } - if ( shadow.map === null ) { - const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadow.map.texture.name = light.name + '.shadowMap'; @@ -18808,7 +20738,7 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { // do blur pass for VSM - if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { VSMPass( shadow, camera ); @@ -18828,6 +20758,22 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { const geometry = _objects.update( fullScreenMesh ); + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + // vertical pass shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; @@ -18848,107 +20794,25 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } - function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) { - - const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; - - let material = _depthMaterials[ index ]; - - if ( material === undefined ) { - - material = new MeshDepthMaterial( { - - depthPacking: RGBADepthPacking, - - morphTargets: useMorphing, - skinning: useSkinning - - } ); - - _depthMaterials[ index ] = material; - - } - - return material; - - } - - function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) { - - const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; - - let material = _distanceMaterials[ index ]; - - if ( material === undefined ) { - - material = new MeshDistanceMaterial( { - - morphTargets: useMorphing, - skinning: useSkinning - - } ); - - _distanceMaterials[ index ] = material; - - } - - return material; - - } - - function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) { + function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) { let result = null; - let getMaterialVariant = getDepthMaterialVariant; - let customMaterial = object.customDepthMaterial; - - if ( light.isPointLight === true ) { - - getMaterialVariant = getDistanceMaterialVariant; - customMaterial = object.customDistanceMaterial; - - } - - if ( customMaterial === undefined ) { - - let useMorphing = false; - - if ( material.morphTargets === true ) { - - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - - } - - let useSkinning = false; + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; - if ( object.isSkinnedMesh === true ) { + if ( customMaterial !== undefined ) { - if ( material.skinning === true ) { - - useSkinning = true; - - } else { - - console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object ); - - } - - } - - const useInstancing = object.isInstancedMesh === true; - - result = getMaterialVariant( useMorphing, useSkinning, useInstancing ); + result = customMaterial; } else { - result = customMaterial; + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; } - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) ) { // in this case we need a unique material instance reflecting the // appropriate state @@ -18990,10 +20854,17 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.clipShadows = material.clipShadows; result.clippingPlanes = material.clippingPlanes; result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; result.linewidth = material.linewidth; @@ -19035,7 +20906,7 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { if ( groupMaterial && groupMaterial.visible ) { - const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); + const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); @@ -19045,7 +20916,7 @@ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { } else if ( material.visible ) { - const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type ); + const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type ); _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); @@ -19380,8 +21251,15 @@ function WebGLState( gl, extensions, capabilities ) { const depthBuffer = new DepthBuffer(); const stencilBuffer = new StencilBuffer(); + const uboBindings = new WeakMap(); + const uboProgamMap = new WeakMap(); + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + let currentProgram = null; let currentBlendingEnabled = false; @@ -19423,8 +21301,11 @@ function WebGLState( gl, extensions, capabilities ) { let currentTextureSlot = null; let currentBoundTextures = {}; - const currentScissor = new Vector4(); - const currentViewport = new Vector4(); + const scissorParam = gl.getParameter( 3088 ); + const viewportParam = gl.getParameter( 2978 ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); function createTexture( type, target, count ) { @@ -19462,30 +21343,140 @@ function WebGLState( gl, extensions, capabilities ) { setCullFace( CullFaceBack ); enable( 2884 ); - setBlending( NoBlending ); + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + if ( isWebGL2 ) { + + // 36009 is equivalent to 36160 + + if ( target === 36009 ) { + + currentBoundFramebuffers[ 36160 ] = framebuffer; + + } + + if ( target === 36160 ) { + + currentBoundFramebuffers[ 36009 ] = framebuffer; + + } + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = 36064 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== 36064 ) { + + drawBuffers[ 0 ] = 36064; + + needsUpdate = true; + + } + + } - // + } else { - function enable( id ) { + if ( drawBuffers[ 0 ] !== 1029 ) { - if ( enabledCapabilities[ id ] !== true ) { + drawBuffers[ 0 ] = 1029; - gl.enable( id ); - enabledCapabilities[ id ] = true; + needsUpdate = true; + + } } - } + if ( needsUpdate ) { - function disable( id ) { + if ( capabilities.isWebGL2 ) { - if ( enabledCapabilities[ id ] !== false ) { + gl.drawBuffers( drawBuffers ); - gl.disable( id ); - enabledCapabilities[ id ] = false; + } else { + + extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + + } } + } function useProgram( program ) { @@ -19590,7 +21581,7 @@ function WebGLState( gl, extensions, capabilities ) { break; case SubtractiveBlending: - gl.blendFuncSeparate( 0, 0, 769, 771 ); + gl.blendFuncSeparate( 0, 769, 0, 1 ); break; case MultiplyBlending: @@ -19616,7 +21607,7 @@ function WebGLState( gl, extensions, capabilities ) { break; case SubtractiveBlending: - gl.blendFunc( 0, 769 ); + gl.blendFuncSeparate( 0, 769, 0, 1 ); break; case MultiplyBlending: @@ -19708,6 +21699,10 @@ function WebGLState( gl, extensions, capabilities ) { setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + material.alphaToCoverage === true + ? enable( 32926 ) + : disable( 32926 ); + } // @@ -19720,12110 +21715,11127 @@ function WebGLState( gl, extensions, capabilities ) { gl.frontFace( 2304 ); - } else { - - gl.frontFace( 2305 ); - - } - - currentFlipSided = flipSided; - - } - - } - - function setCullFace( cullFace ) { - - if ( cullFace !== CullFaceNone ) { - - enable( 2884 ); - - if ( cullFace !== currentCullFace ) { - - if ( cullFace === CullFaceBack ) { - - gl.cullFace( 1029 ); - - } else if ( cullFace === CullFaceFront ) { - - gl.cullFace( 1028 ); - - } else { - - gl.cullFace( 1032 ); - - } - - } - - } else { - - disable( 2884 ); - - } - - currentCullFace = cullFace; - - } - - function setLineWidth( width ) { - - if ( width !== currentLineWidth ) { - - if ( lineWidthAvailable ) gl.lineWidth( width ); - - currentLineWidth = width; - - } - - } - - function setPolygonOffset( polygonOffset, factor, units ) { - - if ( polygonOffset ) { - - enable( 32823 ); - - if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - - gl.polygonOffset( factor, units ); - - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; - - } - - } else { - - disable( 32823 ); - - } - - } - - function setScissorTest( scissorTest ) { - - if ( scissorTest ) { - - enable( 3089 ); - - } else { - - disable( 3089 ); - - } - - } - - // texture - - function activeTexture( webglSlot ) { - - if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1; - - if ( currentTextureSlot !== webglSlot ) { - - gl.activeTexture( webglSlot ); - currentTextureSlot = webglSlot; - - } - - } - - function bindTexture( webglType, webglTexture ) { - - if ( currentTextureSlot === null ) { - - activeTexture(); - - } - - let boundTexture = currentBoundTextures[ currentTextureSlot ]; - - if ( boundTexture === undefined ) { - - boundTexture = { type: undefined, texture: undefined }; - currentBoundTextures[ currentTextureSlot ] = boundTexture; - - } - - if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - - gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - - boundTexture.type = webglType; - boundTexture.texture = webglTexture; - - } - - } - - function unbindTexture() { - - const boundTexture = currentBoundTextures[ currentTextureSlot ]; - - if ( boundTexture !== undefined && boundTexture.type !== undefined ) { - - gl.bindTexture( boundTexture.type, null ); - - boundTexture.type = undefined; - boundTexture.texture = undefined; - - } - - } - - function compressedTexImage2D() { - - try { - - gl.compressedTexImage2D.apply( gl, arguments ); - - } catch ( error ) { - - console.error( 'THREE.WebGLState:', error ); - - } - - } - - function texImage2D() { - - try { - - gl.texImage2D.apply( gl, arguments ); - - } catch ( error ) { - - console.error( 'THREE.WebGLState:', error ); - - } - - } - - function texImage3D() { - - try { - - gl.texImage3D.apply( gl, arguments ); - - } catch ( error ) { - - console.error( 'THREE.WebGLState:', error ); - - } - - } - - // - - function scissor( scissor ) { - - if ( currentScissor.equals( scissor ) === false ) { - - gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); - currentScissor.copy( scissor ); - - } - - } - - function viewport( viewport ) { - - if ( currentViewport.equals( viewport ) === false ) { - - gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); - currentViewport.copy( viewport ); - - } - - } - - // - - function reset() { - - // reset state - - gl.disable( 3042 ); - gl.disable( 2884 ); - gl.disable( 2929 ); - gl.disable( 32823 ); - gl.disable( 3089 ); - gl.disable( 2960 ); - - gl.blendEquation( 32774 ); - gl.blendFunc( 1, 0 ); - gl.blendFuncSeparate( 1, 0, 1, 0 ); - - gl.colorMask( true, true, true, true ); - gl.clearColor( 0, 0, 0, 0 ); - - gl.depthMask( true ); - gl.depthFunc( 513 ); - gl.clearDepth( 1 ); - - gl.stencilMask( 0xffffffff ); - gl.stencilFunc( 519, 0, 0xffffffff ); - gl.stencilOp( 7680, 7680, 7680 ); - gl.clearStencil( 0 ); - - gl.cullFace( 1029 ); - gl.frontFace( 2305 ); - - gl.polygonOffset( 0, 0 ); - - gl.activeTexture( 33984 ); - - gl.useProgram( null ); - - gl.lineWidth( 1 ); - - gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); - gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); - - // reset internals - - enabledCapabilities = {}; - - currentTextureSlot = null; - currentBoundTextures = {}; - - currentProgram = null; - - currentBlendingEnabled = false; - currentBlending = null; - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; - currentPremultipledAlpha = false; - - currentFlipSided = null; - currentCullFace = null; - - currentLineWidth = null; - - currentPolygonOffsetFactor = null; - currentPolygonOffsetUnits = null; - - colorBuffer.reset(); - depthBuffer.reset(); - stencilBuffer.reset(); - - } - - return { - - buffers: { - color: colorBuffer, - depth: depthBuffer, - stencil: stencilBuffer - }, - - enable: enable, - disable: disable, - - useProgram: useProgram, - - setBlending: setBlending, - setMaterial: setMaterial, - - setFlipSided: setFlipSided, - setCullFace: setCullFace, - - setLineWidth: setLineWidth, - setPolygonOffset: setPolygonOffset, - - setScissorTest: setScissorTest, - - activeTexture: activeTexture, - bindTexture: bindTexture, - unbindTexture: unbindTexture, - compressedTexImage2D: compressedTexImage2D, - texImage2D: texImage2D, - texImage3D: texImage3D, - - scissor: scissor, - viewport: viewport, - - reset: reset - - }; - -} - -function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { - - const isWebGL2 = capabilities.isWebGL2; - const maxTextures = capabilities.maxTextures; - const maxCubemapSize = capabilities.maxCubemapSize; - const maxTextureSize = capabilities.maxTextureSize; - const maxSamples = capabilities.maxSamples; - - const _videoTextures = new WeakMap(); - let _canvas; - - // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, - // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! - // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). - - let useOffscreenCanvas = false; - - try { - - useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' - && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; - - } catch ( err ) { - - // Ignore any errors - - } - - function createCanvas( width, height ) { - - // Use OffscreenCanvas when available. Specially needed in web workers - - return useOffscreenCanvas ? - new OffscreenCanvas( width, height ) : - document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - - } - - function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { - - let scale = 1; - - // handle case if texture exceeds max size - - if ( image.width > maxSize || image.height > maxSize ) { - - scale = maxSize / Math.max( image.width, image.height ); - - } - - // only perform resize if necessary - - if ( scale < 1 || needsPowerOfTwo === true ) { - - // only perform resize for certain image types - - if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || - ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - - const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor; - - const width = floor( scale * image.width ); - const height = floor( scale * image.height ); - - if ( _canvas === undefined ) _canvas = createCanvas( width, height ); - - // cube textures can't reuse the same canvas - - const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; - - canvas.width = width; - canvas.height = height; - - const context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, width, height ); - - console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); - - return canvas; - - } else { - - if ( 'data' in image ) { - - console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); - - } - - return image; - - } - - } - - return image; - - } - - function isPowerOfTwo( image ) { - - return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height ); - - } - - function textureNeedsPowerOfTwo( texture ) { - - if ( isWebGL2 ) return false; - - return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || - ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); - - } - - function textureNeedsGenerateMipmaps( texture, supportsMips ) { - - return texture.generateMipmaps && supportsMips && - texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - - } - - function generateMipmap( target, texture, width, height ) { - - _gl.generateMipmap( target ); - - const textureProperties = properties.get( texture ); - - textureProperties.__maxMipLevel = Math.log2( Math.max( width, height ) ); - - } - - function getInternalFormat( internalFormatName, glFormat, glType ) { - - if ( isWebGL2 === false ) return glFormat; - - if ( internalFormatName !== null ) { - - if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; - - console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); - - } - - let internalFormat = glFormat; - - if ( glFormat === 6403 ) { - - if ( glType === 5126 ) internalFormat = 33326; - if ( glType === 5131 ) internalFormat = 33325; - if ( glType === 5121 ) internalFormat = 33321; - - } - - if ( glFormat === 6407 ) { - - if ( glType === 5126 ) internalFormat = 34837; - if ( glType === 5131 ) internalFormat = 34843; - if ( glType === 5121 ) internalFormat = 32849; - - } - - if ( glFormat === 6408 ) { - - if ( glType === 5126 ) internalFormat = 34836; - if ( glType === 5131 ) internalFormat = 34842; - if ( glType === 5121 ) internalFormat = 32856; + } else { - } + gl.frontFace( 2305 ); - if ( internalFormat === 33325 || internalFormat === 33326 || - internalFormat === 34842 || internalFormat === 34836 ) { + } - extensions.get( 'EXT_color_buffer_float' ); + currentFlipSided = flipSided; } - return internalFormat; - } - // Fallback filters for non-power-of-2 textures + function setCullFace( cullFace ) { - function filterFallback( f ) { + if ( cullFace !== CullFaceNone ) { - if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { + enable( 2884 ); - return 9728; + if ( cullFace !== currentCullFace ) { - } + if ( cullFace === CullFaceBack ) { - return 9729; + gl.cullFace( 1029 ); - } + } else if ( cullFace === CullFaceFront ) { - // + gl.cullFace( 1028 ); - function onTextureDispose( event ) { + } else { - const texture = event.target; + gl.cullFace( 1032 ); - texture.removeEventListener( 'dispose', onTextureDispose ); + } - deallocateTexture( texture ); + } - if ( texture.isVideoTexture ) { + } else { - _videoTextures.delete( texture ); + disable( 2884 ); } - info.memory.textures --; + currentCullFace = cullFace; } - function onRenderTargetDispose( event ) { + function setLineWidth( width ) { - const renderTarget = event.target; + if ( width !== currentLineWidth ) { - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + if ( lineWidthAvailable ) gl.lineWidth( width ); - deallocateRenderTarget( renderTarget ); + currentLineWidth = width; - info.memory.textures --; + } } - // + function setPolygonOffset( polygonOffset, factor, units ) { - function deallocateTexture( texture ) { + if ( polygonOffset ) { - const textureProperties = properties.get( texture ); + enable( 32823 ); - if ( textureProperties.__webglInit === undefined ) return; + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - _gl.deleteTexture( textureProperties.__webglTexture ); + gl.polygonOffset( factor, units ); - properties.remove( texture ); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - } + } - function deallocateRenderTarget( renderTarget ) { + } else { - const texture = renderTarget.texture; + disable( 32823 ); - const renderTargetProperties = properties.get( renderTarget ); - const textureProperties = properties.get( texture ); + } - if ( ! renderTarget ) return; + } - if ( textureProperties.__webglTexture !== undefined ) { + function setScissorTest( scissorTest ) { - _gl.deleteTexture( textureProperties.__webglTexture ); + if ( scissorTest ) { - } + enable( 3089 ); - if ( renderTarget.depthTexture ) { + } else { - renderTarget.depthTexture.dispose(); + disable( 3089 ); } - if ( renderTarget.isWebGLCubeRenderTarget ) { + } - for ( let i = 0; i < 6; i ++ ) { + // texture - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + function activeTexture( webglSlot ) { - } + if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1; - } else { + if ( currentTextureSlot !== webglSlot ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); - if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); - if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); - if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; } - properties.remove( texture ); - properties.remove( renderTarget ); - } - // + function bindTexture( webglType, webglTexture ) { - let textureUnits = 0; + if ( currentTextureSlot === null ) { - function resetTextureUnits() { + activeTexture(); - textureUnits = 0; + } - } + let boundTexture = currentBoundTextures[ currentTextureSlot ]; - function allocateTextureUnit() { + if ( boundTexture === undefined ) { - const textureUnit = textureUnits; + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; - if ( textureUnit >= maxTextures ) { + } - console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - } + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - textureUnits += 1; + boundTexture.type = webglType; + boundTexture.texture = webglTexture; - return textureUnit; + } } - // - - function setTexture2D( texture, slot ) { + function unbindTexture() { - const textureProperties = properties.get( texture ); + const boundTexture = currentBoundTextures[ currentTextureSlot ]; - if ( texture.isVideoTexture ) updateVideoTexture( texture ); + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.bindTexture( boundTexture.type, null ); - const image = texture.image; + boundTexture.type = undefined; + boundTexture.texture = undefined; - if ( image === undefined ) { + } - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' ); + } - } else if ( image.complete === false ) { + function compressedTexImage2D() { - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + try { - } else { + gl.compressedTexImage2D.apply( gl, arguments ); - uploadTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); } - state.activeTexture( 33984 + slot ); - state.bindTexture( 3553, textureProperties.__webglTexture ); - } - function setTexture2DArray( texture, slot ) { + function texSubImage2D() { - const textureProperties = properties.get( texture ); + try { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.texSubImage2D.apply( gl, arguments ); - uploadTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - state.activeTexture( 33984 + slot ); - state.bindTexture( 35866, textureProperties.__webglTexture ); + } } - function setTexture3D( texture, slot ) { + function texSubImage3D() { - const textureProperties = properties.get( texture ); + try { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.texSubImage3D.apply( gl, arguments ); - uploadTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - state.activeTexture( 33984 + slot ); - state.bindTexture( 32879, textureProperties.__webglTexture ); + } } - function setTextureCube( texture, slot ) { + function compressedTexSubImage2D() { - const textureProperties = properties.get( texture ); + try { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + gl.compressedTexSubImage2D.apply( gl, arguments ); - uploadCubeTexture( textureProperties, texture, slot ); - return; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - state.activeTexture( 33984 + slot ); - state.bindTexture( 34067, textureProperties.__webglTexture ); + } } - const wrappingToGL = { - [ RepeatWrapping ]: 10497, - [ ClampToEdgeWrapping ]: 33071, - [ MirroredRepeatWrapping ]: 33648 - }; - - const filterToGL = { - [ NearestFilter ]: 9728, - [ NearestMipmapNearestFilter ]: 9984, - [ NearestMipmapLinearFilter ]: 9986, - - [ LinearFilter ]: 9729, - [ LinearMipmapNearestFilter ]: 9985, - [ LinearMipmapLinearFilter ]: 9987 - }; - - function setTextureParameters( textureType, texture, supportsMips ) { + function texStorage2D() { - if ( supportsMips ) { + try { - _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); - _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); + gl.texStorage2D.apply( gl, arguments ); - if ( textureType === 32879 || textureType === 35866 ) { + } catch ( error ) { - _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); + console.error( 'THREE.WebGLState:', error ); - } + } - _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); - _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); + } - } else { + function texStorage3D() { - _gl.texParameteri( textureType, 10242, 33071 ); - _gl.texParameteri( textureType, 10243, 33071 ); + try { - if ( textureType === 32879 || textureType === 35866 ) { + gl.texStorage3D.apply( gl, arguments ); - _gl.texParameteri( textureType, 32882, 33071 ); + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); - 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.' ); + } - } + function texImage2D() { - _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); + try { - if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { + gl.texImage2D.apply( gl, arguments ); - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' ); + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); } - if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + } - const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + function texImage3D() { - if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 - if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only + try { - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + gl.texImage3D.apply( gl, arguments ); - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + } catch ( error ) { - } + console.error( 'THREE.WebGLState:', error ); } } - function initTexture( textureProperties, texture ) { - - if ( textureProperties.__webglInit === undefined ) { - - textureProperties.__webglInit = true; + // - texture.addEventListener( 'dispose', onTextureDispose ); + function scissor( scissor ) { - textureProperties.__webglTexture = _gl.createTexture(); + if ( currentScissor.equals( scissor ) === false ) { - info.memory.textures ++; + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); } } - function uploadTexture( textureProperties, texture, slot ) { - - let textureType = 3553; + function viewport( viewport ) { - if ( texture.isDataTexture2DArray ) textureType = 35866; - if ( texture.isDataTexture3D ) textureType = 32879; + if ( currentViewport.equals( viewport ) === false ) { - initTexture( textureProperties, texture ); + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); - state.activeTexture( 33984 + slot ); - state.bindTexture( textureType, textureProperties.__webglTexture ); + } - _gl.pixelStorei( 37440, texture.flipY ); - _gl.pixelStorei( 37441, texture.premultiplyAlpha ); - _gl.pixelStorei( 3317, texture.unpackAlignment ); - _gl.pixelStorei( 37443, 0 ); + } - const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false; - const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + function updateUBOMapping( uniformsGroup, program ) { - const supportsMips = isPowerOfTwo( image ) || isWebGL2, - glFormat = utils.convert( texture.format ); + let mapping = uboProgamMap.get( program ); - let glType = utils.convert( texture.type ), - glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + if ( mapping === undefined ) { - setTextureParameters( textureType, texture, supportsMips ); + mapping = new WeakMap(); - let mipmap; - const mipmaps = texture.mipmaps; + uboProgamMap.set( program, mapping ); - if ( texture.isDepthTexture ) { + } - // populate depth texture with dummy data + let blockIndex = mapping.get( uniformsGroup ); - glInternalFormat = 6402; + if ( blockIndex === undefined ) { - if ( isWebGL2 ) { + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); - if ( texture.type === FloatType ) { + mapping.set( uniformsGroup, blockIndex ); - glInternalFormat = 36012; + } - } else if ( texture.type === UnsignedIntType ) { + } - glInternalFormat = 33190; + function uniformBlockBinding( uniformsGroup, program ) { - } else if ( texture.type === UnsignedInt248Type ) { + const mapping = uboProgamMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); - glInternalFormat = 35056; + if ( uboBindings.get( uniformsGroup ) !== blockIndex ) { - } else { + // bind shader specific block index to global block point - glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); - } + uboBindings.set( uniformsGroup, blockIndex ); - } else { + } - if ( texture.type === FloatType ) { + } - console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); + // - } + function reset() { - } + // reset state - // validation checks for WebGL 1 + gl.disable( 3042 ); + gl.disable( 2884 ); + gl.disable( 2929 ); + gl.disable( 32823 ); + gl.disable( 3089 ); + gl.disable( 2960 ); + gl.disable( 32926 ); - if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { + gl.blendEquation( 32774 ); + gl.blendFunc( 1, 0 ); + gl.blendFuncSeparate( 1, 0, 1, 0 ); - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); - console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + gl.depthMask( true ); + gl.depthFunc( 513 ); + gl.clearDepth( 1 ); - texture.type = UnsignedShortType; - glType = utils.convert( texture.type ); + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( 519, 0, 0xffffffff ); + gl.stencilOp( 7680, 7680, 7680 ); + gl.clearStencil( 0 ); - } + gl.cullFace( 1029 ); + gl.frontFace( 2305 ); - } + gl.polygonOffset( 0, 0 ); - if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) { + gl.activeTexture( 33984 ); - // Depth stencil textures need the DEPTH_STENCIL internal format - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - glInternalFormat = 34041; + gl.bindFramebuffer( 36160, null ); - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedInt248Type ) { + if ( isWebGL2 === true ) { - console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + gl.bindFramebuffer( 36009, null ); + gl.bindFramebuffer( 36008, null ); - texture.type = UnsignedInt248Type; - glType = utils.convert( texture.type ); + } - } + gl.useProgram( null ); - } + gl.lineWidth( 1 ); - // + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + // reset internals - } else if ( texture.isDataTexture ) { + enabledCapabilities = {}; - // 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 + currentTextureSlot = null; + currentBoundTextures = {}; - if ( mipmaps.length > 0 && supportsMips ) { + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; - for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + currentProgram = null; - mipmap = mipmaps[ i ]; - state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentPremultipledAlpha = false; - } + currentFlipSided = null; + currentCullFace = null; - texture.generateMipmaps = false; - textureProperties.__maxMipLevel = mipmaps.length - 1; + currentLineWidth = null; - } else { + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); - } + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); - } else if ( texture.isCompressedTexture ) { + } - for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + return { - mipmap = mipmaps[ i ]; + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + enable: enable, + disable: disable, - if ( glFormat !== null ) { + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, - state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + useProgram: useProgram, - } else { + setBlending: setBlending, + setMaterial: setMaterial, - console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + setFlipSided: setFlipSided, + setCullFace: setCullFace, - } + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, - } else { + setScissorTest: setScissorTest, - state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + texImage2D: texImage2D, + texImage3D: texImage3D, - } + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, - } + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, - textureProperties.__maxMipLevel = mipmaps.length - 1; + scissor: scissor, + viewport: viewport, - } else if ( texture.isDataTexture2DArray ) { + reset: reset - state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; + }; - } else if ( texture.isDataTexture3D ) { +} - state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { - } else { + const isWebGL2 = capabilities.isWebGL2; + const maxTextures = capabilities.maxTextures; + const maxCubemapSize = capabilities.maxCubemapSize; + const maxTextureSize = capabilities.maxTextureSize; + const maxSamples = capabilities.maxSamples; + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = /OculusBrowser/g.test( navigator.userAgent ); - // regular Texture (image, video, canvas) + const _videoTextures = new WeakMap(); + let _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 + const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source - if ( mipmaps.length > 0 && supportsMips ) { + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). - for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + let useOffscreenCanvas = false; - mipmap = mipmaps[ i ]; - state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); + try { - } + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + // eslint-disable-next-line compat/compat + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; - texture.generateMipmaps = false; - textureProperties.__maxMipLevel = mipmaps.length - 1; + } catch ( err ) { - } else { + // Ignore any errors - state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); - textureProperties.__maxMipLevel = 0; + } - } + function createCanvas( width, height ) { - } + // Use OffscreenCanvas when available. Specially needed in web workers - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + return useOffscreenCanvas ? + // eslint-disable-next-line compat/compat + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); - generateMipmap( textureType, texture, image.width, image.height ); + } - } + function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { - textureProperties.__version = texture.version; + let scale = 1; - if ( texture.onUpdate ) texture.onUpdate( texture ); + // handle case if texture exceeds max size - } + if ( image.width > maxSize || image.height > maxSize ) { - function uploadCubeTexture( textureProperties, texture, slot ) { + scale = maxSize / Math.max( image.width, image.height ); - if ( texture.image.length !== 6 ) return; + } - initTexture( textureProperties, texture ); + // only perform resize if necessary - state.activeTexture( 33984 + slot ); - state.bindTexture( 34067, textureProperties.__webglTexture ); + if ( scale < 1 || needsPowerOfTwo === true ) { - _gl.pixelStorei( 37440, texture.flipY ); - _gl.pixelStorei( 37441, texture.premultiplyAlpha ); - _gl.pixelStorei( 3317, texture.unpackAlignment ); - _gl.pixelStorei( 37443, 0 ); + // only perform resize for certain image types - const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) ); - const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - const cubeImage = []; + const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; - for ( let i = 0; i < 6; i ++ ) { + const width = floor( scale * image.width ); + const height = floor( scale * image.height ); - if ( ! isCompressed && ! isDataTexture ) { + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); - cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); + // cube textures can't reuse the same canvas - } else { + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + canvas.width = width; + canvas.height = height; - } + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); - } + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); - const image = cubeImage[ 0 ], - supportsMips = isPowerOfTwo( image ) || isWebGL2, - glFormat = utils.convert( texture.format ), - glType = utils.convert( texture.type ), - glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + return canvas; - setTextureParameters( 34067, texture, supportsMips ); + } else { - let mipmaps; + if ( 'data' in image ) { - if ( isCompressed ) { + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); - for ( let i = 0; i < 6; i ++ ) { + } - mipmaps = cubeImage[ i ].mipmaps; + return image; - for ( let j = 0; j < mipmaps.length; j ++ ) { + } - const mipmap = mipmaps[ j ]; + } - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + return image; - if ( glFormat !== null ) { + } - state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + function isPowerOfTwo$1( image ) { - } else { + return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); - console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + } - } + function textureNeedsPowerOfTwo( texture ) { - } else { + if ( isWebGL2 ) return false; - state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); - } + } - } + function textureNeedsGenerateMipmaps( texture, supportsMips ) { - } + return texture.generateMipmaps && supportsMips && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - textureProperties.__maxMipLevel = mipmaps.length - 1; + } - } else { + function generateMipmap( target ) { - mipmaps = texture.mipmaps; + _gl.generateMipmap( target ); - for ( let i = 0; i < 6; i ++ ) { + } - if ( isDataTexture ) { + function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) { - state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + if ( isWebGL2 === false ) return glFormat; - for ( let j = 0; j < mipmaps.length; j ++ ) { + if ( internalFormatName !== null ) { - const mipmap = mipmaps[ j ]; - const mipmapImage = mipmap.image[ i ].image; + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; - state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); - } + } - } else { + let internalFormat = glFormat; - state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + if ( glFormat === 6403 ) { - for ( let j = 0; j < mipmaps.length; j ++ ) { + if ( glType === 5126 ) internalFormat = 33326; + if ( glType === 5131 ) internalFormat = 33325; + if ( glType === 5121 ) internalFormat = 33321; - const mipmap = mipmaps[ j ]; + } - state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + if ( glFormat === 33319 ) { - } + if ( glType === 5126 ) internalFormat = 33328; + if ( glType === 5131 ) internalFormat = 33327; + if ( glType === 5121 ) internalFormat = 33323; - } + } - } + if ( glFormat === 6408 ) { - textureProperties.__maxMipLevel = mipmaps.length; + if ( glType === 5126 ) internalFormat = 34836; + if ( glType === 5131 ) internalFormat = 34842; + if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? 35907 : 32856; + if ( glType === 32819 ) internalFormat = 32854; + if ( glType === 32820 ) internalFormat = 32855; } - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + if ( internalFormat === 33325 || internalFormat === 33326 || + internalFormat === 33327 || internalFormat === 33328 || + internalFormat === 34842 || internalFormat === 34836 ) { - // We assume images for cube map have the same size. - generateMipmap( 34067, texture, image.width, image.height ); + extensions.get( 'EXT_color_buffer_float' ); } - textureProperties.__version = texture.version; - - if ( texture.onUpdate ) texture.onUpdate( texture ); + return internalFormat; } - // Render targets + function getMipLevels( texture, image, supportsMips ) { - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { - const texture = renderTarget.texture; + return Math.log2( Math.max( image.width, image.height ) ) + 1; - const glFormat = utils.convert( texture.format ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps - if ( textureTarget === 32879 || textureTarget === 35866 ) { + return texture.mipmaps.length; - state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null ); + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; } else { - state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + // texture without mipmaps (only base level) - } + return 1; - _gl.bindFramebuffer( 36160, framebuffer ); - _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 ); - _gl.bindFramebuffer( 36160, null ); + } } - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + // Fallback filters for non-power-of-2 textures - _gl.bindRenderbuffer( 36161, renderbuffer ); + function filterFallback( f ) { - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { - let glInternalFormat = 33189; + return 9728; - if ( isMultisample ) { + } - const depthTexture = renderTarget.depthTexture; + return 9729; - if ( depthTexture && depthTexture.isDepthTexture ) { + } - if ( depthTexture.type === FloatType ) { + // - glInternalFormat = 36012; + function onTextureDispose( event ) { - } else if ( depthTexture.type === UnsignedIntType ) { + const texture = event.target; - glInternalFormat = 33190; + texture.removeEventListener( 'dispose', onTextureDispose ); - } + deallocateTexture( texture ); - } + if ( texture.isVideoTexture ) { - const samples = getRenderTargetSamples( renderTarget ); + _videoTextures.delete( texture ); - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + } - } else { + } - _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + function onRenderTargetDispose( event ) { - } + const renderTarget = event.target; - _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + deallocateRenderTarget( renderTarget ); - if ( isMultisample ) { + } - const samples = getRenderTargetSamples( renderTarget ); + // - _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); + function deallocateTexture( texture ) { - } else { + const textureProperties = properties.get( texture ); - _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); + if ( textureProperties.__webglInit === undefined ) return; - } + // check if it's necessary to remove the WebGLTexture object + const source = texture.source; + const webglTextures = _sources.get( source ); - _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); + if ( webglTextures ) { - } else { + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; - const texture = renderTarget.texture; + // the WebGLTexture object is not used anymore, remove it - const glFormat = utils.convert( texture.format ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); + if ( webglTexture.usedTimes === 0 ) { - if ( isMultisample ) { + deleteTexture( texture ); - const samples = getRenderTargetSamples( renderTarget ); + } - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + // remove the weak map entry if no WebGLTexture uses the source anymore - } else { + if ( Object.keys( webglTextures ).length === 0 ) { - _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + _sources.delete( source ); } } - _gl.bindRenderbuffer( 36161, null ); + properties.remove( texture ); } - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture( framebuffer, renderTarget ) { + function deleteTexture( texture ) { - const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); - if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); - _gl.bindFramebuffer( 36160, framebuffer ); + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; - if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + info.memory.textures --; - throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + } - } + function deallocateRenderTarget( renderTarget ) { - // 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 ) { + const texture = renderTarget.texture; - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglTexture !== undefined ) { + + _gl.deleteTexture( textureProperties.__webglTexture ); + + info.memory.textures --; } - setTexture2D( renderTarget.depthTexture, 0 ); + if ( renderTarget.depthTexture ) { - const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + renderTarget.depthTexture.dispose(); - if ( renderTarget.depthTexture.format === DepthFormat ) { + } - _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); + if ( renderTarget.isWebGLCubeRenderTarget ) { - } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + for ( let i = 0; i < 6; i ++ ) { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); + } } else { - throw new Error( 'Unknown depthTexture format' ); + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); - } + if ( renderTargetProperties.__webglColorRenderbuffer ) { - } + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); - const renderTargetProperties = properties.get( renderTarget ); + } - const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + } - if ( renderTarget.depthTexture ) { + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); - if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); + } - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + if ( renderTarget.isWebGLMultipleRenderTargets ) { - } else { + for ( let i = 0, il = texture.length; i < il; i ++ ) { - if ( isCube ) { + const attachmentProperties = properties.get( texture[ i ] ); - renderTargetProperties.__webglDepthbuffer = []; + if ( attachmentProperties.__webglTexture ) { - for ( let i = 0; i < 6; i ++ ) { + _gl.deleteTexture( attachmentProperties.__webglTexture ); - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + info.memory.textures --; } - } else { - - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + properties.remove( texture[ i ] ); } } - _gl.bindFramebuffer( 36160, null ); + properties.remove( texture ); + properties.remove( renderTarget ); } - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + // - const texture = renderTarget.texture; + let textureUnits = 0; - const renderTargetProperties = properties.get( renderTarget ); - const textureProperties = properties.get( texture ); + function resetTextureUnits() { - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + textureUnits = 0; - textureProperties.__webglTexture = _gl.createTexture(); + } - info.memory.textures ++; + function allocateTextureUnit() { - const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true ); - const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray; - const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; + const textureUnit = textureUnits; - // Handles WebGL2 RGBFormat fallback - #18858 + if ( textureUnit >= maxTextures ) { - if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) { + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); - texture.format = RGBAFormat; + } - console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' ); + textureUnits += 1; - } + return textureUnit; - // Setup framebuffer + } - if ( isCube ) { + function getTextureCacheKey( texture ) { - renderTargetProperties.__webglFramebuffer = []; + const array = []; - for ( let i = 0; i < 6; i ++ ) { + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.encoding ); - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + return array.join(); - } + } - } else { + // - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + function setTexture2D( texture, slot ) { - if ( isMultisample ) { + const textureProperties = properties.get( texture ); - if ( isWebGL2 ) { + if ( texture.isVideoTexture ) updateVideoTexture( texture ); - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); - renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { - _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer ); + const image = texture.image; - const glFormat = utils.convert( texture.format ); - const glType = utils.convert( texture.type ); - const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); - const samples = getRenderTargetSamples( renderTarget ); - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + if ( image === null ) { - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer ); - _gl.bindRenderbuffer( 36161, null ); + console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' ); - if ( renderTarget.depthBuffer ) { + } else if ( image.complete === false ) { - renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); - } + } else { - _gl.bindFramebuffer( 36160, null ); + uploadTexture( textureProperties, texture, slot ); + return; + } - } else { + } - console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); + state.activeTexture( 33984 + slot ); + state.bindTexture( 3553, textureProperties.__webglTexture ); - } + } - } + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; } - // Setup color buffer + state.activeTexture( 33984 + slot ); + state.bindTexture( 35866, textureProperties.__webglTexture ); - if ( isCube ) { + } - state.bindTexture( 34067, textureProperties.__webglTexture ); - setTextureParameters( 34067, texture, supportsMips ); + function setTexture3D( texture, slot ) { - for ( let i = 0; i < 6; i ++ ) { + const textureProperties = properties.get( texture ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i ); + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - } + uploadTexture( textureProperties, texture, slot ); + return; - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + } - generateMipmap( 34067, texture, renderTarget.width, renderTarget.height ); + state.activeTexture( 33984 + slot ); + state.bindTexture( 32879, textureProperties.__webglTexture ); - } + } - state.bindTexture( 34067, null ); + function setTextureCube( texture, slot ) { - } else { + const textureProperties = properties.get( texture ); - let glTextureType = 3553; + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - if ( isRenderTarget3D ) { + uploadCubeTexture( textureProperties, texture, slot ); + return; - // Render targets containing layers, i.e: Texture 3D and 2d arrays + } - if ( isWebGL2 ) { + state.activeTexture( 33984 + slot ); + state.bindTexture( 34067, textureProperties.__webglTexture ); - const isTexture3D = texture.isDataTexture3D; - glTextureType = isTexture3D ? 32879 : 35866; + } - } else { + const wrappingToGL = { + [ RepeatWrapping ]: 10497, + [ ClampToEdgeWrapping ]: 33071, + [ MirroredRepeatWrapping ]: 33648 + }; + + const filterToGL = { + [ NearestFilter ]: 9728, + [ NearestMipmapNearestFilter ]: 9984, + [ NearestMipmapLinearFilter ]: 9986, + + [ LinearFilter ]: 9729, + [ LinearMipmapNearestFilter ]: 9985, + [ LinearMipmapLinearFilter ]: 9987 + }; - console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' ); + function setTextureParameters( textureType, texture, supportsMips ) { - } + if ( supportsMips ) { + + _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === 32879 || textureType === 35866 ) { + + _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); } - state.bindTexture( glTextureType, textureProperties.__webglTexture ); - setTextureParameters( glTextureType, texture, supportsMips ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, glTextureType ); + _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + } else { + + _gl.texParameteri( textureType, 10242, 33071 ); + _gl.texParameteri( textureType, 10243, 33071 ); - generateMipmap( 3553, texture, renderTarget.width, renderTarget.height ); + if ( textureType === 32879 || textureType === 35866 ) { + + _gl.texParameteri( textureType, 32882, 33071 ); } - state.bindTexture( 3553, null ); + 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.' ); - // Setup depth and stencil buffers + } - if ( renderTarget.depthBuffer ) { + _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); - setupDepthRenderbuffer( renderTarget ); + 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.' ); - } + } - function updateRenderTargetMipmap( renderTarget ) { + } - const texture = renderTarget.texture; + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 + if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; - const webglTexture = properties.get( texture ).__webglTexture; + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - state.bindTexture( target, webglTexture ); - generateMipmap( target, texture, renderTarget.width, renderTarget.height ); - state.bindTexture( target, null ); + } } } - function updateMultisampleRenderTarget( renderTarget ) { + function initTexture( textureProperties, texture ) { - if ( renderTarget.isWebGLMultisampleRenderTarget ) { + let forceUpload = false; - if ( isWebGL2 ) { + if ( textureProperties.__webglInit === undefined ) { - const renderTargetProperties = properties.get( renderTarget ); + textureProperties.__webglInit = true; - _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); + texture.addEventListener( 'dispose', onTextureDispose ); - const width = renderTarget.width; - const height = renderTarget.height; - let mask = 16384; + } - if ( renderTarget.depthBuffer ) mask |= 256; - if ( renderTarget.stencilBuffer ) mask |= 1024; + // create Source <-> WebGLTextures mapping if necessary - _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + const source = texture.source; + let webglTextures = _sources.get( source ); - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905 + if ( webglTextures === undefined ) { - } else { + webglTextures = {}; + _sources.set( source, webglTextures ); - console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); + } - } + // check if there is already a WebGLTexture object for the given texture parameters - } + const textureCacheKey = getTextureCacheKey( texture ); - } + if ( textureCacheKey !== textureProperties.__cacheKey ) { - function getRenderTargetSamples( renderTarget ) { + // if not, create a new instance of WebGLTexture - return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ? - Math.min( maxSamples, renderTarget.samples ) : 0; + if ( webglTextures[ textureCacheKey ] === undefined ) { - } + // create new entry - function updateVideoTexture( texture ) { + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; - const frame = info.render.frame; + info.memory.textures ++; - // Check the last frame we updated the VideoTexture + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical - if ( _videoTextures.get( texture ) !== frame ) { + forceUpload = true; - _videoTextures.set( texture, frame ); - texture.update(); + } - } + webglTextures[ textureCacheKey ].usedTimes ++; - } + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. - // backwards compatibility + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; - let warnedTexture2D = false; - let warnedTextureCube = false; + if ( webglTexture !== undefined ) { - function safeSetTexture2D( texture, slot ) { + webglTextures[ textureProperties.__cacheKey ].usedTimes --; - if ( texture && texture.isWebGLRenderTarget ) { + if ( webglTexture.usedTimes === 0 ) { - if ( warnedTexture2D === false ) { + deleteTexture( texture ); - console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' ); - warnedTexture2D = true; + } } - texture = texture.texture; + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; } - setTexture2D( texture, slot ); + return forceUpload; } - function safeSetTextureCube( texture, slot ) { + function uploadTexture( textureProperties, texture, slot ) { - if ( texture && texture.isWebGLCubeRenderTarget ) { + let textureType = 3553; - if ( warnedTextureCube === false ) { + if ( texture.isDataArrayTexture ) textureType = 35866; + if ( texture.isData3DTexture ) textureType = 32879; - console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' ); - warnedTextureCube = true; + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; - } + state.activeTexture( 33984 + slot ); + state.bindTexture( textureType, textureProperties.__webglTexture ); - texture = texture.texture; + if ( source.version !== source.__currentVersion || forceUpload === true ) { - } + _gl.pixelStorei( 37440, texture.flipY ); + _gl.pixelStorei( 37441, texture.premultiplyAlpha ); + _gl.pixelStorei( 3317, texture.unpackAlignment ); + _gl.pixelStorei( 37443, 0 ); + const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false; + let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + image = verifyColorSpace( texture, image ); - setTextureCube( texture, slot ); + const supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ); - } + let glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture ); - // + setTextureParameters( textureType, texture, supportsMips ); - this.allocateTextureUnit = allocateTextureUnit; - this.resetTextureUnits = resetTextureUnits; + let mipmap; + const mipmaps = texture.mipmaps; - this.setTexture2D = setTexture2D; - this.setTexture2DArray = setTexture2DArray; - this.setTexture3D = setTexture3D; - this.setTextureCube = setTextureCube; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; - this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); + const levels = getMipLevels( texture, image, supportsMips ); - this.safeSetTexture2D = safeSetTexture2D; - this.safeSetTextureCube = safeSetTextureCube; + if ( texture.isDepthTexture ) { -} + // populate depth texture with dummy data -function WebGLUtils( gl, extensions, capabilities ) { + glInternalFormat = 6402; - const isWebGL2 = capabilities.isWebGL2; + if ( isWebGL2 ) { - function convert( p ) { + if ( texture.type === FloatType ) { - let extension; + glInternalFormat = 36012; - if ( p === UnsignedByteType ) return 5121; - if ( p === UnsignedShort4444Type ) return 32819; - if ( p === UnsignedShort5551Type ) return 32820; - if ( p === UnsignedShort565Type ) return 33635; + } else if ( texture.type === UnsignedIntType ) { - if ( p === ByteType ) return 5120; - if ( p === ShortType ) return 5122; - if ( p === UnsignedShortType ) return 5123; - if ( p === IntType ) return 5124; - if ( p === UnsignedIntType ) return 5125; - if ( p === FloatType ) return 5126; + glInternalFormat = 33190; - if ( p === HalfFloatType ) { + } else if ( texture.type === UnsignedInt248Type ) { - if ( isWebGL2 ) return 5131; + glInternalFormat = 35056; - extension = extensions.get( 'OES_texture_half_float' ); + } else { - if ( extension !== null ) { + glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D - return extension.HALF_FLOAT_OES; + } - } else { + } else { - return null; + if ( texture.type === FloatType ) { - } + console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); - } + } - if ( p === AlphaFormat ) return 6406; - if ( p === RGBFormat ) return 6407; - if ( p === RGBAFormat ) return 6408; - if ( p === LuminanceFormat ) return 6409; - if ( p === LuminanceAlphaFormat ) return 6410; - if ( p === DepthFormat ) return 6402; - if ( p === DepthStencilFormat ) return 34041; - if ( p === RedFormat ) return 6403; + } - // WebGL2 formats. + // validation checks for WebGL 1 - if ( p === RedIntegerFormat ) return 36244; - if ( p === RGFormat ) return 33319; - if ( p === RGIntegerFormat ) return 33320; - if ( p === RGBIntegerFormat ) return 36248; - if ( p === RGBAIntegerFormat ) return 36249; + if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { - if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || - p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); - if ( extension !== null ) { + texture.type = UnsignedIntType; + glType = utils.convert( texture.type ); - 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; + } - } else { + } - return null; + if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) { - } + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + glInternalFormat = 34041; - } + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { - if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || - p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); - if ( extension !== null ) { + } - 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; + } - } else { + // - return null; + if ( allocateMemory ) { - } + if ( useTexStorage ) { - } + state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height ); - if ( p === RGB_ETC1_Format ) { + } else { - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); - if ( extension !== null ) { + } - return extension.COMPRESSED_RGB_ETC1_WEBGL; + } - } else { + } else if ( texture.isDataTexture ) { - return null; + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - } + if ( mipmaps.length > 0 && supportsMips ) { - } + if ( useTexStorage && allocateMemory ) { - if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); - extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + } - if ( extension !== null ) { + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { - if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2; - if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC; + mipmap = mipmaps[ i ]; - } + if ( useTexStorage ) { - } + state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); - if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || - p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || - p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || - p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || - p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || - p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || - p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || - p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || - p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || - p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) { + } else { - extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - if ( extension !== null ) { + } - // TODO Complete? + } - return p; + texture.generateMipmaps = false; - } else { + } else { - return null; + if ( useTexStorage ) { - } + if ( allocateMemory ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - if ( p === RGBA_BPTC_Format ) { + } - extension = extensions.get( 'EXT_texture_compression_bptc' ); + state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); - if ( extension !== null ) { + } else { - // TODO Complete? + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); - return p; + } - } else { + } - return null; + } else if ( texture.isCompressedTexture ) { - } + if ( useTexStorage && allocateMemory ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); - if ( p === UnsignedInt248Type ) { + } - if ( isWebGL2 ) return 34042; + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { - extension = extensions.get( 'WEBGL_depth_texture' ); + mipmap = mipmaps[ i ]; - if ( extension !== null ) { + if ( texture.format !== RGBAFormat ) { - return extension.UNSIGNED_INT_24_8_WEBGL; + if ( glFormat !== null ) { - } else { + if ( useTexStorage ) { - return null; + state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); - } + } else { - } + state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } + } - return { convert: convert }; + } else { -} + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); -function ArrayCamera( array = [] ) { + } - PerspectiveCamera.call( this ); + } else { - this.cameras = array; + if ( useTexStorage ) { -} + state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); -ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), { + } else { - constructor: ArrayCamera, + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - isArrayCamera: true + } -} ); + } -class Group extends Object3D { + } - constructor() { + } else if ( texture.isDataArrayTexture ) { - super(); + if ( useTexStorage ) { - this.type = 'Group'; + if ( allocateMemory ) { - } + state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth ); -} + } -Group.prototype.isGroup = true; + state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); -function WebXRController() { + } else { - this._targetRay = null; - this._grip = null; - this._hand = null; + state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); -} + } -Object.assign( WebXRController.prototype, { + } else if ( texture.isData3DTexture ) { - constructor: WebXRController, + if ( useTexStorage ) { - getHandSpace: function () { + if ( allocateMemory ) { - if ( this._hand === null ) { + state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth ); - this._hand = new Group(); - this._hand.matrixAutoUpdate = false; - this._hand.visible = false; + } - this._hand.joints = {}; - this._hand.inputState = { pinching: false }; + state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); - } + } else { - return this._hand; + state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - }, + } - getTargetRaySpace: function () { + } else if ( texture.isFramebufferTexture ) { - if ( this._targetRay === null ) { + if ( allocateMemory ) { - this._targetRay = new Group(); - this._targetRay.matrixAutoUpdate = false; - this._targetRay.visible = false; + if ( useTexStorage ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - return this._targetRay; + } else { - }, + let width = image.width, height = image.height; - getGripSpace: function () { + for ( let i = 0; i < levels; i ++ ) { - if ( this._grip === null ) { + state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null ); - this._grip = new Group(); - this._grip.matrixAutoUpdate = false; - this._grip.visible = false; + width >>= 1; + height >>= 1; - } + } - return this._grip; + } + + } + + } else { - }, + // regular Texture (image, video, canvas) - dispatchEvent: function ( event ) { + // 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 ( this._targetRay !== null ) { + if ( mipmaps.length > 0 && supportsMips ) { - this._targetRay.dispatchEvent( event ); + if ( useTexStorage && allocateMemory ) { - } + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); - if ( this._grip !== null ) { + } - this._grip.dispatchEvent( event ); + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { - } + mipmap = mipmaps[ i ]; - if ( this._hand !== null ) { + if ( useTexStorage ) { - this._hand.dispatchEvent( event ); + state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap ); - } + } else { - return this; + state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); - }, + } - disconnect: function ( inputSource ) { + } - this.dispatchEvent( { type: 'disconnected', data: inputSource } ); + texture.generateMipmaps = false; - if ( this._targetRay !== null ) { + } else { - this._targetRay.visible = false; + if ( useTexStorage ) { - } + if ( allocateMemory ) { - if ( this._grip !== null ) { + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); - this._grip.visible = false; + } - } + state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image ); - if ( this._hand !== null ) { + } else { - this._hand.visible = false; + state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); - } + } - return this; + } - }, + } - update: function ( inputSource, frame, referenceSpace ) { + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - let inputPose = null; - let gripPose = null; - let handPose = null; + generateMipmap( textureType ); - const targetRay = this._targetRay; - const grip = this._grip; - const hand = this._hand; + } - if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { + source.__currentVersion = source.version; - if ( hand && inputSource.hand ) { + if ( texture.onUpdate ) texture.onUpdate( texture ); - handPose = true; + } - for ( const inputjoint of inputSource.hand.values() ) { + textureProperties.__version = texture.version; - // Update the joints groups with the XRJoint poses - const jointPose = frame.getJointPose( inputjoint, referenceSpace ); + } - if ( hand.joints[ inputjoint.jointName ] === undefined ) { + function uploadCubeTexture( textureProperties, texture, slot ) { - // The transform of this joint will be updated with the joint pose on each frame - const joint = new Group(); - joint.matrixAutoUpdate = false; - joint.visible = false; - hand.joints[ inputjoint.jointName ] = joint; - // ?? - hand.add( joint ); + if ( texture.image.length !== 6 ) return; - } + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; - const joint = hand.joints[ inputjoint.jointName ]; + state.activeTexture( 33984 + slot ); + state.bindTexture( 34067, textureProperties.__webglTexture ); - if ( jointPose !== null ) { + if ( source.version !== source.__currentVersion || forceUpload === true ) { - joint.matrix.fromArray( jointPose.transform.matrix ); - joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); - joint.jointRadius = jointPose.radius; + _gl.pixelStorei( 37440, texture.flipY ); + _gl.pixelStorei( 37441, texture.premultiplyAlpha ); + _gl.pixelStorei( 3317, texture.unpackAlignment ); + _gl.pixelStorei( 37443, 0 ); - } + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); - joint.visible = jointPose !== null; + const cubeImage = []; - } + for ( let i = 0; i < 6; i ++ ) { - // Custom events + if ( ! isCompressed && ! isDataTexture ) { - // Check pinchz - const indexTip = hand.joints[ 'index-finger-tip' ]; - const thumbTip = hand.joints[ 'thumb-tip' ]; - const distance = indexTip.position.distanceTo( thumbTip.position ); + cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); - const distanceToPinch = 0.02; - const threshold = 0.005; + } else { - if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - hand.inputState.pinching = false; - this.dispatchEvent( { - type: 'pinchend', - handedness: inputSource.handedness, - target: this - } ); + } - } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); - hand.inputState.pinching = true; - this.dispatchEvent( { - type: 'pinchstart', - handedness: inputSource.handedness, - target: this - } ); + } - } + const image = cubeImage[ 0 ], + supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); - } else { + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true ); + let levels = getMipLevels( texture, image, supportsMips ); - if ( targetRay !== null ) { + setTextureParameters( 34067, texture, supportsMips ); - inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + let mipmaps; - if ( inputPose !== null ) { + if ( isCompressed ) { - targetRay.matrix.fromArray( inputPose.transform.matrix ); - targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + if ( useTexStorage && allocateMemory ) { - } + state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height ); } - if ( grip !== null && inputSource.gripSpace ) { + for ( let i = 0; i < 6; i ++ ) { - gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); + mipmaps = cubeImage[ i ].mipmaps; - if ( gripPose !== null ) { + for ( let j = 0; j < mipmaps.length; j ++ ) { - grip.matrix.fromArray( gripPose.transform.matrix ); - grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); + const mipmap = mipmaps[ j ]; - } + if ( texture.format !== RGBAFormat ) { - } + if ( glFormat !== null ) { - } + if ( useTexStorage ) { - } + state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); - if ( targetRay !== null ) { + } else { - targetRay.visible = ( inputPose !== null ); + state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } + } - if ( grip !== null ) { + } else { - grip.visible = ( gripPose !== null ); + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); - } + } - if ( hand !== null ) { + } else { - hand.visible = ( handPose !== null ); + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); - return this; + } else { - } + state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); -} ); + } -function WebXRManager( renderer, gl ) { + } - const scope = this; + } - let session = null; + } - let framebufferScaleFactor = 1.0; + } else { - let referenceSpace = null; - let referenceSpaceType = 'local-floor'; + mipmaps = texture.mipmaps; - let pose = null; + if ( useTexStorage && allocateMemory ) { - const controllers = []; - const inputSourcesMap = new Map(); + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) - // + if ( mipmaps.length > 0 ) levels ++; - const cameraL = new PerspectiveCamera(); - cameraL.layers.enable( 1 ); - cameraL.viewport = new Vector4(); + state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); - const cameraR = new PerspectiveCamera(); - cameraR.layers.enable( 2 ); - cameraR.viewport = new Vector4(); + } - const cameras = [ cameraL, cameraR ]; + for ( let i = 0; i < 6; i ++ ) { - const cameraVR = new ArrayCamera(); - cameraVR.layers.enable( 1 ); - cameraVR.layers.enable( 2 ); + if ( isDataTexture ) { - let _currentDepthNear = null; - let _currentDepthFar = null; + if ( useTexStorage ) { - // + state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); - this.enabled = false; + } else { - this.isPresenting = false; + state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - this.getController = function ( index ) { + } - let controller = controllers[ index ]; + for ( let j = 0; j < mipmaps.length; j ++ ) { - if ( controller === undefined ) { + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; - controller = new WebXRController(); - controllers[ index ] = controller; + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); - return controller.getTargetRaySpace(); + } else { - }; + state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); - this.getControllerGrip = function ( index ) { + } - let controller = controllers[ index ]; + } - if ( controller === undefined ) { + } else { - controller = new WebXRController(); - controllers[ index ] = controller; + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); - return controller.getGripSpace(); + } else { - }; + state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); - this.getHand = function ( index ) { + } - let controller = controllers[ index ]; + for ( let j = 0; j < mipmaps.length; j ++ ) { - if ( controller === undefined ) { + const mipmap = mipmaps[ j ]; - controller = new WebXRController(); - controllers[ index ] = controller; + if ( useTexStorage ) { - } + state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); - return controller.getHandSpace(); + } else { - }; + state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); - // + } - function onSessionEvent( event ) { + } - const controller = inputSourcesMap.get( event.inputSource ); + } - if ( controller ) { + } - controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + } - } + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - } + // We assume images for cube map have the same size. + generateMipmap( 34067 ); - function onSessionEnd() { + } - inputSourcesMap.forEach( function ( controller, inputSource ) { + source.__currentVersion = source.version; - controller.disconnect( inputSource ); + if ( texture.onUpdate ) texture.onUpdate( texture ); - } ); + } - inputSourcesMap.clear(); + textureProperties.__version = texture.version; - _currentDepthNear = null; - _currentDepthFar = null; + } - // + // Render targets - renderer.setFramebuffer( null ); - renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830 - animation.stop(); + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) { - scope.isPresenting = false; + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const renderTargetProperties = properties.get( renderTarget ); - scope.dispatchEvent( { type: 'sessionend' } ); + if ( ! renderTargetProperties.__hasExternalTextures ) { - } + if ( textureTarget === 32879 || textureTarget === 35866 ) { - this.setFramebufferScaleFactor = function ( value ) { + state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null ); - framebufferScaleFactor = value; + } else { - if ( scope.isPresenting === true ) { + state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); + } } - }; + state.bindFramebuffer( 36160, framebuffer ); - this.setReferenceSpaceType = function ( value ) { + if ( useMultisampledRTT( renderTarget ) ) { - referenceSpaceType = value; + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); - if ( scope.isPresenting === true ) { + } else { - console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); + _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 ); } - }; - - this.getReferenceSpace = function () { + state.bindFramebuffer( 36160, null ); - return referenceSpace; + } - }; - this.getSession = function () { + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { - return session; + _gl.bindRenderbuffer( 36161, renderbuffer ); - }; + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - this.setSession = async function ( value ) { + let glInternalFormat = 33189; - session = value; + if ( isMultisample || useMultisampledRTT( renderTarget ) ) { - if ( session !== null ) { + const depthTexture = renderTarget.depthTexture; - session.addEventListener( 'select', onSessionEvent ); - session.addEventListener( 'selectstart', onSessionEvent ); - session.addEventListener( 'selectend', onSessionEvent ); - session.addEventListener( 'squeeze', onSessionEvent ); - session.addEventListener( 'squeezestart', onSessionEvent ); - session.addEventListener( 'squeezeend', onSessionEvent ); - session.addEventListener( 'end', onSessionEnd ); - session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + if ( depthTexture && depthTexture.isDepthTexture ) { - const attributes = gl.getContextAttributes(); + if ( depthTexture.type === FloatType ) { - if ( attributes.xrCompatible !== true ) { + glInternalFormat = 36012; - await gl.makeXRCompatible(); + } else if ( depthTexture.type === UnsignedIntType ) { - } + glInternalFormat = 33190; - const layerInit = { - antialias: attributes.antialias, - alpha: attributes.alpha, - depth: attributes.depth, - stencil: attributes.stencil, - framebufferScaleFactor: framebufferScaleFactor - }; + } - // eslint-disable-next-line no-undef - const baseLayer = new XRWebGLLayer( session, gl, layerInit ); + } - session.updateRenderState( { baseLayer: baseLayer } ); + const samples = getRenderTargetSamples( renderTarget ); - referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + if ( useMultisampledRTT( renderTarget ) ) { - animation.setContext( session ); - animation.start(); + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - scope.isPresenting = true; + } else { - scope.dispatchEvent( { type: 'sessionstart' } ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - } + } - }; + } else { - function onInputSourcesChange( event ) { + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); - const inputSources = session.inputSources; + } - // Assign inputSources to available controllers + _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); - for ( let i = 0; i < controllers.length; i ++ ) { + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - inputSourcesMap.set( inputSources[ i ], controllers[ i ] ); + const samples = getRenderTargetSamples( renderTarget ); - } + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { - // Notify disconnected + _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); - for ( let i = 0; i < event.removed.length; i ++ ) { + } else if ( useMultisampledRTT( renderTarget ) ) { - const inputSource = event.removed[ i ]; - const controller = inputSourcesMap.get( inputSource ); + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height ); - if ( controller ) { + } else { - controller.dispatchEvent( { type: 'disconnected', data: inputSource } ); - inputSourcesMap.delete( inputSource ); + _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); } - } - - // Notify connected - for ( let i = 0; i < event.added.length; i ++ ) { + _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); - const inputSource = event.added[ i ]; - const controller = inputSourcesMap.get( inputSource ); + } else { - if ( controller ) { + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; - controller.dispatchEvent( { type: 'connected', data: inputSource } ); + for ( let i = 0; i < textures.length; i ++ ) { - } + const texture = textures[ i ]; - } + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); - } + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { - // + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - const cameraLPos = new Vector3(); - const cameraRPos = new Vector3(); + } else if ( useMultisampledRTT( renderTarget ) ) { - /** - * Assumes 2 cameras that are parallel and share an X-axis, and that - * the cameras' projection and world matrices have already been set. - * And that near and far planes are identical for both cameras. - * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 - */ - function setProjectionFromUnion( camera, cameraL, cameraR ) { + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); - cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + } else { - const ipd = cameraLPos.distanceTo( cameraRPos ); + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); - const projL = cameraL.projectionMatrix.elements; - const projR = cameraR.projectionMatrix.elements; + } - // VR systems will have identical far and near planes, and - // most likely identical top and bottom frustum extents. - // Use the left camera for these values. - const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); - const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); - const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; - const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + } - const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; - const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; - const left = near * leftFov; - const right = near * rightFov; + } - // Calculate the new camera's position offset from the - // left camera. xOffset should be roughly half `ipd`. - const zOffset = ipd / ( - leftFov + rightFov ); - const xOffset = zOffset * - leftFov; + _gl.bindRenderbuffer( 36161, null ); - // TODO: Better way to apply this offset? - cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); - camera.translateX( xOffset ); - camera.translateZ( zOffset ); - camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); - camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + } - // Find the union of the frustum values of the cameras and scale - // the values so that the near plane's position does not change in world space, - // although must now be relative to the new union camera. - const near2 = near + zOffset; - const far2 = far + zOffset; - const left2 = left - xOffset; - const right2 = right + ( ipd - xOffset ); - const top2 = topFov * far / far2 * near2; - const bottom2 = bottomFov * far / far2 * near2; + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { - camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); - } + state.bindFramebuffer( 36160, framebuffer ); - function updateCamera( camera, parent ) { + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { - if ( parent === null ) { + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); - camera.matrixWorld.copy( camera.matrix ); + } - } else { + // 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 ) { - camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; } - camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + setTexture2D( renderTarget.depthTexture, 0 ); - } + const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); - this.getCamera = function ( camera ) { + if ( renderTarget.depthTexture.format === DepthFormat ) { - cameraVR.near = cameraR.near = cameraL.near = camera.near; - cameraVR.far = cameraR.far = cameraL.far = camera.far; + if ( useMultisampledRTT( renderTarget ) ) { - if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples ); - // Note that the new renderState won't apply until the next frame. See #18320 + } else { - session.updateRenderState( { - depthNear: cameraVR.near, - depthFar: cameraVR.far - } ); + _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); - _currentDepthNear = cameraVR.near; - _currentDepthFar = cameraVR.far; + } - } + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { - const parent = camera.parent; - const cameras = cameraVR.cameras; + if ( useMultisampledRTT( renderTarget ) ) { - updateCamera( cameraVR, parent ); + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples ); - for ( let i = 0; i < cameras.length; i ++ ) { + } else { - updateCamera( cameras[ i ], parent ); + _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); - } + } - // update camera and its children + } else { - camera.matrixWorld.copy( cameraVR.matrixWorld ); - camera.matrix.copy( cameraVR.matrix ); - camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + throw new Error( 'Unknown depthTexture format' ); - const children = camera.children; + } - for ( let i = 0, l = children.length; i < l; i ++ ) { + } - children[ i ].updateMatrixWorld( true ); + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - } + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - // update projection matrix for proper view frustum culling + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { - if ( cameras.length === 2 ) { + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); - setProjectionFromUnion( cameraVR, cameraL, cameraR ); + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); } else { - // assume single camera setup (AR) + if ( isCube ) { - cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); + renderTargetProperties.__webglDepthbuffer = []; - } + for ( let i = 0; i < 6; i ++ ) { - return cameraVR; + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); - }; + } - // Animation Loop + } else { - let onAnimationFrameCallback = null; + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); - function onAnimationFrame( time, frame ) { + } + + } - pose = frame.getViewerPose( referenceSpace ); + state.bindFramebuffer( 36160, null ); - if ( pose !== null ) { + } - const views = pose.views; - const baseLayer = session.renderState.baseLayer; + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { - renderer.setFramebuffer( baseLayer.framebuffer ); + const renderTargetProperties = properties.get( renderTarget ); - let cameraVRNeedsUpdate = false; + if ( colorTexture !== undefined ) { - // check if it's necessary to rebuild cameraVR's camera list + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 ); - if ( views.length !== cameraVR.cameras.length ) { + } - cameraVR.cameras.length = 0; - cameraVRNeedsUpdate = true; + if ( depthTexture !== undefined ) { - } + setupDepthRenderbuffer( renderTarget ); - for ( let i = 0; i < views.length; i ++ ) { + } - const view = views[ i ]; - const viewport = baseLayer.getViewport( view ); + } - const camera = cameras[ i ]; - camera.matrix.fromArray( view.transform.matrix ); - camera.projectionMatrix.fromArray( view.projectionMatrix ); - camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - if ( i === 0 ) { + const texture = renderTarget.texture; - cameraVR.matrix.copy( camera.matrix ); + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); - } + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - if ( cameraVRNeedsUpdate === true ) { + if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { - cameraVR.cameras.push( camera ); + if ( textureProperties.__webglTexture === undefined ) { - } + textureProperties.__webglTexture = _gl.createTexture(); } - } + textureProperties.__version = texture.version; + info.memory.textures ++; - // + } - const inputSources = session.inputSources; + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - for ( let i = 0; i < controllers.length; i ++ ) { + // Setup framebuffer - const controller = controllers[ i ]; - const inputSource = inputSources[ i ]; + if ( isCube ) { - controller.update( inputSource, frame, referenceSpace ); + renderTargetProperties.__webglFramebuffer = []; - } + for ( let i = 0; i < 6; i ++ ) { - if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - } + } - const animation = new WebGLAnimation(); - animation.setAnimationLoop( onAnimationFrame ); + } else { - this.setAnimationLoop = function ( callback ) { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - onAnimationFrameCallback = callback; + if ( isMultipleRenderTargets ) { - }; + if ( capabilities.drawBuffers ) { - this.dispose = function () {}; + const textures = renderTarget.texture; -} + for ( let i = 0, il = textures.length; i < il; i ++ ) { -Object.assign( WebXRManager.prototype, EventDispatcher.prototype ); + const attachmentProperties = properties.get( textures[ i ] ); -function WebGLMaterials( properties ) { + if ( attachmentProperties.__webglTexture === undefined ) { - function refreshFogUniforms( uniforms, fog ) { + attachmentProperties.__webglTexture = _gl.createTexture(); - uniforms.fogColor.value.copy( fog.color ); + info.memory.textures ++; - if ( fog.isFog ) { + } - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + } - } else if ( fog.isFogExp2 ) { + } else { - uniforms.fogDensity.value = fog.density; + console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' ); - } + } - } + } - function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) { + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - if ( material.isMeshBasicMaterial ) { + const textures = isMultipleRenderTargets ? texture : [ texture ]; - refreshUniformsCommon( uniforms, material ); + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; - } else if ( material.isMeshLambertMaterial ) { + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsLambert( uniforms, material ); + for ( let i = 0; i < textures.length; i ++ ) { - } else if ( material.isMeshToonMaterial ) { + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); - refreshUniformsCommon( uniforms, material ); - refreshUniformsToon( uniforms, material ); + _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } else if ( material.isMeshPhongMaterial ) { + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsPhong( uniforms, material ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } else if ( material.isMeshStandardMaterial ) { + } - refreshUniformsCommon( uniforms, material ); + _gl.bindRenderbuffer( 36161, null ); - if ( material.isMeshPhysicalMaterial ) { + if ( renderTarget.depthBuffer ) { - refreshUniformsPhysical( uniforms, material ); + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); - } else { + } - refreshUniformsStandard( uniforms, material ); + state.bindFramebuffer( 36160, null ); } - } else if ( material.isMeshMatcapMaterial ) { - - refreshUniformsCommon( uniforms, material ); - refreshUniformsMatcap( uniforms, material ); + } - } else if ( material.isMeshDepthMaterial ) { + // Setup color buffer - refreshUniformsCommon( uniforms, material ); - refreshUniformsDepth( uniforms, material ); + if ( isCube ) { - } else if ( material.isMeshDistanceMaterial ) { + state.bindTexture( 34067, textureProperties.__webglTexture ); + setTextureParameters( 34067, texture, supportsMips ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsDistance( uniforms, material ); + for ( let i = 0; i < 6; i ++ ) { - } else if ( material.isMeshNormalMaterial ) { + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i ); - refreshUniformsCommon( uniforms, material ); - refreshUniformsNormal( uniforms, material ); + } - } else if ( material.isLineBasicMaterial ) { + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - refreshUniformsLine( uniforms, material ); + generateMipmap( 34067 ); - if ( material.isLineDashedMaterial ) { + } - refreshUniformsDash( uniforms, material ); + state.unbindTexture(); - } + } else if ( isMultipleRenderTargets ) { - } else if ( material.isPointsMaterial ) { + const textures = renderTarget.texture; - refreshUniformsPoints( uniforms, material, pixelRatio, height ); + for ( let i = 0, il = textures.length; i < il; i ++ ) { - } else if ( material.isSpriteMaterial ) { + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); - refreshUniformsSprites( uniforms, material ); + state.bindTexture( 3553, attachmentProperties.__webglTexture ); + setTextureParameters( 3553, attachment, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 ); - } else if ( material.isShadowMaterial ) { + if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) { - uniforms.color.value.copy( material.color ); - uniforms.opacity.value = material.opacity; + generateMipmap( 3553 ); - } else if ( material.isShaderMaterial ) { + } - material.uniformsNeedUpdate = false; // #15581 + } - } + state.unbindTexture(); - } + } else { - function refreshUniformsCommon( uniforms, material ) { + let glTextureType = 3553; - uniforms.opacity.value = material.opacity; + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { - if ( material.color ) { + if ( isWebGL2 ) { - uniforms.diffuse.value.copy( material.color ); + glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866; - } + } else { - if ( material.emissive ) { + console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' ); - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + } - } + } - if ( material.map ) { + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType ); - uniforms.map.value = material.map; + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - } + generateMipmap( glTextureType ); - if ( material.alphaMap ) { + } - uniforms.alphaMap.value = material.alphaMap; + state.unbindTexture(); } - if ( material.specularMap ) { + // Setup depth and stencil buffers - uniforms.specularMap.value = material.specularMap; + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); } - const envMap = properties.get( material ).envMap; + } - if ( envMap ) { + function updateRenderTargetMipmap( renderTarget ) { - uniforms.envMap.value = envMap; + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; - uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1; + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + for ( let i = 0, il = textures.length; i < il; i ++ ) { - const maxMipLevel = properties.get( envMap ).__maxMipLevel; + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - if ( maxMipLevel !== undefined ) { + const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; + const webglTexture = properties.get( texture ).__webglTexture; - uniforms.maxMipLevel.value = maxMipLevel; + state.bindTexture( target, webglTexture ); + generateMipmap( target ); + state.unbindTexture(); } } - if ( material.lightMap ) { + } - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + function updateMultisampleRenderTarget( renderTarget ) { - } + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { - if ( material.aoMap ) { + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = 16384; + const invalidationArray = []; + const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { - } + for ( let i = 0; i < textures.length; i ++ ) { - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. displacementMap map - // 4. normal map - // 5. bump map - // 6. roughnessMap map - // 7. metalnessMap map - // 8. alphaMap map - // 9. emissiveMap map - // 10. clearcoat map - // 11. clearcoat normal map - // 12. clearcoat roughnessMap map + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null ); - let uvScaleMap; + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 ); - if ( material.map ) { + } - uvScaleMap = material.map; + } - } else if ( material.specularMap ) { + state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); + state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); - uvScaleMap = material.specularMap; + for ( let i = 0; i < textures.length; i ++ ) { - } else if ( material.displacementMap ) { + invalidationArray.push( 36064 + i ); - uvScaleMap = material.displacementMap; + if ( renderTarget.depthBuffer ) { - } else if ( material.normalMap ) { + invalidationArray.push( depthStyle ); - uvScaleMap = material.normalMap; + } - } else if ( material.bumpMap ) { + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; - uvScaleMap = material.bumpMap; + if ( ignoreDepthValues === false ) { - } else if ( material.roughnessMap ) { + if ( renderTarget.depthBuffer ) mask |= 256; + if ( renderTarget.stencilBuffer ) mask |= 1024; - uvScaleMap = material.roughnessMap; + } - } else if ( material.metalnessMap ) { + if ( isMultipleRenderTargets ) { - uvScaleMap = material.metalnessMap; + _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } else if ( material.alphaMap ) { + } - uvScaleMap = material.alphaMap; + if ( ignoreDepthValues === true ) { - } else if ( material.emissiveMap ) { + _gl.invalidateFramebuffer( 36008, [ depthStyle ] ); + _gl.invalidateFramebuffer( 36009, [ depthStyle ] ); - uvScaleMap = material.emissiveMap; + } - } else if ( material.clearcoatMap ) { + if ( isMultipleRenderTargets ) { - uvScaleMap = material.clearcoatMap; + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 ); - } else if ( material.clearcoatNormalMap ) { + } - uvScaleMap = material.clearcoatNormalMap; + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); - } else if ( material.clearcoatRoughnessMap ) { + if ( supportsInvalidateFramebuffer ) { - uvScaleMap = material.clearcoatRoughnessMap; + _gl.invalidateFramebuffer( 36008, invalidationArray ); - } + } - if ( uvScaleMap !== undefined ) { - // backwards compatibility - if ( uvScaleMap.isWebGLRenderTarget ) { + } - uvScaleMap = uvScaleMap.texture; + state.bindFramebuffer( 36008, null ); + state.bindFramebuffer( 36009, null ); - } + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { - if ( uvScaleMap.matrixAutoUpdate === true ) { + for ( let i = 0; i < textures.length; i ++ ) { - uvScaleMap.updateMatrix(); + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); - } + const webglTexture = properties.get( textures[ i ] ).__webglTexture; - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 ); - } + } - // uv repeat and offset setting priorities for uv2 - // 1. ao map - // 2. light map + } - let uv2ScaleMap; + state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer ); + + } - if ( material.aoMap ) { + } - uv2ScaleMap = material.aoMap; + function getRenderTargetSamples( renderTarget ) { - } else if ( material.lightMap ) { + return Math.min( maxSamples, renderTarget.samples ); - uv2ScaleMap = material.lightMap; + } - } + function useMultisampledRTT( renderTarget ) { - if ( uv2ScaleMap !== undefined ) { + const renderTargetProperties = properties.get( renderTarget ); - // backwards compatibility - if ( uv2ScaleMap.isWebGLRenderTarget ) { + return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; - uv2ScaleMap = uv2ScaleMap.texture; + } - } + function updateVideoTexture( texture ) { - if ( uv2ScaleMap.matrixAutoUpdate === true ) { + const frame = info.render.frame; - uv2ScaleMap.updateMatrix(); + // Check the last frame we updated the VideoTexture - } + if ( _videoTextures.get( texture ) !== frame ) { - uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + _videoTextures.set( texture, frame ); + texture.update(); } } - function refreshUniformsLine( uniforms, material ) { + function verifyColorSpace( texture, image ) { - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; + const encoding = texture.encoding; + const format = texture.format; + const type = texture.type; - } + if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image; - function refreshUniformsDash( uniforms, material ) { + if ( encoding !== LinearEncoding ) { - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + // sRGB - } + if ( encoding === sRGBEncoding ) { - function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + if ( isWebGL2 === false ) { - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * pixelRatio; - uniforms.scale.value = height * 0.5; + // in WebGL 1, try to use EXT_sRGB extension and unsized formats - if ( material.map ) { + if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) { - uniforms.map.value = material.map; + texture.format = _SRGBAFormat; - } + // it's not possible to generate mips in WebGL 1 with this extension - if ( material.alphaMap ) { + texture.minFilter = LinearFilter; + texture.generateMipmaps = false; - uniforms.alphaMap.value = material.alphaMap; + } else { - } + // slow fallback (CPU decode) - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map + image = ImageUtils.sRGBToLinear( image ); - let uvScaleMap; + } - if ( material.map ) { + } else { - uvScaleMap = material.map; + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format - } else if ( material.alphaMap ) { + if ( format !== RGBAFormat || type !== UnsignedByteType ) { - uvScaleMap = material.alphaMap; + console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); - } + } - if ( uvScaleMap !== undefined ) { + } - if ( uvScaleMap.matrixAutoUpdate === true ) { + } else { - uvScaleMap.updateMatrix(); + console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding ); } - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - } - } + return image; - function refreshUniformsSprites( uniforms, material ) { + } - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; - uniforms.rotation.value = material.rotation; + // - if ( material.map ) { + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; - uniforms.map.value = material.map; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; - } +} - if ( material.alphaMap ) { +function WebGLUtils( gl, extensions, capabilities ) { - uniforms.alphaMap.value = material.alphaMap; + const isWebGL2 = capabilities.isWebGL2; - } + function convert( p, encoding = null ) { - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map + let extension; - let uvScaleMap; + if ( p === UnsignedByteType ) return 5121; + if ( p === UnsignedShort4444Type ) return 32819; + if ( p === UnsignedShort5551Type ) return 32820; - if ( material.map ) { + if ( p === ByteType ) return 5120; + if ( p === ShortType ) return 5122; + if ( p === UnsignedShortType ) return 5123; + if ( p === IntType ) return 5124; + if ( p === UnsignedIntType ) return 5125; + if ( p === FloatType ) return 5126; - uvScaleMap = material.map; + if ( p === HalfFloatType ) { - } else if ( material.alphaMap ) { + if ( isWebGL2 ) return 5131; - uvScaleMap = material.alphaMap; + extension = extensions.get( 'OES_texture_half_float' ); - } + if ( extension !== null ) { - if ( uvScaleMap !== undefined ) { + return extension.HALF_FLOAT_OES; - if ( uvScaleMap.matrixAutoUpdate === true ) { + } else { - uvScaleMap.updateMatrix(); + return null; } - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - } - } + if ( p === AlphaFormat ) return 6406; + if ( p === RGBAFormat ) return 6408; + if ( p === LuminanceFormat ) return 6409; + if ( p === LuminanceAlphaFormat ) return 6410; + if ( p === DepthFormat ) return 6402; + if ( p === DepthStencilFormat ) return 34041; + if ( p === RedFormat ) return 6403; - function refreshUniformsLambert( uniforms, material ) { + // @deprecated since r137 - if ( material.emissiveMap ) { + if ( p === RGBFormat ) { - uniforms.emissiveMap.value = material.emissiveMap; + console.warn( 'THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228' ); + return 6408; } - } + // WebGL 1 sRGB fallback - function refreshUniformsPhong( uniforms, material ) { + if ( p === _SRGBAFormat ) { - uniforms.specular.value.copy( material.specular ); - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + extension = extensions.get( 'EXT_sRGB' ); - if ( material.emissiveMap ) { + if ( extension !== null ) { - uniforms.emissiveMap.value = material.emissiveMap; + return extension.SRGB_ALPHA_EXT; - } + } else { - if ( material.bumpMap ) { + return null; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + } } - if ( material.normalMap ) { + // WebGL2 formats. - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + if ( p === RedIntegerFormat ) return 36244; + if ( p === RGFormat ) return 33319; + if ( p === RGIntegerFormat ) return 33320; + if ( p === RGBAIntegerFormat ) return 36249; - } + // S3TC - if ( material.displacementMap ) { + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( encoding === sRGBEncoding ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); - } + if ( extension !== null ) { - function refreshUniformsToon( uniforms, material ) { + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - if ( material.gradientMap ) { + } else { - uniforms.gradientMap.value = material.gradientMap; + return null; - } + } - if ( material.emissiveMap ) { + } else { - uniforms.emissiveMap.value = material.emissiveMap; + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - } + if ( extension !== null ) { - if ( material.bumpMap ) { + 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; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + } else { - } + return null; - if ( material.normalMap ) { + } - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + } } - if ( material.displacementMap ) { + // PVRTC - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - } + if ( extension !== null ) { - function refreshUniformsStandard( uniforms, material ) { + 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; - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + } else { - if ( material.roughnessMap ) { + return null; - uniforms.roughnessMap.value = material.roughnessMap; + } } - if ( material.metalnessMap ) { + // ETC1 - uniforms.metalnessMap.value = material.metalnessMap; + if ( p === RGB_ETC1_Format ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - if ( material.emissiveMap ) { + if ( extension !== null ) { - uniforms.emissiveMap.value = material.emissiveMap; + return extension.COMPRESSED_RGB_ETC1_WEBGL; - } + } else { - if ( material.bumpMap ) { + return null; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + } } - if ( material.normalMap ) { + // ETC2 - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); - if ( material.displacementMap ) { + if ( extension !== null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + + } else { + + return null; + + } } - const envMap = properties.get( material ).envMap; + // ASTC - if ( envMap ) { + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } } - } + // BPTC + + if ( p === RGBA_BPTC_Format ) { - function refreshUniformsPhysical( uniforms, material ) { + extension = extensions.get( 'EXT_texture_compression_bptc' ); - refreshUniformsStandard( uniforms, material ); + if ( extension !== null ) { - uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common + if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; - uniforms.clearcoat.value = material.clearcoat; - uniforms.clearcoatRoughness.value = material.clearcoatRoughness; - if ( material.sheen ) uniforms.sheen.value.copy( material.sheen ); + } else { - if ( material.clearcoatMap ) { + return null; - uniforms.clearcoatMap.value = material.clearcoatMap; + } } - if ( material.clearcoatRoughnessMap ) { + // - uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + if ( p === UnsignedInt248Type ) { - } + if ( isWebGL2 ) return 34042; - if ( material.clearcoatNormalMap ) { + extension = extensions.get( 'WEBGL_depth_texture' ); + + if ( extension !== null ) { - uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); - uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + return extension.UNSIGNED_INT_24_8_WEBGL; - if ( material.side === BackSide ) { + } else { - uniforms.clearcoatNormalScale.value.negate(); + return null; } } - uniforms.transmission.value = material.transmission; + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) - if ( material.transmissionMap ) { + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; - uniforms.transmissionMap.value = material.transmissionMap; + } - } + return { convert: convert }; + +} + +class ArrayCamera extends PerspectiveCamera { + + constructor( array = [] ) { + + super(); + + this.isArrayCamera = true; + + this.cameras = array; } - function refreshUniformsMatcap( uniforms, material ) { +} - if ( material.matcap ) { +class Group extends Object3D { - uniforms.matcap.value = material.matcap; + constructor() { - } + super(); - if ( material.bumpMap ) { + this.isGroup = true; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + this.type = 'Group'; - } + } - if ( material.normalMap ) { +} - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); +const _moveEvent = { type: 'move' }; - } +class WebXRController { - if ( material.displacementMap ) { + constructor() { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._targetRay = null; + this._grip = null; + this._hand = null; + + } + + getHandSpace() { + + if ( this._hand === null ) { + + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; } + return this._hand; + } - function refreshUniformsDepth( uniforms, material ) { + getTargetRaySpace() { - if ( material.displacementMap ) { + if ( this._targetRay === null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); } + return this._targetRay; + } - function refreshUniformsDistance( uniforms, material ) { + getGripSpace() { - if ( material.displacementMap ) { + if ( this._grip === null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); } - uniforms.referencePosition.value.copy( material.referencePosition ); - uniforms.nearDistance.value = material.nearDistance; - uniforms.farDistance.value = material.farDistance; + return this._grip; } - function refreshUniformsNormal( uniforms, material ) { + dispatchEvent( event ) { - if ( material.bumpMap ) { + if ( this._targetRay !== null ) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + this._targetRay.dispatchEvent( event ); } - if ( material.normalMap ) { + if ( this._grip !== null ) { - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + this._grip.dispatchEvent( event ); } - if ( material.displacementMap ) { + if ( this._hand !== null ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + this._hand.dispatchEvent( event ); } - } - - return { - refreshFogUniforms: refreshFogUniforms, - refreshMaterialUniforms: refreshMaterialUniforms - }; + return this; -} + } -function createCanvasElement() { + disconnect( inputSource ) { - const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.style.display = 'block'; - return canvas; + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); -} + if ( this._targetRay !== null ) { -function WebGLRenderer( parameters ) { + this._targetRay.visible = false; - parameters = parameters || {}; + } - const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), - _context = parameters.context !== undefined ? parameters.context : null, + if ( this._grip !== 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, - _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', - _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; + this._grip.visible = false; - let currentRenderList = null; - let currentRenderState = null; + } - // render() can be called from within a callback triggered by another render. - // We track this so that the nested render call gets its list and state isolated from the parent render call. + if ( this._hand !== null ) { - const renderListStack = []; - const renderStateStack = []; + this._hand.visible = false; - // public properties + } - this.domElement = _canvas; + return this; - // Debug configuration container - this.debug = { + } - /** - * Enables error checking and reporting when shader programs are being compiled - * @type {boolean} - */ - checkShaderErrors: true - }; + update( inputSource, frame, referenceSpace ) { - // clearing + let inputPose = null; + let gripPose = null; + let handPose = null; - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; - // scene graph + if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { - this.sortObjects = true; + if ( hand && inputSource.hand ) { - // user-defined clipping + handPose = true; - this.clippingPlanes = []; - this.localClippingEnabled = false; + for ( const inputjoint of inputSource.hand.values() ) { - // physically based shading + // Update the joints groups with the XRJoint poses + const jointPose = frame.getJointPose( inputjoint, referenceSpace ); - this.gammaFactor = 2.0; // for backwards compatibility - this.outputEncoding = LinearEncoding; + if ( hand.joints[ inputjoint.jointName ] === undefined ) { - // physical lights + // The transform of this joint will be updated with the joint pose on each frame + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[ inputjoint.jointName ] = joint; + // ?? + hand.add( joint ); - this.physicallyCorrectLights = false; + } - // tone mapping + const joint = hand.joints[ inputjoint.jointName ]; - this.toneMapping = NoToneMapping; - this.toneMappingExposure = 1.0; + if ( jointPose !== null ) { - // morphs + joint.matrix.fromArray( jointPose.transform.matrix ); + joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); + joint.jointRadius = jointPose.radius; - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + } - // internal properties + joint.visible = jointPose !== null; - const _this = this; + } - let _isContextLost = false; + // Custom events - // internal state cache + // Check pinchz + const indexTip = hand.joints[ 'index-finger-tip' ]; + const thumbTip = hand.joints[ 'thumb-tip' ]; + const distance = indexTip.position.distanceTo( thumbTip.position ); - let _framebuffer = null; + const distanceToPinch = 0.02; + const threshold = 0.005; - let _currentActiveCubeFace = 0; - let _currentActiveMipmapLevel = 0; - let _currentRenderTarget = null; - let _currentFramebuffer = null; - let _currentMaterialId = - 1; + if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { - let _currentCamera = null; + hand.inputState.pinching = false; + this.dispatchEvent( { + type: 'pinchend', + handedness: inputSource.handedness, + target: this + } ); - const _currentViewport = new Vector4(); - const _currentScissor = new Vector4(); - let _currentScissorTest = null; + } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { - // + hand.inputState.pinching = true; + this.dispatchEvent( { + type: 'pinchstart', + handedness: inputSource.handedness, + target: this + } ); - let _width = _canvas.width; - let _height = _canvas.height; + } - let _pixelRatio = 1; - let _opaqueSort = null; - let _transparentSort = null; + } else { - const _viewport = new Vector4( 0, 0, _width, _height ); - const _scissor = new Vector4( 0, 0, _width, _height ); - let _scissorTest = false; + if ( grip !== null && inputSource.gripSpace ) { - // frustum + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); - const _frustum = new Frustum(); + if ( gripPose !== null ) { - // clipping + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); - let _clippingEnabled = false; - let _localClippingEnabled = false; + if ( gripPose.linearVelocity ) { - // camera matrices cache + grip.hasLinearVelocity = true; + grip.linearVelocity.copy( gripPose.linearVelocity ); - const _projScreenMatrix = new Matrix4(); + } else { - const _vector3 = new Vector3(); + grip.hasLinearVelocity = false; - const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + } - function getTargetPixelRatio() { + if ( gripPose.angularVelocity ) { - return _currentRenderTarget === null ? _pixelRatio : 1; + grip.hasAngularVelocity = true; + grip.angularVelocity.copy( gripPose.angularVelocity ); - } + } else { - // initialize + grip.hasAngularVelocity = false; - let _gl = _context; + } - function getContext( contextNames, contextAttributes ) { + } - for ( let i = 0; i < contextNames.length; i ++ ) { + } - const contextName = contextNames[ i ]; - const context = _canvas.getContext( contextName, contextAttributes ); - if ( context !== null ) return context; + } - } + if ( targetRay !== null ) { - return null; + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); - } + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { - try { + inputPose = gripPose; - const contextAttributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer, - powerPreference: _powerPreference, - failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat - }; + } - // event listeners must be registered before WebGL context is created, see #12753 + if ( inputPose !== null ) { - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); - if ( _gl === null ) { + if ( inputPose.linearVelocity ) { - const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); - if ( _this.isWebGL1Renderer === true ) { + } else { - contextNames.shift(); + targetRay.hasLinearVelocity = false; - } + } - _gl = getContext( contextNames, contextAttributes ); + if ( inputPose.angularVelocity ) { - if ( _gl === null ) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); - if ( getContext( contextNames ) ) { + } else { - throw new Error( 'Error creating WebGL context with your selected attributes.' ); + targetRay.hasAngularVelocity = false; - } else { + } - throw new Error( 'Error creating WebGL context.' ); + this.dispatchEvent( _moveEvent ); } } + } - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + if ( targetRay !== null ) { - if ( _gl.getShaderPrecisionFormat === undefined ) { + targetRay.visible = ( inputPose !== null ); - _gl.getShaderPrecisionFormat = function () { + } - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + if ( grip !== null ) { - }; + grip.visible = ( gripPose !== null ); } - } catch ( error ) { + if ( hand !== null ) { - console.error( 'THREE.WebGLRenderer: ' + error.message ); - throw error; + hand.visible = ( handPose !== null ); + + } + + return this; } - let extensions, capabilities, state, info; - let properties, textures, cubemaps, attributes, geometries, objects; - let programCache, materials, renderLists, renderStates, clipping; +} - let background, morphtargets, bufferRenderer, indexedBufferRenderer; +class DepthTexture extends Texture { - let utils, bindingStates; + constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { - function initGLContext() { + format = format !== undefined ? format : DepthFormat; - extensions = new WebGLExtensions( _gl ); + if ( format !== DepthFormat && format !== DepthStencilFormat ) { - capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); - extensions.init( capabilities ); + } - utils = new WebGLUtils( _gl, extensions, capabilities ); + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; - state = new WebGLState( _gl, extensions, capabilities ); - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - info = new WebGLInfo( _gl ); - properties = new WebGLProperties(); - textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); - cubemaps = new WebGLCubeMaps( _this ); - attributes = new WebGLAttributes( _gl, capabilities ); - bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); - geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); - objects = new WebGLObjects( _gl, geometries, attributes, info ); - morphtargets = new WebGLMorphtargets( _gl ); - clipping = new WebGLClipping( properties ); - programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping ); - materials = new WebGLMaterials( properties ); - renderLists = new WebGLRenderLists( properties ); - renderStates = new WebGLRenderStates( extensions, capabilities ); - background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha ); + this.isDepthTexture = true; - bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); - indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); + this.image = { width: width, height: height }; - info.programs = programCache.programs; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - _this.capabilities = capabilities; - _this.extensions = extensions; - _this.properties = properties; - _this.renderLists = renderLists; - _this.state = state; - _this.info = info; + this.flipY = false; + this.generateMipmaps = false; } - initGLContext(); - // xr +} - const xr = new WebXRManager( _this, _gl ); +class WebXRManager extends EventDispatcher { - this.xr = xr; + constructor( renderer, gl ) { - // shadow map + super(); - const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); + const scope = this; - this.shadowMap = shadowMap; + let session = null; + let framebufferScaleFactor = 1.0; - // API + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + let customReferenceSpace = null; - this.getContext = function () { + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; - return _gl; + const controllers = []; + const controllerInputSources = []; - }; + // - this.getContextAttributes = function () { + const cameraL = new PerspectiveCamera(); + cameraL.layers.enable( 1 ); + cameraL.viewport = new Vector4(); - return _gl.getContextAttributes(); + const cameraR = new PerspectiveCamera(); + cameraR.layers.enable( 2 ); + cameraR.viewport = new Vector4(); - }; + const cameras = [ cameraL, cameraR ]; - this.forceContextLoss = function () { + const cameraVR = new ArrayCamera(); + cameraVR.layers.enable( 1 ); + cameraVR.layers.enable( 2 ); - const extension = extensions.get( 'WEBGL_lose_context' ); - if ( extension ) extension.loseContext(); + let _currentDepthNear = null; + let _currentDepthFar = null; - }; + // - this.forceContextRestore = function () { + this.cameraAutoUpdate = true; + this.enabled = false; - const extension = extensions.get( 'WEBGL_lose_context' ); - if ( extension ) extension.restoreContext(); + this.isPresenting = false; - }; + this.getController = function ( index ) { - this.getPixelRatio = function () { + let controller = controllers[ index ]; - return _pixelRatio; + if ( controller === undefined ) { - }; + controller = new WebXRController(); + controllers[ index ] = controller; - this.setPixelRatio = function ( value ) { + } - if ( value === undefined ) return; + return controller.getTargetRaySpace(); - _pixelRatio = value; + }; - this.setSize( _width, _height, false ); + this.getControllerGrip = function ( index ) { - }; + let controller = controllers[ index ]; - this.getSize = function ( target ) { + if ( controller === undefined ) { - if ( target === undefined ) { + controller = new WebXRController(); + controllers[ index ] = controller; - console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' ); + } - target = new Vector2(); + return controller.getGripSpace(); - } + }; - return target.set( _width, _height ); + this.getHand = function ( index ) { - }; + let controller = controllers[ index ]; - this.setSize = function ( width, height, updateStyle ) { + if ( controller === undefined ) { - if ( xr.isPresenting ) { + controller = new WebXRController(); + controllers[ index ] = controller; - console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); - return; + } - } + return controller.getHandSpace(); - _width = width; - _height = height; + }; - _canvas.width = Math.floor( width * _pixelRatio ); - _canvas.height = Math.floor( height * _pixelRatio ); + // - if ( updateStyle !== false ) { + function onSessionEvent( event ) { - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); - } + if ( controllerIndex === - 1 ) { - this.setViewport( 0, 0, width, height ); + return; - }; + } - this.getDrawingBufferSize = function ( target ) { + const controller = controllers[ controllerIndex ]; - if ( target === undefined ) { + if ( controller !== undefined ) { - console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' ); + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); - target = new Vector2(); + } } - return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); - - }; - - this.setDrawingBufferSize = function ( width, height, pixelRatio ) { - - _width = width; - _height = height; - - _pixelRatio = pixelRatio; - - _canvas.width = Math.floor( width * pixelRatio ); - _canvas.height = Math.floor( height * pixelRatio ); - - this.setViewport( 0, 0, width, height ); - - }; + function onSessionEnd() { - this.getCurrentViewport = function ( target ) { + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); - if ( target === undefined ) { + for ( let i = 0; i < controllers.length; i ++ ) { - console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' ); + const inputSource = controllerInputSources[ i ]; - target = new Vector4(); + if ( inputSource === null ) continue; - } + controllerInputSources[ i ] = null; - return target.copy( _currentViewport ); + controllers[ i ].disconnect( inputSource ); - }; + } - this.getViewport = function ( target ) { + _currentDepthNear = null; + _currentDepthFar = null; - return target.copy( _viewport ); + // restore framebuffer/rendering state - }; + renderer.setRenderTarget( initialRenderTarget ); - this.setViewport = function ( x, y, width, height ) { + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; - if ( x.isVector4 ) { + // - _viewport.set( x.x, x.y, x.z, x.w ); + animation.stop(); - } else { + scope.isPresenting = false; - _viewport.set( x, y, width, height ); + scope.dispatchEvent( { type: 'sessionend' } ); } - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); - - }; - - this.getScissor = function ( target ) { - - return target.copy( _scissor ); - - }; + this.setFramebufferScaleFactor = function ( value ) { - this.setScissor = function ( x, y, width, height ) { + framebufferScaleFactor = value; - if ( x.isVector4 ) { + if ( scope.isPresenting === true ) { - _scissor.set( x.x, x.y, x.z, x.w ); + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); - } else { + } - _scissor.set( x, y, width, height ); + }; - } + this.setReferenceSpaceType = function ( value ) { - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + referenceSpaceType = value; - }; + if ( scope.isPresenting === true ) { - this.getScissorTest = function () { + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); - return _scissorTest; + } - }; + }; - this.setScissorTest = function ( boolean ) { + this.getReferenceSpace = function () { - state.setScissorTest( _scissorTest = boolean ); + return customReferenceSpace || referenceSpace; - }; + }; - this.setOpaqueSort = function ( method ) { + this.setReferenceSpace = function ( space ) { - _opaqueSort = method; + customReferenceSpace = space; - }; + }; - this.setTransparentSort = function ( method ) { + this.getBaseLayer = function () { - _transparentSort = method; + return glProjLayer !== null ? glProjLayer : glBaseLayer; - }; + }; - // Clearing + this.getBinding = function () { - this.getClearColor = function ( target ) { + return glBinding; - if ( target === undefined ) { + }; - console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' ); + this.getFrame = function () { - target = new Color(); + return xrFrame; - } + }; - return target.copy( background.getClearColor() ); + this.getSession = function () { - }; + return session; - this.setClearColor = function () { + }; - background.setClearColor.apply( background, arguments ); + this.setSession = async function ( value ) { - }; + session = value; - this.getClearAlpha = function () { + if ( session !== null ) { - return background.getClearAlpha(); + initialRenderTarget = renderer.getRenderTarget(); - }; + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); - this.setClearAlpha = function () { + if ( attributes.xrCompatible !== true ) { - background.setClearAlpha.apply( background, arguments ); + await gl.makeXRCompatible(); - }; + } - this.clear = function ( color, depth, stencil ) { + if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) { - let bits = 0; + const layerInit = { + antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true, + alpha: attributes.alpha, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; - if ( color === undefined || color ) bits |= 16384; - if ( depth === undefined || depth ) bits |= 256; - if ( stencil === undefined || stencil ) bits |= 1024; + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); - _gl.clear( bits ); + session.updateRenderState( { baseLayer: glBaseLayer } ); - }; + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + encoding: renderer.outputEncoding, + stencilBuffer: attributes.stencil + } + ); - this.clearColor = function () { + } else { - this.clear( true, false, false ); + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; - }; + if ( attributes.depth ) { - this.clearDepth = function () { + glDepthFormat = attributes.stencil ? 35056 : 33190; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; - this.clear( false, true, false ); + } - }; + const projectionlayerInit = { + colorFormat: 32856, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; - this.clearStencil = function () { + glBinding = new XRWebGLBinding( session, gl ); - this.clear( false, false, true ); + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); - }; + session.updateRenderState( { layers: [ glProjLayer ] } ); - // + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + encoding: renderer.outputEncoding, + samples: attributes.antialias ? 4 : 0 + } ); - this.dispose = function () { + const renderTargetProperties = renderer.properties.get( newRenderTarget ); + renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + } - renderLists.dispose(); - renderStates.dispose(); - properties.dispose(); - cubemaps.dispose(); - objects.dispose(); - bindingStates.dispose(); + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 - xr.dispose(); + // Set foveation to maximum. + this.setFoveation( 1.0 ); - animation.stop(); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); - }; + animation.setContext( session ); + animation.start(); - // Events + scope.isPresenting = true; - function onContextLost( event ) { + scope.dispatchEvent( { type: 'sessionstart' } ); - event.preventDefault(); + } - console.log( 'THREE.WebGLRenderer: Context Lost.' ); + }; - _isContextLost = true; + function onInputSourcesChange( event ) { - } + // Notify disconnected - function onContextRestore( /* event */ ) { + for ( let i = 0; i < event.removed.length; i ++ ) { - console.log( 'THREE.WebGLRenderer: Context Restored.' ); + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); - _isContextLost = false; + if ( index >= 0 ) { - initGLContext(); + controllerInputSources[ index ] = null; + controllers[ index ].dispatchEvent( { type: 'disconnected', data: inputSource } ); - } + } - function onMaterialDispose( event ) { + } - const material = event.target; + // Notify connected - material.removeEventListener( 'dispose', onMaterialDispose ); + for ( let i = 0; i < event.added.length; i ++ ) { - deallocateMaterial( material ); + const inputSource = event.added[ i ]; - } + let controllerIndex = controllerInputSources.indexOf( inputSource ); - // Buffer deallocation + if ( controllerIndex === - 1 ) { - function deallocateMaterial( material ) { + // Assign input source a controller that currently has no input source - releaseMaterialProgramReference( material ); + for ( let i = 0; i < controllers.length; i ++ ) { - properties.remove( material ); + if ( i >= controllerInputSources.length ) { - } + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + } else if ( controllerInputSources[ i ] === null ) { - function releaseMaterialProgramReference( material ) { + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; - const programInfo = properties.get( material ).program; + } - if ( programInfo !== undefined ) { + } - programCache.releaseProgram( programInfo ); + // If all controllers do currently receive input we ignore new ones - } + if ( controllerIndex === - 1 ) break; - } + } - // Buffer rendering + const controller = controllers[ controllerIndex ]; - function renderObjectImmediate( object, program ) { + if ( controller ) { - object.render( function ( object ) { + controller.dispatchEvent( { type: 'connected', data: inputSource } ); - _this.renderBufferImmediate( object, program ); + } - } ); + } - } + } - this.renderBufferImmediate = function ( object, program ) { + // - bindingStates.initAttributes(); + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); - const buffers = properties.get( object ); + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { - 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(); + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); - const programAttributes = program.getAttributes(); + const ipd = cameraLPos.distanceTo( cameraRPos ); - if ( object.hasPositions ) { + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; - _gl.bindBuffer( 34962, buffers.position ); - _gl.bufferData( 34962, object.positionArray, 35048 ); + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; - bindingStates.enableAttribute( programAttributes.position ); - _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 ); + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; - } + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; - if ( object.hasNormals ) { + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); - _gl.bindBuffer( 34962, buffers.normal ); - _gl.bufferData( 34962, object.normalArray, 35048 ); + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; - bindingStates.enableAttribute( programAttributes.normal ); - _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 ); + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); } - if ( object.hasUvs ) { + function updateCamera( camera, parent ) { - _gl.bindBuffer( 34962, buffers.uv ); - _gl.bufferData( 34962, object.uvArray, 35048 ); + if ( parent === null ) { - bindingStates.enableAttribute( programAttributes.uv ); - _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 ); + camera.matrixWorld.copy( camera.matrix ); - } + } else { - if ( object.hasColors ) { + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); - _gl.bindBuffer( 34962, buffers.color ); - _gl.bufferData( 34962, object.colorArray, 35048 ); + } - bindingStates.enableAttribute( programAttributes.color ); - _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); } - bindingStates.disableUnusedAttributes(); + this.updateCamera = function ( camera ) { - _gl.drawArrays( 4, 0, object.count ); + if ( session === null ) return; - object.count = 0; + cameraVR.near = cameraR.near = cameraL.near = camera.near; + cameraVR.far = cameraR.far = cameraL.far = camera.far; - }; + if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { - this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + // Note that the new renderState won't apply until the next frame. See #18320 - if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + session.updateRenderState( { + depthNear: cameraVR.near, + depthFar: cameraVR.far + } ); - const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + _currentDepthNear = cameraVR.near; + _currentDepthFar = cameraVR.far; - const program = setProgram( camera, scene, material, object ); + } - state.setMaterial( material, frontFaceCW ); + const parent = camera.parent; + const cameras = cameraVR.cameras; - // + updateCamera( cameraVR, parent ); - let index = geometry.index; - const position = geometry.attributes.position; + for ( let i = 0; i < cameras.length; i ++ ) { - // + updateCamera( cameras[ i ], parent ); - if ( index === null ) { + } - if ( position === undefined || position.count === 0 ) return; + cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale ); - } else if ( index.count === 0 ) { + // update user camera and its children - return; + camera.matrix.copy( cameraVR.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); - } + const children = camera.children; - // + for ( let i = 0, l = children.length; i < l; i ++ ) { - let rangeFactor = 1; + children[ i ].updateMatrixWorld( true ); - if ( material.wireframe === true ) { + } - index = geometries.getWireframeAttribute( geometry ); - rangeFactor = 2; + // update projection matrix for proper view frustum culling - } + if ( cameras.length === 2 ) { - if ( material.morphTargets || material.morphNormals ) { + setProjectionFromUnion( cameraVR, cameraL, cameraR ); - morphtargets.update( object, geometry, material, program ); + } else { - } + // assume single camera setup (AR) - bindingStates.setup( object, material, program, geometry, index ); + cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); - let attribute; - let renderer = bufferRenderer; + } - if ( index !== null ) { + }; - attribute = attributes.get( index ); + this.getCamera = function () { - renderer = indexedBufferRenderer; - renderer.setIndex( attribute ); + return cameraVR; - } + }; - // + this.getFoveation = function () { - const dataCount = ( index !== null ) ? index.count : position.count; + if ( glProjLayer !== null ) { - const rangeStart = geometry.drawRange.start * rangeFactor; - const rangeCount = geometry.drawRange.count * rangeFactor; + return glProjLayer.fixedFoveation; - const groupStart = group !== null ? group.start * rangeFactor : 0; - const groupCount = group !== null ? group.count * rangeFactor : Infinity; + } - const drawStart = Math.max( rangeStart, groupStart ); - const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + if ( glBaseLayer !== null ) { - const drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + return glBaseLayer.fixedFoveation; - if ( drawCount === 0 ) return; + } - // + return undefined; - if ( object.isMesh ) { + }; - if ( material.wireframe === true ) { + this.setFoveation = function ( foveation ) { - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( 1 ); + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution - } else { + if ( glProjLayer !== null ) { - renderer.setMode( 4 ); + glProjLayer.fixedFoveation = foveation; } - } else if ( object.isLine ) { - - let lineWidth = material.linewidth; - - if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + glBaseLayer.fixedFoveation = foveation; - if ( object.isLineSegments ) { + } - renderer.setMode( 1 ); + }; - } else if ( object.isLineLoop ) { + // Animation Loop - renderer.setMode( 2 ); + let onAnimationFrameCallback = null; - } else { + function onAnimationFrame( time, frame ) { - renderer.setMode( 3 ); + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; - } + if ( pose !== null ) { - } else if ( object.isPoints ) { + const views = pose.views; - renderer.setMode( 0 ); + if ( glBaseLayer !== null ) { - } else if ( object.isSprite ) { + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); - renderer.setMode( 4 ); + } - } + let cameraVRNeedsUpdate = false; - if ( object.isInstancedMesh ) { + // check if it's necessary to rebuild cameraVR's camera list - renderer.renderInstances( drawStart, drawCount, object.count ); + if ( views.length !== cameraVR.cameras.length ) { - } else if ( geometry.isInstancedBufferGeometry ) { + cameraVR.cameras.length = 0; + cameraVRNeedsUpdate = true; - const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount ); + } - renderer.renderInstances( drawStart, drawCount, instanceCount ); + for ( let i = 0; i < views.length; i ++ ) { - } else { + const view = views[ i ]; - renderer.render( drawStart, drawCount ); + let viewport = null; - } + if ( glBaseLayer !== null ) { - }; + viewport = glBaseLayer.getViewport( view ); - // Compile + } else { - this.compile = function ( scene, camera ) { + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; - currentRenderState = renderStates.get( scene ); - currentRenderState.init(); + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { - scene.traverseVisible( function ( object ) { + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture ); - if ( object.isLight && object.layers.test( camera.layers ) ) { + renderer.setRenderTarget( newRenderTarget ); - currentRenderState.pushLight( object ); + } - if ( object.castShadow ) { + } - currentRenderState.pushShadow( object ); + let camera = cameras[ i ]; - } + if ( camera === undefined ) { - } + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; - } ); + } - currentRenderState.setupLights(); + camera.matrix.fromArray( view.transform.matrix ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); - const compiled = new WeakMap(); + if ( i === 0 ) { - scene.traverse( function ( object ) { + cameraVR.matrix.copy( camera.matrix ); - const material = object.material; + } - if ( material ) { + if ( cameraVRNeedsUpdate === true ) { - if ( Array.isArray( material ) ) { + cameraVR.cameras.push( camera ); - for ( let i = 0; i < material.length; i ++ ) { + } - const material2 = material[ i ]; + } - if ( compiled.has( material2 ) === false ) { + } - initMaterial( material2, scene, object ); - compiled.set( material2 ); + // - } + for ( let i = 0; i < controllers.length; i ++ ) { - } + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; - } else if ( compiled.has( material ) === false ) { + if ( inputSource !== null && controller !== undefined ) { - initMaterial( material, scene, object ); - compiled.set( material ); + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); } } - } ); + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); - }; + xrFrame = null; - // Animation Loop + } - let onAnimationFrameCallback = null; + const animation = new WebGLAnimation(); - function onAnimationFrame( time ) { + animation.setAnimationLoop( onAnimationFrame ); - if ( xr.isPresenting ) return; - if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + this.setAnimationLoop = function ( callback ) { - } + onAnimationFrameCallback = callback; - const animation = new WebGLAnimation(); - animation.setAnimationLoop( onAnimationFrame ); + }; - if ( typeof window !== 'undefined' ) animation.setContext( window ); + this.dispose = function () {}; - this.setAnimationLoop = function ( callback ) { + } - onAnimationFrameCallback = callback; - xr.setAnimationLoop( callback ); +} - ( callback === null ) ? animation.stop() : animation.start(); +function WebGLMaterials( renderer, properties ) { - }; + function refreshFogUniforms( uniforms, fog ) { - // Rendering + uniforms.fogColor.value.copy( fog.color ); - this.render = function ( scene, camera ) { + if ( fog.isFog ) { - let renderTarget, forceClear; + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - if ( arguments[ 2 ] !== undefined ) { + } else if ( fog.isFogExp2 ) { - console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' ); - renderTarget = arguments[ 2 ]; + uniforms.fogDensity.value = fog.density; } - if ( arguments[ 3 ] !== undefined ) { - - console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' ); - forceClear = arguments[ 3 ]; - - } + } - if ( camera !== undefined && camera.isCamera !== true ) { + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + if ( material.isMeshBasicMaterial ) { - } + refreshUniformsCommon( uniforms, material ); - if ( _isContextLost === true ) return; + } else if ( material.isMeshLambertMaterial ) { - // reset caching for this frame + refreshUniformsCommon( uniforms, material ); - bindingStates.resetDefaultState(); - _currentMaterialId = - 1; - _currentCamera = null; + } else if ( material.isMeshToonMaterial ) { - // update scene graph + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + } else if ( material.isMeshPhongMaterial ) { - // update camera matrices and frustum + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); - if ( camera.parent === null ) camera.updateMatrixWorld(); + } else if ( material.isMeshStandardMaterial ) { - if ( xr.enabled === true && xr.isPresenting === true ) { + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); - camera = xr.getCamera( camera ); + if ( material.isMeshPhysicalMaterial ) { - } + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); - // - if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget ); + } - currentRenderState = renderStates.get( scene, renderStateStack.length ); - currentRenderState.init(); + } else if ( material.isMeshMatcapMaterial ) { - renderStateStack.push( currentRenderState ); + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromProjectionMatrix( _projScreenMatrix ); + } else if ( material.isMeshDepthMaterial ) { - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + refreshUniformsCommon( uniforms, material ); - currentRenderList = renderLists.get( scene, renderListStack.length ); - currentRenderList.init(); + } else if ( material.isMeshDistanceMaterial ) { - renderListStack.push( currentRenderList ); + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); - projectObject( scene, camera, 0, _this.sortObjects ); + } else if ( material.isMeshNormalMaterial ) { - currentRenderList.finish(); + refreshUniformsCommon( uniforms, material ); - if ( _this.sortObjects === true ) { + } else if ( material.isLineBasicMaterial ) { - currentRenderList.sort( _opaqueSort, _transparentSort ); + refreshUniformsLine( uniforms, material ); - } + if ( material.isLineDashedMaterial ) { - // + refreshUniformsDash( uniforms, material ); - if ( _clippingEnabled === true ) clipping.beginShadows(); + } - const shadowsArray = currentRenderState.state.shadowsArray; + } else if ( material.isPointsMaterial ) { - shadowMap.render( shadowsArray, scene, camera ); + refreshUniformsPoints( uniforms, material, pixelRatio, height ); - currentRenderState.setupLights(); - currentRenderState.setupLightsView( camera ); + } else if ( material.isSpriteMaterial ) { - if ( _clippingEnabled === true ) clipping.endShadows(); + refreshUniformsSprites( uniforms, material ); - // + } else if ( material.isShadowMaterial ) { - if ( this.info.autoReset === true ) this.info.reset(); + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; - if ( renderTarget !== undefined ) { + } else if ( material.isShaderMaterial ) { - this.setRenderTarget( renderTarget ); + material.uniformsNeedUpdate = false; // #15581 } - // + } + + function refreshUniformsCommon( uniforms, material ) { - background.render( currentRenderList, scene, camera, forceClear ); + uniforms.opacity.value = material.opacity; - // render scene + if ( material.color ) { - const opaqueObjects = currentRenderList.opaque; - const transparentObjects = currentRenderList.transparent; + uniforms.diffuse.value.copy( material.color ); - if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); - if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + } - // + if ( material.emissive ) { - if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - // + } - if ( _currentRenderTarget !== null ) { + if ( material.map ) { - // Generate mipmap if we're using any kind of mipmap filtering + uniforms.map.value = material.map; - textures.updateRenderTargetMipmap( _currentRenderTarget ); + } - // resolve multisample renderbuffers to a single-sample texture if necessary + if ( material.alphaMap ) { - textures.updateMultisampleRenderTarget( _currentRenderTarget ); + uniforms.alphaMap.value = material.alphaMap; } - // Ensure depth buffer writing is enabled so it can be cleared on next render + if ( material.bumpMap ) { - state.buffers.depth.setTest( true ); - state.buffers.depth.setMask( true ); - state.buffers.color.setMask( true ); + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; - state.setPolygonOffset( false ); + } - // _gl.finish(); + if ( material.displacementMap ) { - renderStateStack.pop(); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - if ( renderStateStack.length > 0 ) { + } - currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + if ( material.emissiveMap ) { - } else { + uniforms.emissiveMap.value = material.emissiveMap; - currentRenderState = null; + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); } - renderListStack.pop(); + if ( material.specularMap ) { - if ( renderListStack.length > 0 ) { + uniforms.specularMap.value = material.specularMap; - currentRenderList = renderListStack[ renderListStack.length - 1 ]; + } - } else { + if ( material.alphaTest > 0 ) { - currentRenderList = null; + uniforms.alphaTest.value = material.alphaTest; } - }; + const envMap = properties.get( material ).envMap; - function projectObject( object, camera, groupOrder, sortObjects ) { + if ( envMap ) { - if ( object.visible === false ) return; + uniforms.envMap.value = envMap; - const visible = object.layers.test( camera.layers ); + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; - if ( visible ) { + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; - if ( object.isGroup ) { + } - groupOrder = object.renderOrder; + if ( material.lightMap ) { - } else if ( object.isLOD ) { + uniforms.lightMap.value = material.lightMap; - if ( object.autoUpdate === true ) object.update( camera ); + // artist-friendly light intensity scaling factor + const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1; - } else if ( object.isLight ) { + uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; - currentRenderState.pushLight( object ); + } - if ( object.castShadow ) { + if ( material.aoMap ) { - currentRenderState.pushShadow( object ); + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; - } + } - } else if ( object.isSprite ) { + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. displacementMap map + // 4. normal map + // 5. bump map + // 6. roughnessMap map + // 7. metalnessMap map + // 8. alphaMap map + // 9. emissiveMap map + // 10. clearcoat map + // 11. clearcoat normal map + // 12. clearcoat roughnessMap map + // 13. iridescence map + // 14. iridescence thickness map + // 15. specular intensity map + // 16. specular tint map + // 17. transmission map + // 18. thickness map - if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + let uvScaleMap; - if ( sortObjects ) { + if ( material.map ) { - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + uvScaleMap = material.map; - } + } else if ( material.specularMap ) { - const geometry = objects.update( object ); - const material = object.material; + uvScaleMap = material.specularMap; - if ( material.visible ) { + } else if ( material.displacementMap ) { - currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + uvScaleMap = material.displacementMap; - } + } else if ( material.normalMap ) { - } + uvScaleMap = material.normalMap; + + } else if ( material.bumpMap ) { + + uvScaleMap = material.bumpMap; - } else if ( object.isImmediateRenderObject ) { + } else if ( material.roughnessMap ) { - if ( sortObjects ) { + uvScaleMap = material.roughnessMap; - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + } else if ( material.metalnessMap ) { - } + uvScaleMap = material.metalnessMap; - currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null ); + } else if ( material.alphaMap ) { - } else if ( object.isMesh || object.isLine || object.isPoints ) { + uvScaleMap = material.alphaMap; - if ( object.isSkinnedMesh ) { + } else if ( material.emissiveMap ) { - // update skeleton only once in a frame + uvScaleMap = material.emissiveMap; - if ( object.skeleton.frame !== info.render.frame ) { + } else if ( material.clearcoatMap ) { - object.skeleton.update(); - object.skeleton.frame = info.render.frame; + uvScaleMap = material.clearcoatMap; - } + } else if ( material.clearcoatNormalMap ) { - } + uvScaleMap = material.clearcoatNormalMap; - if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + } else if ( material.clearcoatRoughnessMap ) { - if ( sortObjects ) { + uvScaleMap = material.clearcoatRoughnessMap; - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + } else if ( material.iridescenceMap ) { - } + uvScaleMap = material.iridescenceMap; - const geometry = objects.update( object ); - const material = object.material; + } else if ( material.iridescenceThicknessMap ) { - if ( Array.isArray( material ) ) { + uvScaleMap = material.iridescenceThicknessMap; - const groups = geometry.groups; + } else if ( material.specularIntensityMap ) { - for ( let i = 0, l = groups.length; i < l; i ++ ) { + uvScaleMap = material.specularIntensityMap; - const group = groups[ i ]; - const groupMaterial = material[ group.materialIndex ]; + } else if ( material.specularColorMap ) { - if ( groupMaterial && groupMaterial.visible ) { + uvScaleMap = material.specularColorMap; - currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); + } else if ( material.transmissionMap ) { - } + uvScaleMap = material.transmissionMap; - } + } else if ( material.thicknessMap ) { - } else if ( material.visible ) { + uvScaleMap = material.thicknessMap; - currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + } else if ( material.sheenColorMap ) { - } + uvScaleMap = material.sheenColorMap; - } + } else if ( material.sheenRoughnessMap ) { - } + uvScaleMap = material.sheenRoughnessMap; } - const children = object.children; + if ( uvScaleMap !== undefined ) { - for ( let i = 0, l = children.length; i < l; i ++ ) { + // backwards compatibility + if ( uvScaleMap.isWebGLRenderTarget ) { - projectObject( children[ i ], camera, groupOrder, sortObjects ); + uvScaleMap = uvScaleMap.texture; - } + } - } + if ( uvScaleMap.matrixAutoUpdate === true ) { - function renderObjects( renderList, scene, camera ) { + uvScaleMap.updateMatrix(); - const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + } - for ( let i = 0, l = renderList.length; i < l; i ++ ) { + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - const renderItem = renderList[ i ]; + } - const object = renderItem.object; - const geometry = renderItem.geometry; - const material = overrideMaterial === null ? renderItem.material : overrideMaterial; - const group = renderItem.group; + // uv repeat and offset setting priorities for uv2 + // 1. ao map + // 2. light map - if ( camera.isArrayCamera ) { + let uv2ScaleMap; - const cameras = camera.cameras; + if ( material.aoMap ) { - for ( let j = 0, jl = cameras.length; j < jl; j ++ ) { + uv2ScaleMap = material.aoMap; - const camera2 = cameras[ j ]; + } else if ( material.lightMap ) { - if ( object.layers.test( camera2.layers ) ) { + uv2ScaleMap = material.lightMap; - state.viewport( _currentViewport.copy( camera2.viewport ) ); + } - currentRenderState.setupLightsView( camera2 ); + if ( uv2ScaleMap !== undefined ) { - renderObject( object, scene, camera2, geometry, material, group ); + // backwards compatibility + if ( uv2ScaleMap.isWebGLRenderTarget ) { - } + uv2ScaleMap = uv2ScaleMap.texture; - } + } - } else { + if ( uv2ScaleMap.matrixAutoUpdate === true ) { - renderObject( object, scene, camera, geometry, material, group ); + uv2ScaleMap.updateMatrix(); } + uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + } } - function renderObject( object, scene, camera, geometry, material, group ) { + function refreshUniformsLine( uniforms, material ) { - object.onBeforeRender( _this, scene, camera, geometry, material, group ); + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + } - if ( object.isImmediateRenderObject ) { + function refreshUniformsDash( uniforms, material ) { - const program = setProgram( camera, scene, material, object ); + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - state.setMaterial( material ); + } - bindingStates.reset(); + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { - renderObjectImmediate( object, program ); + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; - } else { + if ( material.map ) { - _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + uniforms.map.value = material.map; } - object.onAfterRender( _this, scene, camera, geometry, material, group ); + if ( material.alphaMap ) { - } + uniforms.alphaMap.value = material.alphaMap; - function initMaterial( material, scene, object ) { + } - if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + if ( material.alphaTest > 0 ) { - const materialProperties = properties.get( material ); + uniforms.alphaTest.value = material.alphaTest; - const lights = currentRenderState.state.lights; - const shadowsArray = currentRenderState.state.shadowsArray; + } - const lightsStateVersion = lights.state.version; + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map - const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); - const programCacheKey = programCache.getProgramCacheKey( parameters ); + let uvScaleMap; - let program = materialProperties.program; - let programChange = true; + if ( material.map ) { - // always update environment and fog - changing these trigger an initMaterial call, but it's possible that the program doesn't change + uvScaleMap = material.map; - materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; - materialProperties.fog = scene.fog; - materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment ); + } else if ( material.alphaMap ) { - if ( program === undefined ) { + uvScaleMap = material.alphaMap; - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + } - } else if ( program.cacheKey !== programCacheKey ) { + if ( uvScaleMap !== undefined ) { - // changed glsl or parameters - releaseMaterialProgramReference( material ); + if ( uvScaleMap.matrixAutoUpdate === true ) { - } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) { + uvScaleMap.updateMatrix(); - programChange = false; + } - } else if ( parameters.shaderID !== undefined ) { + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - // same glsl and uniform list - return; + } - } else { + } - // only rebuild uniform list - programChange = false; + function refreshUniformsSprites( uniforms, material ) { - } + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; - if ( programChange ) { + if ( material.map ) { - parameters.uniforms = programCache.getUniforms( material ); + uniforms.map.value = material.map; - material.onBeforeCompile( parameters, _this ); + } - program = programCache.acquireProgram( parameters, programCacheKey ); + if ( material.alphaMap ) { - materialProperties.program = program; - materialProperties.uniforms = parameters.uniforms; - materialProperties.outputEncoding = parameters.outputEncoding; + uniforms.alphaMap.value = material.alphaMap; } - const uniforms = materialProperties.uniforms; - - if ( ! material.isShaderMaterial && - ! material.isRawShaderMaterial || - material.clipping === true ) { + if ( material.alphaTest > 0 ) { - materialProperties.numClippingPlanes = clipping.numPlanes; - materialProperties.numIntersection = clipping.numIntersection; - uniforms.clippingPlanes = clipping.uniform; + uniforms.alphaTest.value = material.alphaTest; } - // store the light setup it was created for + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map - materialProperties.needsLights = materialNeedsLights( material ); - materialProperties.lightsStateVersion = lightsStateVersion; + let uvScaleMap; - if ( materialProperties.needsLights ) { + if ( material.map ) { - // wire up the material to this renderer's lighting state + uvScaleMap = material.map; - uniforms.ambientLightColor.value = lights.state.ambient; - uniforms.lightProbe.value = lights.state.probe; - uniforms.directionalLights.value = lights.state.directional; - uniforms.directionalLightShadows.value = lights.state.directionalShadow; - uniforms.spotLights.value = lights.state.spot; - uniforms.spotLightShadows.value = lights.state.spotShadow; - uniforms.rectAreaLights.value = lights.state.rectArea; - uniforms.ltc_1.value = lights.state.rectAreaLTC1; - uniforms.ltc_2.value = lights.state.rectAreaLTC2; - uniforms.pointLights.value = lights.state.point; - uniforms.pointLightShadows.value = lights.state.pointShadow; - uniforms.hemisphereLights.value = lights.state.hemi; + } else if ( material.alphaMap ) { - uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; - uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; - uniforms.spotShadowMap.value = lights.state.spotShadowMap; - uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix; - uniforms.pointShadowMap.value = lights.state.pointShadowMap; - uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; - // TODO (abelnation): add area lights shadow info to uniforms + uvScaleMap = material.alphaMap; } - const progUniforms = materialProperties.program.getUniforms(); - const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + if ( uvScaleMap !== undefined ) { - materialProperties.uniformsList = uniformsList; + if ( uvScaleMap.matrixAutoUpdate === true ) { - } + uvScaleMap.updateMatrix(); - function setProgram( camera, scene, material, object ) { + } - if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - textures.resetTextureUnits(); + } - const fog = scene.fog; - const environment = material.isMeshStandardMaterial ? scene.environment : null; - const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding; - const envMap = cubemaps.get( material.envMap || environment ); + } - const materialProperties = properties.get( material ); - const lights = currentRenderState.state.lights; + function refreshUniformsPhong( uniforms, material ) { - if ( _clippingEnabled === true ) { + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - if ( _localClippingEnabled === true || camera !== _currentCamera ) { + } - const useCache = - camera === _currentCamera && - material.id === _currentMaterialId; + function refreshUniformsToon( uniforms, material ) { - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - clipping.setState( material, camera, useCache ); + if ( material.gradientMap ) { - } + uniforms.gradientMap.value = material.gradientMap; } - if ( material.version === materialProperties.__version ) { + } - if ( material.fog && materialProperties.fog !== fog ) { + function refreshUniformsStandard( uniforms, material ) { - initMaterial( material, scene, object ); + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; - } else if ( materialProperties.environment !== environment ) { + if ( material.roughnessMap ) { - initMaterial( material, scene, object ); + uniforms.roughnessMap.value = material.roughnessMap; - } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + } - initMaterial( material, scene, object ); + if ( material.metalnessMap ) { - } else if ( materialProperties.numClippingPlanes !== undefined && - ( materialProperties.numClippingPlanes !== clipping.numPlanes || - materialProperties.numIntersection !== clipping.numIntersection ) ) { + uniforms.metalnessMap.value = material.metalnessMap; - initMaterial( material, scene, object ); + } - } else if ( materialProperties.outputEncoding !== encoding ) { + const envMap = properties.get( material ).envMap; - initMaterial( material, scene, object ); + if ( envMap ) { - } else if ( materialProperties.envMap !== envMap ) { + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - initMaterial( material, scene, object ); + } - } + } - } else { + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { - initMaterial( material, scene, object ); - materialProperties.__version = material.version; + uniforms.ior.value = material.ior; // also part of uniforms common - } + if ( material.sheen > 0 ) { - let refreshProgram = false; - let refreshMaterial = false; - let refreshLights = false; + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); - const program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.uniforms; + uniforms.sheenRoughness.value = material.sheenRoughness; - if ( state.useProgram( program.program ) ) { + if ( material.sheenColorMap ) { - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + uniforms.sheenColorMap.value = material.sheenColorMap; - } + } - if ( material.id !== _currentMaterialId ) { + if ( material.sheenRoughnessMap ) { - _currentMaterialId = material.id; + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; - refreshMaterial = true; + } } - if ( refreshProgram || _currentCamera !== camera ) { + if ( material.clearcoat > 0 ) { - p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; - if ( capabilities.logarithmicDepthBuffer ) { + if ( material.clearcoatMap ) { - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + uniforms.clearcoatMap.value = material.clearcoatMap; } - if ( _currentCamera !== camera ) { - - _currentCamera = camera; - - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + if ( material.clearcoatRoughnessMap ) { - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; } - // load material specific uniforms - // (shader material also gets them for the sake of genericity) - - if ( material.isShaderMaterial || - material.isMeshPhongMaterial || - material.isMeshToonMaterial || - material.isMeshStandardMaterial || - material.envMap ) { + if ( material.clearcoatNormalMap ) { - const uCamPos = p_uniforms.map.cameraPosition; + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; - if ( uCamPos !== undefined ) { + if ( material.side === BackSide ) { - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + uniforms.clearcoatNormalScale.value.negate(); } } - if ( material.isMeshPhongMaterial || - material.isMeshToonMaterial || - material.isMeshLambertMaterial || - material.isMeshBasicMaterial || - material.isMeshStandardMaterial || - material.isShaderMaterial ) { + } - p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + if ( material.iridescence > 0 ) { - } + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; - if ( material.isMeshPhongMaterial || - material.isMeshToonMaterial || - material.isMeshLambertMaterial || - material.isMeshBasicMaterial || - material.isMeshStandardMaterial || - material.isShaderMaterial || - material.isShadowMaterial || - material.skinning ) { + if ( material.iridescenceMap ) { - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + uniforms.iridescenceMap.value = material.iridescenceMap; } - } - - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // otherwise textures used for skinning can take over texture units reserved for other material textures - - if ( material.skinning ) { - - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + if ( material.iridescenceThicknessMap ) { - const skeleton = object.skeleton; + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; - if ( skeleton ) { + } - const bones = skeleton.bones; + } - if ( capabilities.floatVertexTextures ) { + if ( material.transmission > 0 ) { - if ( skeleton.boneTexture === null ) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); - // 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 ( material.transmissionMap ) { + uniforms.transmissionMap.value = material.transmissionMap; - let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix - size = MathUtils.ceilPowerOfTwo( size ); - size = Math.max( size, 4 ); + } - const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel - boneMatrices.set( skeleton.boneMatrices ); // copy current values + uniforms.thickness.value = material.thickness; - const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + if ( material.thicknessMap ) { - skeleton.boneMatrices = boneMatrices; - skeleton.boneTexture = boneTexture; - skeleton.boneTextureSize = size; + uniforms.thicknessMap.value = material.thicknessMap; - } + } - p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); - p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); - } else { + } - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); - } + if ( material.specularIntensityMap ) { - } + uniforms.specularIntensityMap.value = material.specularIntensityMap; } - if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + if ( material.specularColorMap ) { - materialProperties.receiveShadow = object.receiveShadow; - p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + uniforms.specularColorMap.value = material.specularColorMap; } - if ( refreshMaterial ) { + } - p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + function refreshUniformsMatcap( uniforms, material ) { - if ( materialProperties.needsLights ) { + if ( material.matcap ) { - // the current material requires lighting info + uniforms.matcap.value = material.matcap; - // 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 + } - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + } - } + function refreshUniformsDistance( uniforms, material ) { - // refresh uniforms common to several materials + uniforms.referencePosition.value.copy( material.referencePosition ); + uniforms.nearDistance.value = material.nearDistance; + uniforms.farDistance.value = material.farDistance; - if ( fog && material.fog ) { + } - materials.refreshFogUniforms( m_uniforms, fog ); + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; - } +} - materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height ); +function WebGLUniformsGroups( gl, info, capabilities, state ) { - WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; - } + const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program - if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + function bind( uniformsGroup, program ) { - WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); - material.uniformsNeedUpdate = false; + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); - } + } - if ( material.isSpriteMaterial ) { + function update( uniformsGroup, program ) { - p_uniforms.setValue( _gl, 'center', object.center ); + let buffer = buffers[ uniformsGroup.id ]; - } + if ( buffer === undefined ) { - // common matrices + prepareUniformsGroup( uniformsGroup ); - p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); - p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; - return program; + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); - } + } - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + // ensure to update the binding points/block indices mapping for this program - function markUniformsLightsNeedsUpdate( uniforms, value ) { + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); - uniforms.ambientLightColor.needsUpdate = value; - uniforms.lightProbe.needsUpdate = value; + // update UBO once per frame - uniforms.directionalLights.needsUpdate = value; - uniforms.directionalLightShadows.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.pointLightShadows.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.spotLightShadows.needsUpdate = value; - uniforms.rectAreaLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + const frame = info.render.frame; - } + if ( updateList[ uniformsGroup.id ] !== frame ) { - function materialNeedsLights( material ) { + updateBufferData( uniformsGroup ); - return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || - material.isMeshStandardMaterial || material.isShadowMaterial || - ( material.isShaderMaterial && material.lights === true ); + updateList[ uniformsGroup.id ] = frame; + + } } - // - this.setFramebuffer = function ( value ) { + function createBuffer( uniformsGroup ) { - if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value ); + // the setup of an UBO is independent of a particular shader program but global - _framebuffer = value; + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; - }; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; - this.getActiveCubeFace = function () { + gl.bindBuffer( 35345, buffer ); + gl.bufferData( 35345, size, usage ); + gl.bindBuffer( 35345, null ); + gl.bindBufferBase( 35345, bindingPointIndex, buffer ); - return _currentActiveCubeFace; + return buffer; - }; + } - this.getActiveMipmapLevel = function () { + function allocateBindingPointIndex() { - return _currentActiveMipmapLevel; + for ( let i = 0; i < maxBindingPoints; i ++ ) { - }; + if ( allocatedBindingPoints.indexOf( i ) === - 1 ) { - this.getRenderTarget = function () { + allocatedBindingPoints.push( i ); + return i; - return _currentRenderTarget; + } - }; + } - this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); - _currentRenderTarget = renderTarget; - _currentActiveCubeFace = activeCubeFace; - _currentActiveMipmapLevel = activeMipmapLevel; + return 0; - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + } - textures.setupRenderTarget( renderTarget ); + function updateBufferData( uniformsGroup ) { - } + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; - let framebuffer = _framebuffer; - let isCube = false; - let isRenderTarget3D = false; + gl.bindBuffer( 35345, buffer ); - if ( renderTarget ) { + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { - const texture = renderTarget.texture; + const uniform = uniforms[ i ]; - if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) { + // partly update the buffer if necessary - isRenderTarget3D = true; + if ( hasUniformChanged( uniform, i, cache ) === true ) { - } + const value = uniform.value; + const offset = uniform.__offset; - const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( typeof value === 'number' ) { - if ( renderTarget.isWebGLCubeRenderTarget ) { + uniform.__data[ 0 ] = value; + gl.bufferSubData( 35345, offset, uniform.__data ); - framebuffer = __webglFramebuffer[ activeCubeFace ]; - isCube = true; + } else { - } else if ( renderTarget.isWebGLMultisampleRenderTarget ) { + if ( uniform.value.isMatrix3 ) { - framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + // manually converting 3x3 to 3x4 - } else { + uniform.__data[ 0 ] = uniform.value.elements[ 0 ]; + uniform.__data[ 1 ] = uniform.value.elements[ 1 ]; + uniform.__data[ 2 ] = uniform.value.elements[ 2 ]; + uniform.__data[ 3 ] = uniform.value.elements[ 0 ]; + uniform.__data[ 4 ] = uniform.value.elements[ 3 ]; + uniform.__data[ 5 ] = uniform.value.elements[ 4 ]; + uniform.__data[ 6 ] = uniform.value.elements[ 5 ]; + uniform.__data[ 7 ] = uniform.value.elements[ 0 ]; + uniform.__data[ 8 ] = uniform.value.elements[ 6 ]; + uniform.__data[ 9 ] = uniform.value.elements[ 7 ]; + uniform.__data[ 10 ] = uniform.value.elements[ 8 ]; + uniform.__data[ 11 ] = uniform.value.elements[ 0 ]; - framebuffer = __webglFramebuffer; + } else { - } + value.toArray( uniform.__data ); - _currentViewport.copy( renderTarget.viewport ); - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + } - } else { + gl.bufferSubData( 35345, offset, uniform.__data ); - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); - _currentScissorTest = _scissorTest; + } + + } } - if ( _currentFramebuffer !== framebuffer ) { + gl.bindBuffer( 35345, null ); - _gl.bindFramebuffer( 36160, framebuffer ); - _currentFramebuffer = framebuffer; + } - } + function hasUniformChanged( uniform, index, cache ) { - state.viewport( _currentViewport ); - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + const value = uniform.value; - if ( isCube ) { + if ( cache[ index ] === undefined ) { - const textureProperties = properties.get( renderTarget.texture ); - _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + // cache entry does not exist so far - } else if ( isRenderTarget3D ) { + if ( typeof value === 'number' ) { - const textureProperties = properties.get( renderTarget.texture ); - const layer = activeCubeFace || 0; - _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); + cache[ index ] = value; - } + } else { - }; + cache[ index ] = value.clone(); - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + } - if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + return true; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + } else { - } + // compare current value with cached entry - let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( typeof value === 'number' ) { - if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + if ( cache[ index ] !== value ) { - framebuffer = framebuffer[ activeCubeFaceIndex ]; + cache[ index ] = value; + return true; - } + } - if ( framebuffer ) { + } else { - let restore = false; + const cachedObject = cache[ index ]; - if ( framebuffer !== _currentFramebuffer ) { + if ( cachedObject.equals( value ) === false ) { - _gl.bindFramebuffer( 36160, framebuffer ); + cachedObject.copy( value ); + return true; - restore = true; + } } - try { - - const texture = renderTarget.texture; - const textureFormat = texture.format; - const textureType = texture.type; + } - if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { + return false; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + } - } + function prepareUniformsGroup( uniformsGroup ) { - const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 - if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513) - ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox - ! halfFloatSupportedByExt ) { + const uniforms = uniformsGroup.uniforms; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + let chunkOffset = 0; // offset within a single chunk in bytes - } + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { - if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) { + const uniform = uniforms[ i ]; + const info = getUniformSize( uniform ); - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + // the following two properties will be used for partial buffer updates - if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; - _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + // - } + if ( i > 0 ) { - } else { + chunkOffset = offset % chunkSize; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + const remainingSizeInChunk = chunkSize - chunkOffset; - } + // check for chunk overflow - } finally { + if ( chunkOffset !== 0 && ( remainingSizeInChunk - info.boundary ) < 0 ) { - if ( restore ) { + // add padding and adjust offset - _gl.bindFramebuffer( 36160, _currentFramebuffer ); + offset += ( chunkSize - chunkOffset ); + uniform.__offset = offset; } } - } + offset += info.storage; - }; + } - this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { + // ensure correct final padding - const levelScale = Math.pow( 2, - level ); - const width = Math.floor( texture.image.width * levelScale ); - const height = Math.floor( texture.image.height * levelScale ); - const glFormat = utils.convert( texture.format ); + chunkOffset = offset % chunkSize; - textures.setTexture2D( texture, 0 ); + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); - _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 ); + // - state.unbindTexture(); + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; - }; + return this; - this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { + } - const width = srcTexture.image.width; - const height = srcTexture.image.height; - const glFormat = utils.convert( dstTexture.format ); - const glType = utils.convert( dstTexture.type ); + function getUniformSize( uniform ) { - textures.setTexture2D( dstTexture, 0 ); + const value = uniform.value; - // As another texture upload may have changed pixelStorei - // parameters, make sure they are correct for the dstTexture - _gl.pixelStorei( 37440, dstTexture.flipY ); - _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); - _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; - if ( srcTexture.isDataTexture ) { + // determine sizes according to STD140 - _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); + if ( typeof value === 'number' ) { - } else { + // float/int - if ( srcTexture.isCompressedTexture ) { + info.boundary = 4; + info.storage = 4; - _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); + } else if ( value.isVector2 ) { - } else { + // vec2 - _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image ); + info.boundary = 8; + info.storage = 8; - } + } else if ( value.isVector3 || value.isColor ) { - } + // vec3 - // Generate mipmaps only when copying level 0 - if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 ); + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes - state.unbindTexture(); + } else if ( value.isVector4 ) { - }; + // vec4 - this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { + info.boundary = 16; + info.storage = 16; - if ( _this.isWebGL1Renderer ) { + } else if ( value.isMatrix3 ) { - console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); - return; + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) - } + info.boundary = 48; + info.storage = 48; - const { width, height, data } = srcTexture.image; - const glFormat = utils.convert( dstTexture.format ); - const glType = utils.convert( dstTexture.type ); - let glTarget; + } else if ( value.isMatrix4 ) { - if ( dstTexture.isDataTexture3D ) { + // mat4 - textures.setTexture3D( dstTexture, 0 ); - glTarget = 32879; + info.boundary = 64; + info.storage = 64; - } else if ( dstTexture.isDataTexture2DArray ) { + } else if ( value.isTexture ) { - textures.setTexture2DArray( dstTexture, 0 ); - glTarget = 35866; + console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); } else { - console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); - return; + console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value ); } - _gl.pixelStorei( 37440, dstTexture.flipY ); - _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); - _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); + return info; - const unpackRowLen = _gl.getParameter( 3314 ); - const unpackImageHeight = _gl.getParameter( 32878 ); - const unpackSkipPixels = _gl.getParameter( 3316 ); - const unpackSkipRows = _gl.getParameter( 3315 ); - const unpackSkipImages = _gl.getParameter( 32877 ); + } - _gl.pixelStorei( 3314, width ); - _gl.pixelStorei( 32878, height ); - _gl.pixelStorei( 3316, sourceBox.min.x ); - _gl.pixelStorei( 3315, sourceBox.min.y ); - _gl.pixelStorei( 32877, sourceBox.min.z ); + function onUniformsGroupsDispose( event ) { - _gl.texSubImage3D( - glTarget, - level, - position.x, - position.y, - position.z, - sourceBox.max.x - sourceBox.min.x + 1, - sourceBox.max.y - sourceBox.min.y + 1, - sourceBox.max.z - sourceBox.min.z + 1, - glFormat, - glType, - data - ); + const uniformsGroup = event.target; - _gl.pixelStorei( 3314, unpackRowLen ); - _gl.pixelStorei( 32878, unpackImageHeight ); - _gl.pixelStorei( 3316, unpackSkipPixels ); - _gl.pixelStorei( 3315, unpackSkipRows ); - _gl.pixelStorei( 32877, unpackSkipImages ); + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); - // Generate mipmaps only when copying level 0 - if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); - state.unbindTexture(); + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); - }; + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; - this.initTexture = function ( texture ) { + } - textures.setTexture2D( texture, 0 ); + function dispose() { - state.unbindTexture(); + for ( const id in buffers ) { - }; + gl.deleteBuffer( buffers[ id ] ); - this.resetState = function () { + } - state.reset(); - bindingStates.reset(); + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; - }; + } - if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + return { - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef + bind: bind, + update: update, - } + dispose: dispose + + }; } -class WebGL1Renderer extends WebGLRenderer {} +function createCanvasElement() { -WebGL1Renderer.prototype.isWebGL1Renderer = true; + const canvas = createElementNS( 'canvas' ); + canvas.style.display = 'block'; + return canvas; -class FogExp2 { +} - constructor( color, density ) { +function WebGLRenderer( parameters = {} ) { - this.name = ''; + this.isWebGLRenderer = true; - this.color = new Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), + _context = parameters.context !== undefined ? parameters.context : null, - } + _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, + _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', + _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; - clone() { + let _alpha; - return new FogExp2( this.color, this.density ); + if ( _context !== null ) { - } + _alpha = _context.getContextAttributes().alpha; - toJSON( /* meta */ ) { + } else { - return { - type: 'FogExp2', - color: this.color.getHex(), - density: this.density - }; + _alpha = parameters.alpha !== undefined ? parameters.alpha : false; } -} + let currentRenderList = null; + let currentRenderState = null; -FogExp2.prototype.isFogExp2 = true; + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. -class Fog { + const renderListStack = []; + const renderStateStack = []; - constructor( color, near, far ) { + // public properties - this.name = ''; + this.domElement = _canvas; - this.color = new Color( color ); + // Debug configuration container + this.debug = { - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true + }; - } + // clearing - clone() { + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - return new Fog( this.color, this.near, this.far ); + // scene graph - } + this.sortObjects = true; - toJSON( /* meta */ ) { + // user-defined clipping - return { - type: 'Fog', - color: this.color.getHex(), - near: this.near, - far: this.far - }; + this.clippingPlanes = []; + this.localClippingEnabled = false; - } + // physically based shading -} + this.outputEncoding = LinearEncoding; -Fog.prototype.isFog = true; + // physical lights -class Scene extends Object3D { + this.physicallyCorrectLights = false; - constructor() { + // tone mapping - super(); + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1.0; - this.type = 'Scene'; + // - this.background = null; - this.environment = null; - this.fog = null; + Object.defineProperties( this, { - this.overrideMaterial = null; + // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d - this.autoUpdate = true; // checked by the renderer + gammaFactor: { + get: function () { - if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + return 2; - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef + }, + set: function () { + + console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' ); + } } - } + } ); - copy( source, recursive ) { + // internal properties - super.copy( source, recursive ); + const _this = this; - if ( source.background !== null ) this.background = source.background.clone(); - if ( source.environment !== null ) this.environment = source.environment.clone(); - if ( source.fog !== null ) this.fog = source.fog.clone(); + let _isContextLost = false; - if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + // internal state cache - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = - 1; - return this; + let _currentCamera = null; - } + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; - toJSON( meta ) { + // - const data = super.toJSON( meta ); + let _width = _canvas.width; + let _height = _canvas.height; - if ( this.background !== null ) data.object.background = this.background.toJSON( meta ); - if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta ); - if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; - return data; + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; - } + // frustum -} + const _frustum = new Frustum(); -Scene.prototype.isScene = true; + // clipping -function InterleavedBuffer( array, stride ) { + let _clippingEnabled = false; + let _localClippingEnabled = false; - this.array = array; - this.stride = stride; - this.count = array !== undefined ? array.length / stride : 0; + // transmission - this.usage = StaticDrawUsage; - this.updateRange = { offset: 0, count: - 1 }; + let _transmissionRenderTarget = null; - this.version = 0; + // camera matrices cache - this.uuid = MathUtils.generateUUID(); + const _projScreenMatrix = new Matrix4(); -} + const _vector2 = new Vector2(); + const _vector3 = new Vector3(); -Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', { + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; - set: function ( value ) { + function getTargetPixelRatio() { - if ( value === true ) this.version ++; + return _currentRenderTarget === null ? _pixelRatio : 1; } -} ); - -Object.assign( InterleavedBuffer.prototype, { + // initialize - isInterleavedBuffer: true, + let _gl = _context; - onUploadCallback: function () {}, + function getContext( contextNames, contextAttributes ) { - setUsage: function ( value ) { + for ( let i = 0; i < contextNames.length; i ++ ) { - this.usage = value; + const contextName = contextNames[ i ]; + const context = _canvas.getContext( contextName, contextAttributes ); + if ( context !== null ) return context; - return this; + } - }, + return null; - copy: function ( source ) { + } - this.array = new source.array.constructor( source.array ); - this.count = source.count; - this.stride = source.stride; - this.usage = source.usage; + try { - return this; + const contextAttributes = { + alpha: true, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer, + powerPreference: _powerPreference, + failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat + }; - }, + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); - copyAt: function ( index1, attribute, index2 ) { + // event listeners must be registered before WebGL context is created, see #12753 + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); - index1 *= this.stride; - index2 *= attribute.stride; + if ( _gl === null ) { - for ( let i = 0, l = this.stride; i < l; i ++ ) { + const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + if ( _this.isWebGL1Renderer === true ) { - } + contextNames.shift(); - return this; + } - }, + _gl = getContext( contextNames, contextAttributes ); - set: function ( value, offset = 0 ) { + if ( _gl === null ) { - this.array.set( value, offset ); + if ( getContext( contextNames ) ) { - return this; + throw new Error( 'Error creating WebGL context with your selected attributes.' ); - }, + } else { - clone: function ( data ) { + throw new Error( 'Error creating WebGL context.' ); - if ( data.arrayBuffers === undefined ) { + } - data.arrayBuffers = {}; + } } - if ( this.array.buffer._uuid === undefined ) { + // Some experimental-webgl implementations do not have getShaderPrecisionFormat + + if ( _gl.getShaderPrecisionFormat === undefined ) { + + _gl.getShaderPrecisionFormat = function () { + + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - this.array.buffer._uuid = MathUtils.generateUUID(); + }; } - if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + } catch ( error ) { - data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; + + } + + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - } + extensions.init( capabilities ); - const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); + utils = new WebGLUtils( _gl, extensions, capabilities ); - const ib = new InterleavedBuffer( array, this.stride ); - ib.setUsage( this.usage ); + state = new WebGLState( _gl, extensions, capabilities ); - return ib; + info = new WebGLInfo(); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + cubemaps = new WebGLCubeMaps( _this ); + cubeuvmaps = new WebGLCubeUVMaps( _this ); + attributes = new WebGLAttributes( _gl, capabilities ); + bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions, capabilities ); + background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); - }, + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); - onUpload: function ( callback ) { + info.programs = programCache.programs; - this.onUploadCallback = callback; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; - return this; + } - }, + initGLContext(); - toJSON: function ( data ) { + // xr - if ( data.arrayBuffers === undefined ) { + const xr = new WebXRManager( _this, _gl ); - data.arrayBuffers = {}; + this.xr = xr; - } + // API - // generate UUID for array buffer if necessary + this.getContext = function () { - if ( this.array.buffer._uuid === undefined ) { + return _gl; - this.array.buffer._uuid = MathUtils.generateUUID(); + }; - } + this.getContextAttributes = function () { - if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + return _gl.getContextAttributes(); - data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) ); + }; - } + this.forceContextLoss = function () { - // + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); - return { - uuid: this.uuid, - buffer: this.array.buffer._uuid, - type: this.array.constructor.name, - stride: this.stride - }; + }; - } + this.forceContextRestore = function () { -} ); + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); -const _vector$6 = new Vector3(); + }; -function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { + this.getPixelRatio = function () { - this.name = ''; + return _pixelRatio; - this.data = interleavedBuffer; - this.itemSize = itemSize; - this.offset = offset; + }; - this.normalized = normalized === true; + this.setPixelRatio = function ( value ) { -} + if ( value === undefined ) return; -Object.defineProperties( InterleavedBufferAttribute.prototype, { + _pixelRatio = value; - count: { + this.setSize( _width, _height, false ); - get: function () { + }; - return this.data.count; + this.getSize = function ( target ) { - } + return target.set( _width, _height ); - }, + }; - array: { + this.setSize = function ( width, height, updateStyle ) { - get: function () { + if ( xr.isPresenting ) { - return this.data.array; + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; } - }, + _width = width; + _height = height; - needsUpdate: { + _canvas.width = Math.floor( width * _pixelRatio ); + _canvas.height = Math.floor( height * _pixelRatio ); - set: function ( value ) { + if ( updateStyle !== false ) { - this.data.needsUpdate = value; + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; } - } + this.setViewport( 0, 0, width, height ); -} ); + }; -Object.assign( InterleavedBufferAttribute.prototype, { + this.getDrawingBufferSize = function ( target ) { - isInterleavedBufferAttribute: true, + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); - applyMatrix4: function ( m ) { + }; - for ( let i = 0, l = this.data.count; i < l; i ++ ) { + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { - _vector$6.x = this.getX( i ); - _vector$6.y = this.getY( i ); - _vector$6.z = this.getZ( i ); + _width = width; + _height = height; - _vector$6.applyMatrix4( m ); + _pixelRatio = pixelRatio; - this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + _canvas.width = Math.floor( width * pixelRatio ); + _canvas.height = Math.floor( height * pixelRatio ); - } + this.setViewport( 0, 0, width, height ); - return this; + }; - }, + this.getCurrentViewport = function ( target ) { - setX: function ( index, x ) { + return target.copy( _currentViewport ); - this.data.array[ index * this.data.stride + this.offset ] = x; + }; - return this; + this.getViewport = function ( target ) { - }, + return target.copy( _viewport ); - setY: function ( index, y ) { + }; - this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + this.setViewport = function ( x, y, width, height ) { - return this; + if ( x.isVector4 ) { - }, + _viewport.set( x.x, x.y, x.z, x.w ); - setZ: function ( index, z ) { + } else { - this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + _viewport.set( x, y, width, height ); - return this; + } - }, + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); - setW: function ( index, w ) { + }; - this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + this.getScissor = function ( target ) { - return this; + return target.copy( _scissor ); - }, + }; - getX: function ( index ) { + this.setScissor = function ( x, y, width, height ) { - return this.data.array[ index * this.data.stride + this.offset ]; + if ( x.isVector4 ) { - }, + _scissor.set( x.x, x.y, x.z, x.w ); - getY: function ( index ) { + } else { - return this.data.array[ index * this.data.stride + this.offset + 1 ]; + _scissor.set( x, y, width, height ); - }, + } - getZ: function ( index ) { + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); - return this.data.array[ index * this.data.stride + this.offset + 2 ]; + }; - }, + this.getScissorTest = function () { - getW: function ( index ) { + return _scissorTest; - return this.data.array[ index * this.data.stride + this.offset + 3 ]; + }; - }, + this.setScissorTest = function ( boolean ) { - setXY: function ( index, x, y ) { + state.setScissorTest( _scissorTest = boolean ); - index = index * this.data.stride + this.offset; + }; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; + this.setOpaqueSort = function ( method ) { - return this; + _opaqueSort = method; - }, + }; - setXYZ: function ( index, x, y, z ) { + this.setTransparentSort = function ( method ) { - index = index * this.data.stride + this.offset; + _transparentSort = method; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; + }; - return this; + // Clearing - }, + this.getClearColor = function ( target ) { - setXYZW: function ( index, x, y, z, w ) { + return target.copy( background.getClearColor() ); - 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; - this.data.array[ index + 3 ] = w; + this.setClearColor = function () { - return this; + background.setClearColor.apply( background, arguments ); - }, + }; - clone: function ( data ) { + this.getClearAlpha = function () { - if ( data === undefined ) { + return background.getClearAlpha(); - console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' ); + }; - const array = []; + this.setClearAlpha = function () { - for ( let i = 0; i < this.count; i ++ ) { + background.setClearAlpha.apply( background, arguments ); - const index = i * this.data.stride + this.offset; + }; - for ( let j = 0; j < this.itemSize; j ++ ) { + this.clear = function ( color = true, depth = true, stencil = true ) { - array.push( this.data.array[ index + j ] ); + let bits = 0; - } + if ( color ) bits |= 16384; + if ( depth ) bits |= 256; + if ( stencil ) bits |= 1024; - } + _gl.clear( bits ); - return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); + }; - } else { + this.clearColor = function () { - if ( data.interleavedBuffers === undefined ) { + this.clear( true, false, false ); - data.interleavedBuffers = {}; + }; - } + this.clearDepth = function () { - if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + this.clear( false, true, false ); - data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); + }; - } + this.clearStencil = function () { - return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); + this.clear( false, false, true ); - } + }; - }, + // - toJSON: function ( data ) { + this.dispose = function () { - if ( data === undefined ) { + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); - console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' ); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); - const array = []; + xr.dispose(); - for ( let i = 0; i < this.count; i ++ ) { + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); - const index = i * this.data.stride + this.offset; + if ( _transmissionRenderTarget ) { - for ( let j = 0; j < this.itemSize; j ++ ) { + _transmissionRenderTarget.dispose(); + _transmissionRenderTarget = null; - array.push( this.data.array[ index + j ] ); + } - } + animation.stop(); - } + }; - // deinterleave data and save it as an ordinary buffer attribute for now + // Events - return { - itemSize: this.itemSize, - type: this.array.constructor.name, - array: array, - normalized: this.normalized - }; + function onContextLost( event ) { - } else { + event.preventDefault(); - // save as true interlaved attribtue + console.log( 'THREE.WebGLRenderer: Context Lost.' ); - if ( data.interleavedBuffers === undefined ) { + _isContextLost = true; - data.interleavedBuffers = {}; + } - } + function onContextRestore( /* event */ ) { - if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + console.log( 'THREE.WebGLRenderer: Context Restored.' ); - data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); + _isContextLost = false; - } + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; - return { - isInterleavedBufferAttribute: true, - itemSize: this.itemSize, - data: this.data.uuid, - offset: this.offset, - normalized: this.normalized - }; + initGLContext(); - } + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; } -} ); + function onContextCreationError( event ) { -/** - * parameters = { - * color: , - * map: new THREE.Texture( ), - * alphaMap: new THREE.Texture( ), - * rotation: , - * sizeAttenuation: - * } - */ + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); -class SpriteMaterial extends Material { - - constructor( parameters ) { + } - super(); + function onMaterialDispose( event ) { - this.type = 'SpriteMaterial'; + const material = event.target; - this.color = new Color( 0xffffff ); + material.removeEventListener( 'dispose', onMaterialDispose ); - this.map = null; + deallocateMaterial( material ); - this.alphaMap = null; + } - this.rotation = 0; + // Buffer deallocation - this.sizeAttenuation = true; + function deallocateMaterial( material ) { - this.transparent = true; + releaseMaterialProgramReferences( material ); - this.setValues( parameters ); + properties.remove( material ); } - copy( source ) { - super.copy( source ); + function releaseMaterialProgramReferences( material ) { - this.color.copy( source.color ); + const programs = properties.get( material ).programs; - this.map = source.map; + if ( programs !== undefined ) { - this.alphaMap = source.alphaMap; + programs.forEach( function ( program ) { - this.rotation = source.rotation; + programCache.releaseProgram( program ); - this.sizeAttenuation = source.sizeAttenuation; + } ); - return this; + if ( material.isShaderMaterial ) { - } + programCache.releaseShaderCache( material ); -} + } -SpriteMaterial.prototype.isSpriteMaterial = true; + } -let _geometry; + } -const _intersectPoint = /*@__PURE__*/ new Vector3(); -const _worldScale = /*@__PURE__*/ new Vector3(); -const _mvPosition = /*@__PURE__*/ new Vector3(); + // Buffer rendering -const _alignedPosition = /*@__PURE__*/ new Vector2(); -const _rotatedPosition = /*@__PURE__*/ new Vector2(); -const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { -const _vA$1 = /*@__PURE__*/ new Vector3(); -const _vB$1 = /*@__PURE__*/ new Vector3(); -const _vC$1 = /*@__PURE__*/ new Vector3(); + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) -const _uvA$1 = /*@__PURE__*/ new Vector2(); -const _uvB$1 = /*@__PURE__*/ new Vector2(); -const _uvC$1 = /*@__PURE__*/ new Vector2(); + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); -class Sprite extends Object3D { + const program = setProgram( camera, scene, geometry, material, object ); - constructor( material ) { + state.setMaterial( material, frontFaceCW ); - super(); + // - this.type = 'Sprite'; + let index = geometry.index; + const position = geometry.attributes.position; - if ( _geometry === undefined ) { + // - _geometry = new BufferGeometry(); + if ( index === null ) { - const float32Array = new Float32Array( [ - - 0.5, - 0.5, 0, 0, 0, - 0.5, - 0.5, 0, 1, 0, - 0.5, 0.5, 0, 1, 1, - - 0.5, 0.5, 0, 0, 1 - ] ); + if ( position === undefined || position.count === 0 ) return; - const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); + } else if ( index.count === 0 ) { - _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); - _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); - _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); + return; } - this.geometry = _geometry; - this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - - this.center = new Vector2( 0.5, 0.5 ); - - } + // - raycast( raycaster, intersects ) { + let rangeFactor = 1; - if ( raycaster.camera === null ) { + if ( material.wireframe === true ) { - console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); + index = geometries.getWireframeAttribute( geometry ); + rangeFactor = 2; } - _worldScale.setFromMatrixScale( this.matrixWorld ); + bindingStates.setup( object, material, program, geometry, index ); - _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); - this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); + let attribute; + let renderer = bufferRenderer; - _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); + if ( index !== null ) { - if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + attribute = attributes.get( index ); - _worldScale.multiplyScalar( - _mvPosition.z ); + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); } - const rotation = this.material.rotation; - let sin, cos; + // - if ( rotation !== 0 ) { + const dataCount = ( index !== null ) ? index.count : position.count; - cos = Math.cos( rotation ); - sin = Math.sin( rotation ); + const rangeStart = geometry.drawRange.start * rangeFactor; + const rangeCount = geometry.drawRange.count * rangeFactor; - } + const groupStart = group !== null ? group.start * rangeFactor : 0; + const groupCount = group !== null ? group.count * rangeFactor : Infinity; - const center = this.center; + const drawStart = Math.max( rangeStart, groupStart ); + const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + const drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - _uvA$1.set( 0, 0 ); - _uvB$1.set( 1, 0 ); - _uvC$1.set( 1, 1 ); + if ( drawCount === 0 ) return; - // check first triangle - let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint ); + // - if ( intersect === null ) { + if ( object.isMesh ) { - // check second triangle - transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - _uvB$1.set( 0, 1 ); + if ( material.wireframe === true ) { - intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint ); - if ( intersect === null ) { + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( 1 ); - return; + } else { + + renderer.setMode( 4 ); } - } + } else if ( object.isLine ) { - const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); + let lineWidth = material.linewidth; - if ( distance < raycaster.near || distance > raycaster.far ) return; + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - intersects.push( { + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - distance: distance, - point: _intersectPoint.clone(), - uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ), - face: null, - object: this + if ( object.isLineSegments ) { - } ); + renderer.setMode( 1 ); - } + } else if ( object.isLineLoop ) { - copy( source ) { + renderer.setMode( 2 ); - super.copy( source ); + } else { - if ( source.center !== undefined ) this.center.copy( source.center ); + renderer.setMode( 3 ); - this.material = source.material; + } - return this; + } else if ( object.isPoints ) { - } + renderer.setMode( 0 ); -} + } else if ( object.isSprite ) { -Sprite.prototype.isSprite = true; + renderer.setMode( 4 ); -function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { + } - // compute position in camera space - _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); + if ( object.isInstancedMesh ) { - // to check if rotation is not zero - if ( sin !== undefined ) { + renderer.renderInstances( drawStart, drawCount, object.count ); - _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); - _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); + } else if ( geometry.isInstancedBufferGeometry ) { - } else { + const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount ); - _rotatedPosition.copy( _alignedPosition ); + renderer.renderInstances( drawStart, drawCount, instanceCount ); - } + } else { + renderer.render( drawStart, drawCount ); - vertexPosition.copy( mvPosition ); - vertexPosition.x += _rotatedPosition.x; - vertexPosition.y += _rotatedPosition.y; + } - // transform to world space - vertexPosition.applyMatrix4( _viewWorldMatrix ); + }; -} + // Compile -const _v1$4 = /*@__PURE__*/ new Vector3(); -const _v2$2 = /*@__PURE__*/ new Vector3(); + this.compile = function ( scene, camera ) { -class LOD extends Object3D { + function prepare( material, scene, object ) { - constructor() { + if ( material.transparent === true && material.side === DoubleSide ) { - super(); + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); - this._currentLevel = 0; + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); - this.type = 'LOD'; + material.side = DoubleSide; + + } else { + + getProgram( material, scene, object ); - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] - }, - isLOD: { - value: true, } - } ); - this.autoUpdate = true; + } - } + currentRenderState = renderStates.get( scene ); + currentRenderState.init(); - copy( source ) { + renderStateStack.push( currentRenderState ); - super.copy( source, false ); + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); - const levels = source.levels; + } - for ( let i = 0, l = levels.length; i < l; i ++ ) { + } - const level = levels[ i ]; + } ); - this.addLevel( level.object.clone(), level.distance ); + currentRenderState.setupLights( _this.physicallyCorrectLights ); - } + scene.traverse( function ( object ) { - this.autoUpdate = source.autoUpdate; + const material = object.material; - return this; + if ( material ) { - } + if ( Array.isArray( material ) ) { - addLevel( object, distance = 0 ) { + for ( let i = 0; i < material.length; i ++ ) { - distance = Math.abs( distance ); + const material2 = material[ i ]; - const levels = this.levels; + prepare( material2, scene, object ); - let l; + } - for ( l = 0; l < levels.length; l ++ ) { + } else { - if ( distance < levels[ l ].distance ) { + prepare( material, scene, object ); - break; + } } - } + } ); - levels.splice( l, 0, { distance: distance, object: object } ); + renderStateStack.pop(); + currentRenderState = null; - this.add( object ); + }; - return this; + // Animation Loop - } + let onAnimationFrameCallback = null; - getCurrentLevel() { + function onAnimationFrame( time ) { - return this._currentLevel; + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); } - getObjectForDistance( distance ) { - - const levels = this.levels; - - if ( levels.length > 0 ) { + function onXRSessionStart() { - let i, l; + animation.stop(); - for ( i = 1, l = levels.length; i < l; i ++ ) { + } - if ( distance < levels[ i ].distance ) { + function onXRSessionEnd() { - break; + animation.start(); - } + } - } + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); - return levels[ i - 1 ].object; + if ( typeof self !== 'undefined' ) animation.setContext( self ); - } + this.setAnimationLoop = function ( callback ) { - return null; + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); - } + ( callback === null ) ? animation.stop() : animation.start(); - raycast( raycaster, intersects ) { + }; - const levels = this.levels; + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); - if ( levels.length > 0 ) { + // Rendering - _v1$4.setFromMatrixPosition( this.matrixWorld ); + this.render = function ( scene, camera ) { - const distance = raycaster.ray.origin.distanceTo( _v1$4 ); + if ( camera !== undefined && camera.isCamera !== true ) { - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; } - } + if ( _isContextLost === true ) return; - update( camera ) { + // update scene graph - const levels = this.levels; + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); - if ( levels.length > 1 ) { + // update camera matrices and frustum - _v1$4.setFromMatrixPosition( camera.matrixWorld ); - _v2$2.setFromMatrixPosition( this.matrixWorld ); + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); - const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom; + if ( xr.enabled === true && xr.isPresenting === true ) { - levels[ 0 ].object.visible = true; + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); - let i, l; + camera = xr.getCamera(); // use XR camera for rendering - for ( i = 1, l = levels.length; i < l; i ++ ) { + } - if ( distance >= levels[ i ].distance ) { + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init(); - } else { + renderStateStack.push( currentRenderState ); - break; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); - } + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - } + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); - this._currentLevel = i - 1; + renderListStack.push( currentRenderList ); - for ( ; i < l; i ++ ) { + projectObject( scene, camera, 0, _this.sortObjects ); - levels[ i ].object.visible = false; + currentRenderList.finish(); - } + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); } - } + // - toJSON( meta ) { + if ( _clippingEnabled === true ) clipping.beginShadows(); - const data = super.toJSON( meta ); + const shadowsArray = currentRenderState.state.shadowsArray; - if ( this.autoUpdate === false ) data.object.autoUpdate = false; + shadowMap.render( shadowsArray, scene, camera ); - data.object.levels = []; + if ( _clippingEnabled === true ) clipping.endShadows(); - const levels = this.levels; + // - for ( let i = 0, l = levels.length; i < l; i ++ ) { + if ( this.info.autoReset === true ) this.info.reset(); - const level = levels[ i ]; + // - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + background.render( currentRenderList, scene ); - } + // render scene - return data; + currentRenderState.setupLights( _this.physicallyCorrectLights ); - } + if ( camera.isArrayCamera ) { -} + const cameras = camera.cameras; -const _basePosition = new Vector3(); + for ( let i = 0, l = cameras.length; i < l; i ++ ) { -const _skinIndex = new Vector4(); -const _skinWeight = new Vector4(); + const camera2 = cameras[ i ]; -const _vector$7 = new Vector3(); -const _matrix$1 = new Matrix4(); + renderScene( currentRenderList, scene, camera2, camera2.viewport ); -function SkinnedMesh( geometry, material ) { + } - Mesh.call( this, geometry, material ); + } else { - this.type = 'SkinnedMesh'; + renderScene( currentRenderList, scene, camera ); - this.bindMode = 'attached'; - this.bindMatrix = new Matrix4(); - this.bindMatrixInverse = new Matrix4(); + } -} + // -SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + if ( _currentRenderTarget !== null ) { - constructor: SkinnedMesh, + // resolve multisample renderbuffers to a single-sample texture if necessary - isSkinnedMesh: true, + textures.updateMultisampleRenderTarget( _currentRenderTarget ); - copy: function ( source ) { + // Generate mipmap if we're using any kind of mipmap filtering - Mesh.prototype.copy.call( this, source ); + textures.updateRenderTargetMipmap( _currentRenderTarget ); - this.bindMode = source.bindMode; - this.bindMatrix.copy( source.bindMatrix ); - this.bindMatrixInverse.copy( source.bindMatrixInverse ); + } - this.skeleton = source.skeleton; + // - return this; + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); - }, + // _gl.finish(); - bind: function ( skeleton, bindMatrix ) { + bindingStates.resetDefaultState(); + _currentMaterialId = - 1; + _currentCamera = null; - this.skeleton = skeleton; + renderStateStack.pop(); - if ( bindMatrix === undefined ) { + if ( renderStateStack.length > 0 ) { - this.updateMatrixWorld( true ); + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; - this.skeleton.calculateInverses(); + } else { - bindMatrix = this.matrixWorld; + currentRenderState = null; } - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.copy( bindMatrix ).invert(); - - }, + renderListStack.pop(); - pose: function () { + if ( renderListStack.length > 0 ) { - this.skeleton.pose(); + currentRenderList = renderListStack[ renderListStack.length - 1 ]; - }, + } else { - normalizeSkinWeights: function () { + currentRenderList = null; - const vector = new Vector4(); + } - const skinWeight = this.geometry.attributes.skinWeight; + }; - for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { + function projectObject( object, camera, groupOrder, sortObjects ) { - vector.x = skinWeight.getX( i ); - vector.y = skinWeight.getY( i ); - vector.z = skinWeight.getZ( i ); - vector.w = skinWeight.getW( i ); + if ( object.visible === false ) return; - const scale = 1.0 / vector.manhattanLength(); + const visible = object.layers.test( camera.layers ); - if ( scale !== Infinity ) { + if ( visible ) { - vector.multiplyScalar( scale ); + if ( object.isGroup ) { - } else { + groupOrder = object.renderOrder; - vector.set( 1, 0, 0, 0 ); // do something reasonable + } else if ( object.isLOD ) { - } + if ( object.autoUpdate === true ) object.update( camera ); - skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); + } else if ( object.isLight ) { - } + currentRenderState.pushLight( object ); - }, + if ( object.castShadow ) { - updateMatrixWorld: function ( force ) { + currentRenderState.pushShadow( object ); - Mesh.prototype.updateMatrixWorld.call( this, force ); + } - if ( this.bindMode === 'attached' ) { + } else if ( object.isSprite ) { - this.bindMatrixInverse.copy( this.matrixWorld ).invert(); + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { - } else if ( this.bindMode === 'detached' ) { + if ( sortObjects ) { - this.bindMatrixInverse.copy( this.bindMatrix ).invert(); + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - } else { + } - console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); + const geometry = objects.update( object ); + const material = object.material; - } + if ( material.visible ) { - }, + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); - boneTransform: function ( index, target ) { + } - const skeleton = this.skeleton; - const geometry = this.geometry; + } - _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); - _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); + } else if ( object.isMesh || object.isLine || object.isPoints ) { - _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix ); + if ( object.isSkinnedMesh ) { - target.set( 0, 0, 0 ); + // update skeleton only once in a frame - for ( let i = 0; i < 4; i ++ ) { + if ( object.skeleton.frame !== info.render.frame ) { - const weight = _skinWeight.getComponent( i ); + object.skeleton.update(); + object.skeleton.frame = info.render.frame; - if ( weight !== 0 ) { + } - const boneIndex = _skinIndex.getComponent( i ); + } - _matrix$1.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { - target.addScaledVector( _vector$7.copy( _basePosition ).applyMatrix4( _matrix$1 ), weight ); + if ( sortObjects ) { - } + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - } + } - return target.applyMatrix4( this.bindMatrixInverse ); + const geometry = objects.update( object ); + const material = object.material; - } + if ( Array.isArray( material ) ) { -} ); + const groups = geometry.groups; -function Bone() { + for ( let i = 0, l = groups.length; i < l; i ++ ) { - Object3D.call( this ); + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; - this.type = 'Bone'; + if ( groupMaterial && groupMaterial.visible ) { -} + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); -Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { + } - constructor: Bone, + } - isBone: true + } else if ( material.visible ) { -} ); + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); -const _offsetMatrix = /*@__PURE__*/ new Matrix4(); -const _identityMatrix = /*@__PURE__*/ new Matrix4(); + } -class Skeleton { + } - constructor( bones = [], boneInverses = [] ) { + } - this.uuid = MathUtils.generateUUID(); + } - this.bones = bones.slice( 0 ); - this.boneInverses = boneInverses; - this.boneMatrices = null; + const children = object.children; - this.boneTexture = null; - this.boneTextureSize = 0; + for ( let i = 0, l = children.length; i < l; i ++ ) { - this.frame = - 1; + projectObject( children[ i ], camera, groupOrder, sortObjects ); - this.init(); + } } - init() { - - const bones = this.bones; - const boneInverses = this.boneInverses; + function renderScene( currentRenderList, scene, camera, viewport ) { - this.boneMatrices = new Float32Array( bones.length * 16 ); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + const transparentObjects = currentRenderList.transparent; - // calculate inverse bone matrices if necessary + currentRenderState.setupLightsView( camera ); - if ( boneInverses.length === 0 ) { + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera ); - this.calculateInverses(); + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); - } else { + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); - // handle special case + // Ensure depth buffer writing is enabled so it can be cleared on next render - if ( bones.length !== boneInverses.length ) { + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); - console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' ); + state.setPolygonOffset( false ); - this.boneInverses = []; + } - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + function renderTransmissionPass( opaqueObjects, scene, camera ) { - this.boneInverses.push( new Matrix4() ); + const isWebGL2 = capabilities.isWebGL2; - } + if ( _transmissionRenderTarget === null ) { - } + _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: ( isWebGL2 && _antialias === true ) ? 4 : 0 + } ); } - } + _this.getDrawingBufferSize( _vector2 ); - calculateInverses() { + if ( isWebGL2 ) { - this.boneInverses.length = 0; + _transmissionRenderTarget.setSize( _vector2.x, _vector2.y ); - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + } else { - const inverse = new Matrix4(); + _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) ); - if ( this.bones[ i ] ) { + } - inverse.copy( this.bones[ i ].matrixWorld ).invert(); + // - } + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget( _transmissionRenderTarget ); + _this.clear(); - this.boneInverses.push( inverse ); + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; - } + renderObjects( opaqueObjects, scene, camera ); + + _this.toneMapping = currentToneMapping; + + textures.updateMultisampleRenderTarget( _transmissionRenderTarget ); + textures.updateRenderTargetMipmap( _transmissionRenderTarget ); + + _this.setRenderTarget( currentRenderTarget ); } - pose() { + function renderObjects( renderList, scene, camera ) { - // recover the bind-time world matrices + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + for ( let i = 0, l = renderList.length; i < l; i ++ ) { - const bone = this.bones[ i ]; + const renderItem = renderList[ i ]; - if ( bone ) { + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; - bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); } } - // compute the local matrices, positions, rotations and scales + } - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + function renderObject( object, scene, camera, geometry, material, group ) { - const bone = this.bones[ i ]; + object.onBeforeRender( _this, scene, camera, geometry, material, group ); - if ( bone ) { + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - if ( bone.parent && bone.parent.isBone ) { + material.onBeforeRender( _this, scene, camera, geometry, object, group ); - bone.matrix.copy( bone.parent.matrixWorld ).invert(); - bone.matrix.multiply( bone.matrixWorld ); + if ( material.transparent === true && material.side === DoubleSide ) { - } else { + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); - bone.matrix.copy( bone.matrixWorld ); + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); - } + material.side = DoubleSide; - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + } else { - } + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); } + object.onAfterRender( _this, scene, camera, geometry, material, group ); + } - update() { + function getProgram( material, scene, object ) { - const bones = this.bones; - const boneInverses = this.boneInverses; - const boneMatrices = this.boneMatrices; - const boneTexture = this.boneTexture; + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... - // flatten bone matrices to array + const materialProperties = properties.get( material ); - for ( let i = 0, il = bones.length; i < il; i ++ ) { + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; - // compute the offset between the current and the original transform + const lightsStateVersion = lights.state.version; - const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); - _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); - _offsetMatrix.toArray( boneMatrices, i * 16 ); + let programs = materialProperties.programs; - } + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change - if ( boneTexture !== null ) { + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); - boneTexture.needsUpdate = true; + if ( programs === undefined ) { - } + // new material - } + material.addEventListener( 'dispose', onMaterialDispose ); - clone() { + programs = new Map(); + materialProperties.programs = programs; - return new Skeleton( this.bones, this.boneInverses ); + } - } + let program = programs.get( programCacheKey ); - getBoneByName( name ) { + if ( program !== undefined ) { - for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + // early out if program and light state is identical - const bone = this.bones[ i ]; + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { - if ( bone.name === name ) { + updateCommonMaterialProperties( material, parameters ); - return bone; + return program; } - } - - return undefined; + } else { - } + parameters.uniforms = programCache.getUniforms( material ); - dispose( ) { + material.onBuild( object, parameters, _this ); - if ( this.boneTexture !== null ) { + material.onBeforeCompile( parameters, _this ); - this.boneTexture.dispose(); + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); - this.boneTexture = null; + materialProperties.uniforms = parameters.uniforms; } - } + const uniforms = materialProperties.uniforms; - fromJSON( json, bones ) { + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { - this.uuid = json.uuid; + uniforms.clippingPlanes = clipping.uniform; - for ( let i = 0, l = json.bones.length; i < l; i ++ ) { + } - const uuid = json.bones[ i ]; - let bone = bones[ uuid ]; + updateCommonMaterialProperties( material, parameters ); - if ( bone === undefined ) { + // store the light setup it was created for - console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid ); - bone = new Bone(); + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; - } + if ( materialProperties.needsLights ) { - this.bones.push( bone ); - this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms } - this.init(); + const progUniforms = program.getUniforms(); + const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - return this; + materialProperties.currentProgram = program; + materialProperties.uniformsList = uniformsList; + + return program; } - toJSON() { + function updateCommonMaterialProperties( material, parameters ) { - const data = { - metadata: { - version: 4.5, - type: 'Skeleton', - generator: 'Skeleton.toJSON' - }, - bones: [], - boneInverses: [] - }; + const materialProperties = properties.get( material ); - data.uuid = this.uuid; + materialProperties.outputEncoding = parameters.outputEncoding; + materialProperties.instancing = parameters.instancing; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; - const bones = this.bones; - const boneInverses = this.boneInverses; + } - for ( let i = 0, l = bones.length; i < l; i ++ ) { + function setProgram( camera, scene, geometry, material, object ) { - const bone = bones[ i ]; - data.bones.push( bone.uuid ); + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... - const boneInverse = boneInverses[ i ]; - data.boneInverses.push( boneInverse.toArray() ); + textures.resetTextureUnits(); - } + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding ); + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent; + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping; + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; - return data; + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; - } + if ( _clippingEnabled === true ) { -} + if ( _localClippingEnabled === true || camera !== _currentCamera ) { -const _instanceLocalMatrix = new Matrix4(); -const _instanceWorldMatrix = new Matrix4(); + const useCache = + camera === _currentCamera && + material.id === _currentMaterialId; -const _instanceIntersects = []; + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + clipping.setState( material, camera, useCache ); -const _mesh = new Mesh(); + } -function InstancedMesh( geometry, material, count ) { + } - Mesh.call( this, geometry, material ); + // - this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 ); - this.instanceColor = null; + let needsProgramChange = false; - this.count = count; + if ( material.version === materialProperties.__version ) { - this.frustumCulled = false; + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { -} + needsProgramChange = true; -InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + } else if ( materialProperties.outputEncoding !== encoding ) { - constructor: InstancedMesh, + needsProgramChange = true; - isInstancedMesh: true, + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { - copy: function ( source ) { + needsProgramChange = true; - Mesh.prototype.copy.call( this, source ); + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { - this.instanceMatrix.copy( source.instanceMatrix ); + needsProgramChange = true; - if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { - this.count = source.count; + needsProgramChange = true; - return this; + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { - }, + needsProgramChange = true; - getColorAt: function ( index, color ) { + } else if ( materialProperties.envMap !== envMap ) { - color.fromArray( this.instanceColor.array, index * 3 ); + needsProgramChange = true; - }, + } else if ( material.fog === true && materialProperties.fog !== fog ) { - getMatrixAt: function ( index, matrix ) { + needsProgramChange = true; - matrix.fromArray( this.instanceMatrix.array, index * 16 ); + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { - }, + needsProgramChange = true; - raycast: function ( raycaster, intersects ) { + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { - const matrixWorld = this.matrixWorld; - const raycastTimes = this.count; + needsProgramChange = true; - _mesh.geometry = this.geometry; - _mesh.material = this.material; + } else if ( materialProperties.vertexTangents !== vertexTangents ) { - if ( _mesh.material === undefined ) return; + needsProgramChange = true; - for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { + } else if ( materialProperties.morphTargets !== morphTargets ) { - // calculate the world matrix for each instance + needsProgramChange = true; - this.getMatrixAt( instanceId, _instanceLocalMatrix ); + } else if ( materialProperties.morphNormals !== morphNormals ) { - _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); + needsProgramChange = true; - // the mesh represents this single instance + } else if ( materialProperties.morphColors !== morphColors ) { - _mesh.matrixWorld = _instanceWorldMatrix; + needsProgramChange = true; - _mesh.raycast( raycaster, _instanceIntersects ); + } else if ( materialProperties.toneMapping !== toneMapping ) { - // process the result of raycast + needsProgramChange = true; - for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { + } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) { - const intersect = _instanceIntersects[ i ]; - intersect.instanceId = instanceId; - intersect.object = this; - intersects.push( intersect ); + needsProgramChange = true; } - _instanceIntersects.length = 0; + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; } - }, + // - setColorAt: function ( index, color ) { + let program = materialProperties.currentProgram; - if ( this.instanceColor === null ) { + if ( needsProgramChange === true ) { - this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 ); + program = getProgram( material, scene, object ); } - color.toArray( this.instanceColor.array, index * 3 ); - - }, + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; - setMatrixAt: function ( index, matrix ) { + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; - matrix.toArray( this.instanceMatrix.array, index * 16 ); + if ( state.useProgram( program.program ) ) { - }, + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - updateMorphTargets: function () { + } - }, + if ( material.id !== _currentMaterialId ) { - dispose: function () { + _currentMaterialId = material.id; - this.dispatchEvent( { type: 'dispose' } ); + refreshMaterial = true; - } + } -} ); + if ( refreshProgram || _currentCamera !== camera ) { -/** - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round" - * } - */ + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); -class LineBasicMaterial extends Material { + if ( capabilities.logarithmicDepthBuffer ) { - constructor( parameters ) { + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - super(); + } - this.type = 'LineBasicMaterial'; + if ( _currentCamera !== camera ) { - this.color = new Color( 0xffffff ); + _currentCamera = camera; - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + // 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.morphTargets = false; + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done - this.setValues( parameters ); + } - } + // load material specific uniforms + // (shader material also gets them for the sake of genericity) + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshStandardMaterial || + material.envMap ) { - copy( source ) { + const uCamPos = p_uniforms.map.cameraPosition; - super.copy( source ); + if ( uCamPos !== undefined ) { - this.color.copy( source.color ); + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + } - this.morphTargets = source.morphTargets; + } - return this; + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { - } + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); -} + } -LineBasicMaterial.prototype.isLineBasicMaterial = true; + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.isShadowMaterial || + object.isSkinnedMesh ) { -const _start = new Vector3(); -const _end = new Vector3(); -const _inverseMatrix$1 = new Matrix4(); -const _ray$1 = new Ray(); -const _sphere$2 = new Sphere(); + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); -function Line( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { + } - Object3D.call( this ); + } - this.type = 'Line'; + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures - this.geometry = geometry; - this.material = material; + if ( object.isSkinnedMesh ) { - this.updateMorphTargets(); + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); -} + const skeleton = object.skeleton; -Line.prototype = Object.assign( Object.create( Object3D.prototype ), { + if ( skeleton ) { - constructor: Line, + if ( capabilities.floatVertexTextures ) { - isLine: true, + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); - copy: function ( source ) { + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); - Object3D.prototype.copy.call( this, source ); + } else { - this.material = source.material; - this.geometry = source.geometry; + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); - return this; + } - }, + } - computeLineDistances: function () { + } - const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; - if ( geometry.isBufferGeometry ) { + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) { - // we assume non-indexed geometry + morphtargets.update( object, geometry, material, program ); - if ( geometry.index === null ) { + } - const positionAttribute = geometry.attributes.position; - const lineDistances = [ 0 ]; + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { - for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); - _start.fromBufferAttribute( positionAttribute, i - 1 ); - _end.fromBufferAttribute( positionAttribute, i ); + } - lineDistances[ i ] = lineDistances[ i - 1 ]; - lineDistances[ i ] += _start.distanceTo( _end ); + // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 - } + if ( material.isMeshGouraudMaterial && material.envMap !== null ) { - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + m_uniforms.envMap.value = envMap; - } else { + m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; - console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + } - } + if ( refreshMaterial ) { - } else if ( geometry.isGeometry ) { + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); - console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + if ( materialProperties.needsLights ) { - } + // the current material requires lighting info - return this; + // 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 - }, + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); - raycast: function ( raycaster, intersects ) { + } - const geometry = this.geometry; - const matrixWorld = this.matrixWorld; - const threshold = raycaster.params.Line.threshold; + // refresh uniforms common to several materials - // Checking boundingSphere distance to ray + if ( fog && material.fog === true ) { - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + materials.refreshFogUniforms( m_uniforms, fog ); - _sphere$2.copy( geometry.boundingSphere ); - _sphere$2.applyMatrix4( matrixWorld ); - _sphere$2.radius += threshold; + } - if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return; + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget ); - // + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); - _inverseMatrix$1.copy( matrixWorld ).invert(); - _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + } - const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - const localThresholdSq = localThreshold * localThreshold; + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { - const vStart = new Vector3(); - const vEnd = new Vector3(); - const interSegment = new Vector3(); - const interRay = new Vector3(); - const step = this.isLineSegments ? 2 : 1; + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + material.uniformsNeedUpdate = false; - if ( geometry.isBufferGeometry ) { + } - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; + if ( material.isSpriteMaterial ) { - if ( index !== null ) { + p_uniforms.setValue( _gl, 'center', object.center ); - const indices = index.array; + } - for ( let i = 0, l = indices.length - 1; i < l; i += step ) { + // common matrices - const a = indices[ i ]; - const b = indices[ i + 1 ]; + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - vStart.fromBufferAttribute( positionAttribute, a ); - vEnd.fromBufferAttribute( positionAttribute, b ); + // UBOs - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + if ( material.isShaderMaterial || material.isRawShaderMaterial ) { - if ( distSq > localThresholdSq ) continue; + const groups = material.uniformsGroups; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + for ( let i = 0, l = groups.length; i < l; i ++ ) { - const distance = raycaster.ray.origin.distanceTo( interRay ); + if ( capabilities.isWebGL2 ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + const group = groups[ i ]; - intersects.push( { + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); - 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 + } else { - } ); + console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' ); } - } else { + } - for ( let i = 0, l = positionAttribute.count - 1; i < l; i += step ) { + } - vStart.fromBufferAttribute( positionAttribute, i ); - vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + return program; - const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + } - if ( distSq > localThresholdSq ) continue; + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + function markUniformsLightsNeedsUpdate( uniforms, value ) { - const distance = raycaster.ray.origin.distanceTo( interRay ); + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; - if ( distance < raycaster.near || distance > raycaster.far ) continue; + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - intersects.push( { + } - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + function materialNeedsLights( material ) { - } ); + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); - } + } - } + this.getActiveCubeFace = function () { - } else if ( geometry.isGeometry ) { + return _currentActiveCubeFace; - console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + }; - } + this.getActiveMipmapLevel = function () { - }, + return _currentActiveMipmapLevel; - updateMorphTargets: function () { + }; - const geometry = this.geometry; + this.getRenderTarget = function () { - if ( geometry.isBufferGeometry ) { + return _currentRenderTarget; - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); + }; - if ( keys.length > 0 ) { + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture; - if ( morphAttribute !== undefined ) { + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__hasExternalTextures = true; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + if ( renderTargetProperties.__hasExternalTextures ) { - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; - const name = morphAttribute[ m ].name || String( m ); + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { - } + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; } } - } else { + } - const morphTargets = geometry.morphTargets; + }; - if ( morphTargets !== undefined && morphTargets.length > 0 ) { + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { - console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; - } + }; - } + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { - } + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let useDefaultFramebuffer = true; -} ); + if ( renderTarget ) { -const _start$1 = new Vector3(); -const _end$1 = new Vector3(); + const renderTargetProperties = properties.get( renderTarget ); -function LineSegments( geometry, material ) { + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { - Line.call( this, geometry, material ); + // We need to make sure to rebind the framebuffer. + state.bindFramebuffer( 36160, null ); + useDefaultFramebuffer = false; - this.type = 'LineSegments'; + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { -} + textures.setupRenderTarget( renderTarget ); -LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { + } else if ( renderTargetProperties.__hasExternalTextures ) { - constructor: LineSegments, + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); - isLineSegments: true, + } - computeLineDistances: function () { + } - const geometry = this.geometry; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { - if ( geometry.isBufferGeometry ) { + const texture = renderTarget.texture; - // we assume non-indexed geometry + if ( texture.isData3DTexture || texture.isDataArrayTexture ) { - if ( geometry.index === null ) { + isRenderTarget3D = true; - const positionAttribute = geometry.attributes.position; - const lineDistances = []; + } - for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; - _start$1.fromBufferAttribute( positionAttribute, i ); - _end$1.fromBufferAttribute( positionAttribute, i + 1 ); + if ( renderTarget.isWebGLCubeRenderTarget ) { - lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; - lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); + framebuffer = __webglFramebuffer[ activeCubeFace ]; + isCube = true; - } + } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; } else { - console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + framebuffer = __webglFramebuffer; } - } else if ( geometry.isGeometry ) { + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { - console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; } - return this; + const framebufferBound = state.bindFramebuffer( 36160, framebuffer ); - } + if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) { -} ); + state.drawBuffers( renderTarget, framebuffer ); -class LineLoop extends Line { + } - constructor( geometry, material ) { + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); - super( geometry, material ); + if ( isCube ) { - this.type = 'LineLoop'; + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); - } + } else if ( isRenderTarget3D ) { -} + const textureProperties = properties.get( renderTarget.texture ); + const layer = activeCubeFace || 0; + _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); -LineLoop.prototype.isLineLoop = true; + } -/** - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * alphaMap: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * - * morphTargets: - * } - */ + _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings -class PointsMaterial extends Material { + }; - constructor( parameters ) { + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { - super(); + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { - this.type = 'PointsMaterial'; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - this.color = new Color( 0xffffff ); + } - this.map = null; + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; - this.alphaMap = null; + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { - this.size = 1; - this.sizeAttenuation = true; + framebuffer = framebuffer[ activeCubeFaceIndex ]; - this.morphTargets = false; + } - this.setValues( parameters ); + if ( framebuffer ) { - } + state.bindFramebuffer( 36160, framebuffer ); - copy( source ) { + try { - super.copy( source ); + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; - this.color.copy( source.color ); + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { - this.map = source.map; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; - this.alphaMap = source.alphaMap; + } - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); - this.morphTargets = source.morphTargets; + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! halfFloatSupportedByExt ) { - return this; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - } + } -} + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) -PointsMaterial.prototype.isPointsMaterial = true; + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { -const _inverseMatrix$2 = new Matrix4(); -const _ray$2 = new Ray(); -const _sphere$3 = new Sphere(); -const _position$1 = new Vector3(); + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); -function Points( geometry = new BufferGeometry(), material = new PointsMaterial() ) { + } - Object3D.call( this ); + } finally { - this.type = 'Points'; + // restore framebuffer of current render target if necessary - this.geometry = geometry; - this.material = material; + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( 36160, framebuffer ); - this.updateMorphTargets(); + } -} + } -Points.prototype = Object.assign( Object.create( Object3D.prototype ), { + }; - constructor: Points, + this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { - isPoints: true, + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); - copy: function ( source ) { + textures.setTexture2D( texture, 0 ); - Object3D.prototype.copy.call( this, source ); + _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height ); - this.material = source.material; - this.geometry = source.geometry; + state.unbindTexture(); - return this; + }; - }, + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { - raycast: function ( raycaster, intersects ) { + const width = srcTexture.image.width; + const height = srcTexture.image.height; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); - const geometry = this.geometry; - const matrixWorld = this.matrixWorld; - const threshold = raycaster.params.Points.threshold; + textures.setTexture2D( dstTexture, 0 ); - // Checking boundingSphere distance to ray + // As another texture upload may have changed pixelStorei + // parameters, make sure they are correct for the dstTexture + _gl.pixelStorei( 37440, dstTexture.flipY ); + _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + if ( srcTexture.isDataTexture ) { - _sphere$3.copy( geometry.boundingSphere ); - _sphere$3.applyMatrix4( matrixWorld ); - _sphere$3.radius += threshold; + _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); - if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; + } else { - // + if ( srcTexture.isCompressedTexture ) { - _inverseMatrix$2.copy( matrixWorld ).invert(); - _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); - const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - const localThresholdSq = localThreshold * localThreshold; + } else { - if ( geometry.isBufferGeometry ) { + _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image ); - const index = geometry.index; - const attributes = geometry.attributes; - const positionAttribute = attributes.position; + } - if ( index !== null ) { + } - const indices = index.array; + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 ); - for ( let i = 0, il = indices.length; i < il; i ++ ) { + state.unbindTexture(); - const a = indices[ i ]; + }; - _position$1.fromBufferAttribute( positionAttribute, a ); + this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { - testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + if ( _this.isWebGL1Renderer ) { - } + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); + return; - } else { + } - for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) { + const width = sourceBox.max.x - sourceBox.min.x + 1; + const height = sourceBox.max.y - sourceBox.min.y + 1; + const depth = sourceBox.max.z - sourceBox.min.z + 1; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; - _position$1.fromBufferAttribute( positionAttribute, i ); + if ( dstTexture.isData3DTexture ) { - testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + textures.setTexture3D( dstTexture, 0 ); + glTarget = 32879; - } + } else if ( dstTexture.isDataArrayTexture ) { - } + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = 35866; } else { - console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); + return; } - }, - - updateMorphTargets: function () { - - const geometry = this.geometry; - - if ( geometry.isBufferGeometry ) { + _gl.pixelStorei( 37440, dstTexture.flipY ); + _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); - const morphAttributes = geometry.morphAttributes; - const keys = Object.keys( morphAttributes ); + const unpackRowLen = _gl.getParameter( 3314 ); + const unpackImageHeight = _gl.getParameter( 32878 ); + const unpackSkipPixels = _gl.getParameter( 3316 ); + const unpackSkipRows = _gl.getParameter( 3315 ); + const unpackSkipImages = _gl.getParameter( 32877 ); - if ( keys.length > 0 ) { + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image; - const morphAttribute = morphAttributes[ keys[ 0 ] ]; + _gl.pixelStorei( 3314, image.width ); + _gl.pixelStorei( 32878, image.height ); + _gl.pixelStorei( 3316, sourceBox.min.x ); + _gl.pixelStorei( 3315, sourceBox.min.y ); + _gl.pixelStorei( 32877, sourceBox.min.z ); - if ( morphAttribute !== undefined ) { + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data ); - for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + } else { - const name = morphAttribute[ m ].name || String( m ); + if ( srcTexture.isCompressedTexture ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); + _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); - } + } else { - } + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image ); } - } else { - - const morphTargets = geometry.morphTargets; + } - if ( morphTargets !== undefined && morphTargets.length > 0 ) { + _gl.pixelStorei( 3314, unpackRowLen ); + _gl.pixelStorei( 32878, unpackImageHeight ); + _gl.pixelStorei( 3316, unpackSkipPixels ); + _gl.pixelStorei( 3315, unpackSkipRows ); + _gl.pixelStorei( 32877, unpackSkipImages ); - console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); - } + state.unbindTexture(); - } + }; - } + this.initTexture = function ( texture ) { -} ); + if ( texture.isCubeTexture ) { -function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + textures.setTextureCube( texture, 0 ); - const rayPointDistanceSq = _ray$2.distanceSqToPoint( point ); + } else if ( texture.isData3DTexture ) { - if ( rayPointDistanceSq < localThresholdSq ) { + textures.setTexture3D( texture, 0 ); - const intersectPoint = new Vector3(); + } else if ( texture.isDataArrayTexture ) { - _ray$2.closestPointToPoint( point, intersectPoint ); - intersectPoint.applyMatrix4( matrixWorld ); + textures.setTexture2DArray( texture, 0 ); - const distance = raycaster.ray.origin.distanceTo( intersectPoint ); + } else { - if ( distance < raycaster.near || distance > raycaster.far ) return; + textures.setTexture2D( texture, 0 ); - intersects.push( { + } - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint, - index: index, - face: null, - object: object + state.unbindTexture(); - } ); + }; - } + this.resetState = function () { -} + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; -class VideoTexture extends Texture { + state.reset(); + bindingStates.reset(); - constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + }; - super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - this.format = format !== undefined ? format : RGBFormat; + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); - this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; - this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + } - this.generateMipmaps = false; +} - const scope = this; +class WebGL1Renderer extends WebGLRenderer {} - function updateVideo() { +WebGL1Renderer.prototype.isWebGL1Renderer = true; - scope.needsUpdate = true; - video.requestVideoFrameCallback( updateVideo ); +class FogExp2 { - } + constructor( color, density = 0.00025 ) { - if ( 'requestVideoFrameCallback' in video ) { + this.isFogExp2 = true; - video.requestVideoFrameCallback( updateVideo ); + this.name = ''; - } + this.color = new Color( color ); + this.density = density; } clone() { - return new this.constructor( this.image ).copy( this ); + return new FogExp2( this.color, this.density ); } - update() { - - const video = this.image; - const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; - - if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { - - this.needsUpdate = true; + toJSON( /* meta */ ) { - } + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; } } -VideoTexture.prototype.isVideoTexture = true; +class Fog { -class CompressedTexture extends Texture { + constructor( color, near = 1, far = 1000 ) { - constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.isFog = true; - super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.name = ''; - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + this.color = new Color( color ); - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + this.near = near; + this.far = far; - this.flipY = false; + } - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + clone() { - this.generateMipmaps = false; + return new Fog( this.color, this.near, this.far ); } -} - -CompressedTexture.prototype.isCompressedTexture = true; + toJSON( /* meta */ ) { -class CanvasTexture extends Texture { + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; - constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + } - super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); +} - this.needsUpdate = true; +class Scene extends Object3D { - } + constructor() { -} + super(); -CanvasTexture.prototype.isCanvasTexture = true; + this.isScene = true; -class DepthTexture extends Texture { + this.type = 'Scene'; - constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + this.background = null; + this.environment = null; + this.fog = null; - format = format !== undefined ? format : DepthFormat; + this.overrideMaterial = null; - if ( format !== DepthFormat && format !== DepthStencilFormat ) { + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); } - if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; - if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; + } - super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + copy( source, recursive ) { - this.image = { width: width, height: height }; + super.copy( source, recursive ); - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); - this.flipY = false; - this.generateMipmaps = false; + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + return this; } + toJSON( meta ) { -} + const data = super.toJSON( meta ); -DepthTexture.prototype.isDepthTexture = true; + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); -class CircleGeometry extends BufferGeometry { + return data; - constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) { + } - super(); + // @deprecated - this.type = 'CircleGeometry'; + get autoUpdate() { - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + return this.matrixWorldAutoUpdate; - segments = Math.max( 3, segments ); + } - // buffers + set autoUpdate( value ) { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + this.matrixWorldAutoUpdate = value; - // helper variables + } - const vertex = new Vector3(); - const uv = new Vector2(); +} - // center point +class InterleavedBuffer { - vertices.push( 0, 0, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( 0.5, 0.5 ); + constructor( array, stride ) { - for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { + this.isInterleavedBuffer = true; - const segment = thetaStart + s / segments * thetaLength; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; - // vertex + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + this.version = 0; - vertices.push( vertex.x, vertex.y, vertex.z ); + this.uuid = generateUUID(); - // normal + } - normals.push( 0, 0, 1 ); + onUploadCallback() {} - // uvs + set needsUpdate( value ) { - uv.x = ( vertices[ i ] / radius + 1 ) / 2; - uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + if ( value === true ) this.version ++; - uvs.push( uv.x, uv.y ); + } - } + setUsage( value ) { - // indices + this.usage = value; - for ( let i = 1; i <= segments; i ++ ) { + return this; - indices.push( i, i + 1, 0 ); + } - } + copy( source ) { - // build geometry + this.array = new source.array.constructor( source.array ); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + return this; } -} + copyAt( index1, attribute, index2 ) { -class CylinderGeometry extends BufferGeometry { + index1 *= this.stride; + index2 *= attribute.stride; - constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + for ( let i = 0, l = this.stride; i < l; i ++ ) { - super(); - this.type = 'CylinderGeometry'; + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - const scope = this; + return this; - radialSegments = Math.floor( radialSegments ); - heightSegments = Math.floor( heightSegments ); + } - // buffers + set( value, offset = 0 ) { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + this.array.set( value, offset ); - // helper variables + return this; - let index = 0; - const indexArray = []; - const halfHeight = height / 2; - let groupStart = 0; + } - // generate geometry + clone( data ) { - generateTorso(); + if ( data.arrayBuffers === undefined ) { - if ( openEnded === false ) { + data.arrayBuffers = {}; - if ( radiusTop > 0 ) generateCap( true ); - if ( radiusBottom > 0 ) generateCap( false ); + } + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); } - // build geometry + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; - function generateTorso() { + } - const normal = new Vector3(); - const vertex = new Vector3(); + const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); - let groupCount = 0; + const ib = new this.constructor( array, this.stride ); + ib.setUsage( this.usage ); - // this will be used to calculate the normal - const slope = ( radiusBottom - radiusTop ) / height; + return ib; - // generate vertices, normals and uvs + } - for ( let y = 0; y <= heightSegments; y ++ ) { + onUpload( callback ) { - const indexRow = []; + this.onUploadCallback = callback; - const v = y / heightSegments; + return this; - // calculate the radius of the current row + } - const radius = v * ( radiusBottom - radiusTop ) + radiusTop; + toJSON( data ) { - for ( let x = 0; x <= radialSegments; x ++ ) { + if ( data.arrayBuffers === undefined ) { - const u = x / radialSegments; + data.arrayBuffers = {}; - const theta = u * thetaLength + thetaStart; + } - const sinTheta = Math.sin( theta ); - const cosTheta = Math.cos( theta ); + // generate UUID for array buffer if necessary - // vertex + if ( this.array.buffer._uuid === undefined ) { - vertex.x = radius * sinTheta; - vertex.y = - v * height + halfHeight; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + this.array.buffer._uuid = generateUUID(); - // normal + } - normal.set( sinTheta, slope, cosTheta ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { - // uv + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); - uvs.push( u, 1 - v ); + } - // save index of vertex in respective row + // - indexRow.push( index ++ ); + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; - } + } - // now save vertices of the row in our index array +} - indexArray.push( indexRow ); +const _vector$6 = /*@__PURE__*/ new Vector3(); - } +class InterleavedBufferAttribute { - // generate indices + constructor( interleavedBuffer, itemSize, offset, normalized = false ) { - for ( let x = 0; x < radialSegments; x ++ ) { + this.isInterleavedBufferAttribute = true; - for ( let y = 0; y < heightSegments; y ++ ) { + this.name = ''; - // we use the index array to access the correct indices + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; - const a = indexArray[ y ][ x ]; - const b = indexArray[ y + 1 ][ x ]; - const c = indexArray[ y + 1 ][ x + 1 ]; - const d = indexArray[ y ][ x + 1 ]; + this.normalized = normalized === true; - // faces + } - indices.push( a, b, d ); - indices.push( b, c, d ); + get count() { - // update group counter + return this.data.count; - groupCount += 6; + } - } + get array() { - } + return this.data.array; - // add a group to the geometry. this will ensure multi material support + } - scope.addGroup( groupStart, groupCount, 0 ); + set needsUpdate( value ) { - // calculate new start value for groups + this.data.needsUpdate = value; - groupStart += groupCount; + } - } + applyMatrix4( m ) { - function generateCap( top ) { + for ( let i = 0, l = this.data.count; i < l; i ++ ) { - // save the index of the first center vertex - const centerIndexStart = index; + _vector$6.fromBufferAttribute( this, i ); - const uv = new Vector2(); - const vertex = new Vector3(); + _vector$6.applyMatrix4( m ); - let groupCount = 0; + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); - const radius = ( top === true ) ? radiusTop : radiusBottom; - const sign = ( top === true ) ? 1 : - 1; + } - // 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 + return this; - for ( let x = 1; x <= radialSegments; x ++ ) { + } - // vertex + applyNormalMatrix( m ) { - vertices.push( 0, halfHeight * sign, 0 ); + for ( let i = 0, l = this.count; i < l; i ++ ) { - // normal + _vector$6.fromBufferAttribute( this, i ); - normals.push( 0, sign, 0 ); + _vector$6.applyNormalMatrix( m ); - // uv + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); - uvs.push( 0.5, 0.5 ); + } - // increase index + return this; - index ++; + } - } + transformDirection( m ) { - // save the index of the last center vertex - const centerIndexEnd = index; + for ( let i = 0, l = this.count; i < l; i ++ ) { - // now we generate the surrounding vertices, normals and uvs + _vector$6.fromBufferAttribute( this, i ); - for ( let x = 0; x <= radialSegments; x ++ ) { + _vector$6.transformDirection( m ); - const u = x / radialSegments; - const theta = u * thetaLength + thetaStart; + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); - const cosTheta = Math.cos( theta ); - const sinTheta = Math.sin( theta ); + } - // vertex + return this; - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // normal + setX( index, x ) { - normals.push( 0, sign, 0 ); + if ( this.normalized ) x = normalize( x, this.array ); - // uv + this.data.array[ index * this.data.stride + this.offset ] = x; - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.push( uv.x, uv.y ); + return this; - // increase index + } - index ++; + setY( index, y ) { - } + if ( this.normalized ) y = normalize( y, this.array ); - // generate indices + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; - for ( let x = 0; x < radialSegments; x ++ ) { + return this; - const c = centerIndexStart + x; - const i = centerIndexEnd + x; + } - if ( top === true ) { + setZ( index, z ) { - // face top + if ( this.normalized ) z = normalize( z, this.array ); - indices.push( i, i + 1, c ); + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; - } else { + return this; - // face bottom + } - indices.push( i + 1, i, c ); + setW( index, w ) { - } + if ( this.normalized ) w = normalize( w, this.array ); - groupCount += 3; + 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, top === true ? 1 : 2 ); + getX( index ) { - // calculate new start value for groups + let x = this.data.array[ index * this.data.stride + this.offset ]; - groupStart += groupCount; + if ( this.normalized ) x = denormalize( x, this.array ); - } + return x; } -} + getY( index ) { -class ConeGeometry extends CylinderGeometry { + let y = this.data.array[ index * this.data.stride + this.offset + 1 ]; - constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + if ( this.normalized ) y = denormalize( y, this.array ); - super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + return y; - this.type = 'ConeGeometry'; + } - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + getZ( index ) { - } + let z = this.data.array[ index * this.data.stride + this.offset + 2 ]; -} + if ( this.normalized ) z = denormalize( z, this.array ); -class PolyhedronGeometry extends BufferGeometry { + return z; - constructor( vertices, indices, radius = 1, detail = 0 ) { + } - super(); + getW( index ) { - this.type = 'PolyhedronGeometry'; + let w = this.data.array[ index * this.data.stride + this.offset + 3 ]; - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + if ( this.normalized ) w = denormalize( w, this.array ); - // default buffer data + return w; - const vertexBuffer = []; - const uvBuffer = []; + } - // the subdivision creates the vertex buffer data + setXY( index, x, y ) { - subdivide( detail ); + index = index * this.data.stride + this.offset; - // all vertices should lie on a conceptual sphere with a given radius + if ( this.normalized ) { - applyRadius( radius ); + x = normalize( x, this.array ); + y = normalize( y, this.array ); - // finally, create the uv data + } - generateUVs(); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; - // build non-indexed geometry + return this; - this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + } - if ( detail === 0 ) { + setXYZ( index, x, y, z ) { - this.computeVertexNormals(); // flat normals + index = index * this.data.stride + this.offset; - } else { + if ( this.normalized ) { - this.normalizeNormals(); // smooth normals + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); } - // helper functions + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; - function subdivide( detail ) { + return this; - const a = new Vector3(); - const b = new Vector3(); - const c = new Vector3(); + } - // iterate over all faces and apply a subdivison with the given detail value + setXYZW( index, x, y, z, w ) { - for ( let i = 0; i < indices.length; i += 3 ) { + index = index * this.data.stride + this.offset; - // get the vertices of the face + if ( this.normalized ) { - getVertexByIndex( indices[ i + 0 ], a ); - getVertexByIndex( indices[ i + 1 ], b ); - getVertexByIndex( indices[ i + 2 ], c ); + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); - // perform subdivision + } - subdivideFace( a, b, c, detail ); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; - } + return this; - } + } - function subdivideFace( a, b, c, detail ) { + clone( data ) { - const cols = detail + 1; + if ( data === undefined ) { - // we use this multidimensional array as a data structure for creating the subdivision + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.' ); - const v = []; + const array = []; - // construct all of the vertices for this subdivision + for ( let i = 0; i < this.count; i ++ ) { - for ( let i = 0; i <= cols; i ++ ) { + const index = i * this.data.stride + this.offset; - v[ i ] = []; + for ( let j = 0; j < this.itemSize; j ++ ) { - const aj = a.clone().lerp( c, i / cols ); - const bj = b.clone().lerp( c, i / cols ); + array.push( this.data.array[ index + j ] ); - const rows = cols - i; + } - for ( let j = 0; j <= rows; j ++ ) { + } - if ( j === 0 && i === cols ) { + return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); - v[ i ][ j ] = aj; + } else { - } else { + if ( data.interleavedBuffers === undefined ) { - v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); + data.interleavedBuffers = {}; - } + } - } + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); } - // construct all of the faces + return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); - for ( let i = 0; i < cols; i ++ ) { + } + + } + + toJSON( data ) { - for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + if ( data === undefined ) { - const k = Math.floor( j / 2 ); + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.' ); - if ( j % 2 === 0 ) { + const array = []; - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); - pushVertex( v[ i ][ k ] ); + for ( let i = 0; i < this.count; i ++ ) { - } else { + const index = i * this.data.stride + this.offset; - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); + for ( let j = 0; j < this.itemSize; j ++ ) { - } + array.push( this.data.array[ index + j ] ); } } - } + // deinterleave data and save it as an ordinary buffer attribute for now - function applyRadius( radius ) { + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: array, + normalized: this.normalized + }; - const vertex = new Vector3(); + } else { - // iterate over the entire buffer and apply the radius to each vertex + // save as true interleaved attribtue - for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + if ( data.interleavedBuffers === undefined ) { - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + data.interleavedBuffers = {}; - vertex.normalize().multiplyScalar( radius ); + } - vertexBuffer[ i + 0 ] = vertex.x; - vertexBuffer[ i + 1 ] = vertex.y; - vertexBuffer[ i + 2 ] = vertex.z; + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } - function generateUVs() { + } - const vertex = new Vector3(); +} - for ( let i = 0; i < vertexBuffer.length; i += 3 ) { +class SpriteMaterial extends Material { - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + constructor( parameters ) { - const u = azimuth( vertex ) / 2 / Math.PI + 0.5; - const v = inclination( vertex ) / Math.PI + 0.5; - uvBuffer.push( u, 1 - v ); + super(); - } + this.isSpriteMaterial = true; - correctUVs(); + this.type = 'SpriteMaterial'; - correctSeam(); + this.color = new Color( 0xffffff ); - } + this.map = null; - function correctSeam() { + this.alphaMap = null; - // handle case when face straddles the seam, see #3269 + this.rotation = 0; - for ( let i = 0; i < uvBuffer.length; i += 6 ) { + this.sizeAttenuation = true; - // uv data of a single face + this.transparent = true; - const x0 = uvBuffer[ i + 0 ]; - const x1 = uvBuffer[ i + 2 ]; - const x2 = uvBuffer[ i + 4 ]; + this.fog = true; - const max = Math.max( x0, x1, x2 ); - const min = Math.min( x0, x1, x2 ); + this.setValues( parameters ); - // 0.9 is somewhat arbitrary + } - if ( max > 0.9 && min < 0.1 ) { + copy( source ) { - if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; - if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; - if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; + super.copy( source ); - } + this.color.copy( source.color ); - } + this.map = source.map; - } + this.alphaMap = source.alphaMap; - function pushVertex( vertex ) { + this.rotation = source.rotation; - vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + this.sizeAttenuation = source.sizeAttenuation; - } + this.fog = source.fog; - function getVertexByIndex( index, vertex ) { + return this; - const stride = index * 3; + } - vertex.x = vertices[ stride + 0 ]; - vertex.y = vertices[ stride + 1 ]; - vertex.z = vertices[ stride + 2 ]; +} - } +let _geometry; - function correctUVs() { +const _intersectPoint = /*@__PURE__*/ new Vector3(); +const _worldScale = /*@__PURE__*/ new Vector3(); +const _mvPosition = /*@__PURE__*/ new Vector3(); - const a = new Vector3(); - const b = new Vector3(); - const c = new Vector3(); +const _alignedPosition = /*@__PURE__*/ new Vector2(); +const _rotatedPosition = /*@__PURE__*/ new Vector2(); +const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); - const centroid = new Vector3(); +const _vA = /*@__PURE__*/ new Vector3(); +const _vB = /*@__PURE__*/ new Vector3(); +const _vC = /*@__PURE__*/ new Vector3(); - const uvA = new Vector2(); - const uvB = new Vector2(); - const uvC = new Vector2(); +const _uvA = /*@__PURE__*/ new Vector2(); +const _uvB = /*@__PURE__*/ new Vector2(); +const _uvC = /*@__PURE__*/ new Vector2(); - for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { +class Sprite extends Object3D { - a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); - b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); - c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); + constructor( material ) { - uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); - uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); - uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); + super(); - centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + this.isSprite = true; - const azi = azimuth( centroid ); + this.type = 'Sprite'; - correctUV( uvA, j + 0, a, azi ); - correctUV( uvB, j + 2, b, azi ); - correctUV( uvC, j + 4, c, azi ); + if ( _geometry === undefined ) { - } + _geometry = new BufferGeometry(); - } + const float32Array = new Float32Array( [ + - 0.5, - 0.5, 0, 0, 0, + 0.5, - 0.5, 0, 1, 0, + 0.5, 0.5, 0, 1, 1, + - 0.5, 0.5, 0, 0, 1 + ] ); - function correctUV( uv, stride, vector, azimuth ) { + const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { + _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); + _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); + _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); - uvBuffer[ stride ] = uv.x - 1; + } - } + this.geometry = _geometry; + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + this.center = new Vector2( 0.5, 0.5 ); - uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + } - } + raycast( raycaster, intersects ) { + + if ( raycaster.camera === null ) { + + console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); } - // Angle around the Y axis, counter-clockwise when looking from above. + _worldScale.setFromMatrixScale( this.matrixWorld ); - function azimuth( vector ) { + _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); + this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); - return Math.atan2( vector.z, - vector.x ); + _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); - } + if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + _worldScale.multiplyScalar( - _mvPosition.z ); - // Angle above the XZ plane. + } - function inclination( vector ) { + const rotation = this.material.rotation; + let sin, cos; - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + if ( rotation !== 0 ) { + + cos = Math.cos( rotation ); + sin = Math.sin( rotation ); } - } + const center = this.center; -} + transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); -class DodecahedronGeometry extends PolyhedronGeometry { + _uvA.set( 0, 0 ); + _uvB.set( 1, 0 ); + _uvC.set( 1, 1 ); - constructor( radius = 1, detail = 0 ) { + // check first triangle + let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint ); - const t = ( 1 + Math.sqrt( 5 ) ) / 2; - const r = 1 / t; + if ( intersect === null ) { - const vertices = [ + // check second triangle + transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + _uvB.set( 0, 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, 1, + intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint ); + if ( intersect === null ) { - // (0, ±1/φ, ±φ) - 0, - r, - t, 0, - r, t, - 0, r, - t, 0, r, t, + return; - // (±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 - ]; + } - const 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 - ]; + const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); - super( vertices, indices, radius, detail ); + if ( distance < raycaster.near || distance > raycaster.far ) return; - this.type = 'DodecahedronGeometry'; + intersects.push( { - this.parameters = { - radius: radius, - detail: detail - }; + distance: distance, + point: _intersectPoint.clone(), + uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ), + face: null, + object: this + + } ); } -} + copy( source, recursive ) { -const _v0$2 = new Vector3(); -const _v1$5 = new Vector3(); -const _normal$1 = new Vector3(); -const _triangle = new Triangle(); + super.copy( source, recursive ); -class EdgesGeometry extends BufferGeometry { + if ( source.center !== undefined ) this.center.copy( source.center ); - constructor( geometry, thresholdAngle ) { + this.material = source.material; - super(); + return this; - this.type = 'EdgesGeometry'; + } - this.parameters = { - thresholdAngle: thresholdAngle - }; +} - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; +function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { - if ( geometry.isGeometry === true ) { + // compute position in camera space + _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); - console.error( 'THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - return; + // to check if rotation is not zero + if ( sin !== undefined ) { - } + _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); + _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); - const precisionPoints = 4; - const precision = Math.pow( 10, precisionPoints ); - const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle ); + } else { - const indexAttr = geometry.getIndex(); - const positionAttr = geometry.getAttribute( 'position' ); - const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + _rotatedPosition.copy( _alignedPosition ); - const indexArr = [ 0, 0, 0 ]; - const vertKeys = [ 'a', 'b', 'c' ]; - const hashes = new Array( 3 ); + } - const edgeData = {}; - const vertices = []; - for ( let i = 0; i < indexCount; i += 3 ) { - if ( indexAttr ) { + vertexPosition.copy( mvPosition ); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; - indexArr[ 0 ] = indexAttr.getX( i ); - indexArr[ 1 ] = indexAttr.getX( i + 1 ); - indexArr[ 2 ] = indexAttr.getX( i + 2 ); + // transform to world space + vertexPosition.applyMatrix4( _viewWorldMatrix ); - } else { +} - indexArr[ 0 ] = i; - indexArr[ 1 ] = i + 1; - indexArr[ 2 ] = i + 2; +const _v1$2 = /*@__PURE__*/ new Vector3(); +const _v2$1 = /*@__PURE__*/ new Vector3(); - } +class LOD extends Object3D { - const { a, b, c } = _triangle; - a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); - b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); - c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); - _triangle.getNormal( _normal$1 ); + constructor() { - // create hashes for the edge from the vertices - hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; - hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; - hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; + super(); - // skip degenerate triangles - if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { + this._currentLevel = 0; - continue; + this.type = 'LOD'; + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true, } + } ); - // iterate over every edge - for ( let j = 0; j < 3; j ++ ) { + this.autoUpdate = true; - // get the first and next vertex making up the edge - const jNext = ( j + 1 ) % 3; - const vecHash0 = hashes[ j ]; - const vecHash1 = hashes[ jNext ]; - const v0 = _triangle[ vertKeys[ j ] ]; - const v1 = _triangle[ vertKeys[ jNext ] ]; + } - const hash = `${ vecHash0 }_${ vecHash1 }`; - const reverseHash = `${ vecHash1 }_${ vecHash0 }`; + copy( source ) { - if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { + super.copy( source, false ); - // if we found a sibling edge add it into the vertex array if - // it meets the angle threshold and delete the edge from the map. - if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + const levels = source.levels; - vertices.push( v0.x, v0.y, v0.z ); - vertices.push( v1.x, v1.y, v1.z ); + for ( let i = 0, l = levels.length; i < l; i ++ ) { - } + const level = levels[ i ]; - edgeData[ reverseHash ] = null; + this.addLevel( level.object.clone(), level.distance ); - } else if ( ! ( hash in edgeData ) ) { + } - // if we've already got an edge here then skip adding a new one - edgeData[ hash ] = { + this.autoUpdate = source.autoUpdate; - index0: indexArr[ j ], - index1: indexArr[ jNext ], - normal: _normal$1.clone(), + return this; - }; + } - } + addLevel( object, distance = 0 ) { - } + distance = Math.abs( distance ); - } + const levels = this.levels; - // iterate over all remaining, unmatched edges and add them to the vertex array - for ( const key in edgeData ) { + let l; - if ( edgeData[ key ] ) { + for ( l = 0; l < levels.length; l ++ ) { - const { index0, index1 } = edgeData[ key ]; - _v0$2.fromBufferAttribute( positionAttr, index0 ); - _v1$5.fromBufferAttribute( positionAttr, index1 ); + if ( distance < levels[ l ].distance ) { - vertices.push( _v0$2.x, _v0$2.y, _v0$2.z ); - vertices.push( _v1$5.x, _v1$5.y, _v1$5.z ); + break; } } - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + levels.splice( l, 0, { distance: distance, object: object } ); - } + this.add( object ); -} + return this; -/** - * Port from https://github.com/mapbox/earcut (v2.2.2) - */ + } -const Earcut = { + getCurrentLevel() { - triangulate: function ( data, holeIndices, dim ) { + return this._currentLevel; - dim = dim || 2; + } - const hasHoles = holeIndices && holeIndices.length; - const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; - let outerNode = linkedList( data, 0, outerLen, dim, true ); - const triangles = []; + getObjectForDistance( distance ) { - if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + const levels = this.levels; - let minX, minY, maxX, maxY, x, y, invSize; + if ( levels.length > 0 ) { - if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + let i, l; - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if ( data.length > 80 * dim ) { + for ( i = 1, l = levels.length; i < l; i ++ ) { - minX = maxX = data[ 0 ]; - minY = maxY = data[ 1 ]; + if ( distance < levels[ i ].distance ) { - for ( let i = dim; i < outerLen; i += dim ) { + break; - x = data[ i ]; - y = data[ i + 1 ]; - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; + } } - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max( maxX - minX, maxY - minY ); - invSize = invSize !== 0 ? 1 / invSize : 0; + return levels[ i - 1 ].object; } - earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); - - return triangles; + return null; } -}; + raycast( raycaster, intersects ) { -// create a circular doubly linked list from polygon points in the specified winding order -function linkedList( data, start, end, dim, clockwise ) { + const levels = this.levels; - let i, last; + if ( levels.length > 0 ) { - if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { + _v1$2.setFromMatrixPosition( this.matrixWorld ); - for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + const distance = raycaster.ray.origin.distanceTo( _v1$2 ); - } else { + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + } } - if ( last && equals( last, last.next ) ) { + update( camera ) { - removeNode( last ); - last = last.next; + const levels = this.levels; - } + if ( levels.length > 1 ) { - return last; + _v1$2.setFromMatrixPosition( camera.matrixWorld ); + _v2$1.setFromMatrixPosition( this.matrixWorld ); -} + const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom; -// eliminate colinear or duplicate points -function filterPoints( start, end ) { + levels[ 0 ].object.visible = true; - if ( ! start ) return start; - if ( ! end ) end = start; + let i, l; - let p = start, - again; - do { + for ( i = 1, l = levels.length; i < l; i ++ ) { - again = false; + if ( distance >= levels[ i ].distance ) { - if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - removeNode( p ); - p = end = p.prev; - if ( p === p.next ) break; - again = true; + } else { - } else { + break; - p = p.next; + } - } + } - } while ( again || p !== end ); + this._currentLevel = i - 1; - return end; + for ( ; i < l; i ++ ) { -} + levels[ i ].object.visible = false; -// main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { + } - if ( ! ear ) return; + } - // interlink polygon nodes in z-order - if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); + } - let stop = ear, - prev, next; + toJSON( meta ) { - // iterate through ears, slicing them one by one - while ( ear.prev !== ear.next ) { + const data = super.toJSON( meta ); - prev = ear.prev; - next = ear.next; + if ( this.autoUpdate === false ) data.object.autoUpdate = false; - if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + data.object.levels = []; - // cut off the triangle - triangles.push( prev.i / dim ); - triangles.push( ear.i / dim ); - triangles.push( next.i / dim ); + const levels = this.levels; - removeNode( ear ); + for ( let i = 0, l = levels.length; i < l; i ++ ) { - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; + const level = levels[ i ]; - continue; + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); } - ear = next; - - // if we looped through the whole remaining polygon and can't find any more ears - if ( ear === stop ) { + return data; - // try filtering points and slicing again - if ( ! pass ) { + } - earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); +} - // if this didn't work, try curing all small self-intersections locally +const _basePosition = /*@__PURE__*/ new Vector3(); - } else if ( pass === 1 ) { +const _skinIndex = /*@__PURE__*/ new Vector4(); +const _skinWeight = /*@__PURE__*/ new Vector4(); - ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); - earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); +const _vector$5 = /*@__PURE__*/ new Vector3(); +const _matrix = /*@__PURE__*/ new Matrix4(); - // as a last resort, try splitting the remaining polygon into two +class SkinnedMesh extends Mesh { - } else if ( pass === 2 ) { + constructor( geometry, material ) { - splitEarcut( ear, triangles, dim, minX, minY, invSize ); + super( geometry, material ); - } + this.isSkinnedMesh = true; - break; + this.type = 'SkinnedMesh'; - } + this.bindMode = 'attached'; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); } -} - -// check whether a polygon node forms a valid ear with adjacent nodes -function isEar( ear ) { - - const a = ear.prev, - b = ear, - c = ear.next; - - if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - - // now make sure we don't have other points inside the potential ear - let p = ear.next.next; - - while ( p !== ear.prev ) { + copy( source, recursive ) { - if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) return false; - p = p.next; + super.copy( source, recursive ); - } + this.bindMode = source.bindMode; + this.bindMatrix.copy( source.bindMatrix ); + this.bindMatrixInverse.copy( source.bindMatrixInverse ); - return true; + this.skeleton = source.skeleton; -} + return this; -function isEarHashed( ear, minX, minY, invSize ) { + } - const a = ear.prev, - b = ear, - c = ear.next; + bind( skeleton, bindMatrix ) { - if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + this.skeleton = skeleton; - // triangle bbox; min & max are calculated like this for speed - const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), - minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), - maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), - maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); + if ( bindMatrix === undefined ) { - // z-order range for the current triangle bbox; - const minZ = zOrder( minTX, minTY, minX, minY, invSize ), - maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); + this.updateMatrixWorld( true ); - let p = ear.prevZ, - n = ear.nextZ; + this.skeleton.calculateInverses(); - // look for points inside the triangle in both directions - while ( p && p.z >= minZ && n && n.z <= maxZ ) { + bindMatrix = this.matrixWorld; - if ( p !== ear.prev && p !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) return false; - p = p.prevZ; + } - if ( n !== ear.prev && n !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && - area( n.prev, n, n.next ) >= 0 ) return false; - n = n.nextZ; + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.copy( bindMatrix ).invert(); } - // look for remaining points in decreasing z-order - while ( p && p.z >= minZ ) { + pose() { - if ( p !== ear.prev && p !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) return false; - p = p.prevZ; + this.skeleton.pose(); } - // look for remaining points in increasing z-order - while ( n && n.z <= maxZ ) { + normalizeSkinWeights() { - if ( n !== ear.prev && n !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && - area( n.prev, n, n.next ) >= 0 ) return false; - n = n.nextZ; + const vector = new Vector4(); - } + const skinWeight = this.geometry.attributes.skinWeight; - return true; + for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { -} + vector.fromBufferAttribute( skinWeight, i ); -// go through all polygon nodes and cure small local self-intersections -function cureLocalIntersections( start, triangles, dim ) { + const scale = 1.0 / vector.manhattanLength(); - let p = start; - do { + if ( scale !== Infinity ) { - const a = p.prev, - b = p.next.next; + vector.multiplyScalar( scale ); - if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + } else { - triangles.push( a.i / dim ); - triangles.push( p.i / dim ); - triangles.push( b.i / dim ); + vector.set( 1, 0, 0, 0 ); // do something reasonable - // remove two nodes involved - removeNode( p ); - removeNode( p.next ); + } - p = start = b; + skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); } - p = p.next; + } - } while ( p !== start ); + updateMatrixWorld( force ) { - return filterPoints( p ); + super.updateMatrixWorld( force ); -} + if ( this.bindMode === 'attached' ) { -// try splitting polygon into two and triangulate them independently -function splitEarcut( start, triangles, dim, minX, minY, invSize ) { + this.bindMatrixInverse.copy( this.matrixWorld ).invert(); - // look for a valid diagonal that divides the polygon into two - let a = start; - do { + } else if ( this.bindMode === 'detached' ) { - let b = a.next.next; - while ( b !== a.prev ) { + this.bindMatrixInverse.copy( this.bindMatrix ).invert(); - if ( a.i !== b.i && isValidDiagonal( a, b ) ) { + } else { - // split the polygon in two by the diagonal - let c = splitPolygon( a, b ); + console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); - // filter colinear points around the cuts - a = filterPoints( a, a.next ); - c = filterPoints( c, c.next ); + } - // run earcut on each half - earcutLinked( a, triangles, dim, minX, minY, invSize ); - earcutLinked( c, triangles, dim, minX, minY, invSize ); - return; + } - } + boneTransform( index, target ) { - b = b.next; + const skeleton = this.skeleton; + const geometry = this.geometry; - } + _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); + _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); - a = a.next; + _basePosition.copy( target ).applyMatrix4( this.bindMatrix ); - } while ( a !== start ); + target.set( 0, 0, 0 ); -} + for ( let i = 0; i < 4; i ++ ) { -// link every hole into the outer loop, producing a single-ring polygon without holes -function eliminateHoles( data, holeIndices, outerNode, dim ) { + const weight = _skinWeight.getComponent( i ); - const queue = []; - let i, len, start, end, list; + if ( weight !== 0 ) { - for ( i = 0, len = holeIndices.length; i < len; i ++ ) { + const boneIndex = _skinIndex.getComponent( i ); - start = holeIndices[ i ] * dim; - end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; - list = linkedList( data, start, end, dim, false ); - if ( list === list.next ) list.steiner = true; - queue.push( getLeftmost( list ) ); + _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); - } + target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight ); - queue.sort( compareX ); + } - // process holes from left to right - for ( i = 0; i < queue.length; i ++ ) { + } - eliminateHole( queue[ i ], outerNode ); - outerNode = filterPoints( outerNode, outerNode.next ); + return target.applyMatrix4( this.bindMatrixInverse ); } - return outerNode; - } -function compareX( a, b ) { +class Bone extends Object3D { - return a.x - b.x; + constructor() { + + super(); + + this.isBone = true; + + this.type = 'Bone'; + + } } -// find a bridge between vertices that connects hole with an outer ring and and link it -function eliminateHole( hole, outerNode ) { +class DataTexture extends Texture { - outerNode = findHoleBridge( hole, outerNode ); - if ( outerNode ) { + constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) { - const b = splitPolygon( outerNode, hole ); + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - // filter collinear points around the cuts - filterPoints( outerNode, outerNode.next ); - filterPoints( b, b.next ); + this.isDataTexture = true; + + this.image = { data: data, width: width, height: height }; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; } } -// David Eberly's algorithm for finding a bridge between hole and outer polygon -function findHoleBridge( hole, outerNode ) { +const _offsetMatrix = /*@__PURE__*/ new Matrix4(); +const _identityMatrix = /*@__PURE__*/ new Matrix4(); - let p = outerNode; - const hx = hole.x; - const hy = hole.y; - let qx = - Infinity, m; +class Skeleton { - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { + constructor( bones = [], boneInverses = [] ) { - if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { + this.uuid = generateUUID(); - const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); - if ( x <= hx && x > qx ) { + this.bones = bones.slice( 0 ); + this.boneInverses = boneInverses; + this.boneMatrices = null; - qx = x; - if ( x === hx ) { + this.boneTexture = null; + this.boneTextureSize = 0; - if ( hy === p.y ) return p; - if ( hy === p.next.y ) return p.next; + this.frame = - 1; - } + this.init(); - m = p.x < p.next.x ? p : p.next; + } - } + init() { - } + const bones = this.bones; + const boneInverses = this.boneInverses; - p = p.next; + this.boneMatrices = new Float32Array( bones.length * 16 ); - } while ( p !== outerNode ); + // calculate inverse bone matrices if necessary - if ( ! m ) return null; + if ( boneInverses.length === 0 ) { - if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint + this.calculateInverses(); - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point + } else { - const stop = m, - mx = m.x, - my = m.y; - let tanMin = Infinity, tan; + // handle special case - p = m; + if ( bones.length !== boneInverses.length ) { - do { + console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' ); - if ( hx >= p.x && p.x >= mx && hx !== p.x && - pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { + this.boneInverses = []; - tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { + this.boneInverses.push( new Matrix4() ); - m = p; - tanMin = tan; + } } } - p = p.next; - - } while ( p !== stop ); + } - return m; + calculateInverses() { -} + this.boneInverses.length = 0; -// whether sector in vertex m contains sector in vertex p in the same coordinates -function sectorContainsSector( m, p ) { + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; + const inverse = new Matrix4(); -} + if ( this.bones[ i ] ) { -// interlink polygon nodes in z-order -function indexCurve( start, minX, minY, invSize ) { + inverse.copy( this.bones[ i ].matrixWorld ).invert(); - let p = start; - do { + } - if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; + this.boneInverses.push( inverse ); - } while ( p !== start ); + } - p.prevZ.nextZ = null; - p.prevZ = null; + } - sortLinked( p ); + pose() { -} + // recover the bind-time world matrices -// Simon Tatham's linked list merge sort algorithm -// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html -function sortLinked( list ) { + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - let i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; + const bone = this.bones[ i ]; - do { + if ( bone ) { - p = list; - list = null; - tail = null; - numMerges = 0; + bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); - while ( p ) { + } - numMerges ++; - q = p; - pSize = 0; - for ( i = 0; i < inSize; i ++ ) { + } - pSize ++; - q = q.nextZ; - if ( ! q ) break; + // compute the local matrices, positions, rotations and scales - } + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - qSize = inSize; + const bone = this.bones[ i ]; - while ( pSize > 0 || ( qSize > 0 && q ) ) { + if ( bone ) { - if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { + if ( bone.parent && bone.parent.isBone ) { - e = p; - p = p.nextZ; - pSize --; + bone.matrix.copy( bone.parent.matrixWorld ).invert(); + bone.matrix.multiply( bone.matrixWorld ); } else { - e = q; - q = q.nextZ; - qSize --; + bone.matrix.copy( bone.matrixWorld ); } - if ( tail ) tail.nextZ = e; - else list = e; - - e.prevZ = tail; - tail = e; + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); } - p = q; - } - tail.nextZ = null; - inSize *= 2; + } - } while ( numMerges > 1 ); + update() { - return list; + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; -} + // flatten bone matrices to array -// z-order of a point given coords and inverse of the longer side of data bbox -function zOrder( x, y, minX, minY, invSize ) { + for ( let i = 0, il = bones.length; i < il; i ++ ) { - // coords are transformed into non-negative 15-bit integer range - x = 32767 * ( x - minX ) * invSize; - y = 32767 * ( y - minY ) * invSize; + // compute the offset between the current and the original transform - x = ( x | ( x << 8 ) ) & 0x00FF00FF; - x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; - x = ( x | ( x << 2 ) ) & 0x33333333; - x = ( x | ( x << 1 ) ) & 0x55555555; + const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; - y = ( y | ( y << 8 ) ) & 0x00FF00FF; - y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; - y = ( y | ( y << 2 ) ) & 0x33333333; - y = ( y | ( y << 1 ) ) & 0x55555555; + _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + _offsetMatrix.toArray( boneMatrices, i * 16 ); - return x | ( y << 1 ); + } -} + if ( boneTexture !== null ) { -// find the leftmost node of a polygon ring -function getLeftmost( start ) { + boneTexture.needsUpdate = true; - let p = start, - leftmost = start; - do { + } - if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; - p = p.next; + } - } while ( p !== start ); + clone() { - return leftmost; + return new Skeleton( this.bones, this.boneInverses ); -} + } -// check if a point lies within a convex triangle -function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { + computeBoneTexture() { - return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && - ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && - ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; + // 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) -} + let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = ceilPowerOfTwo( size ); + size = Math.max( size, 4 ); -// check if a diagonal between two polygon nodes is valid (lies in polygon interior) -function isValidDiagonal( a, b ) { + const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( this.boneMatrices ); // copy current values - return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges - ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible - ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors - equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + boneTexture.needsUpdate = true; -} + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + this.boneTextureSize = size; -// signed area of a triangle -function area( p, q, r ) { + return this; - return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); + } -} + getBoneByName( name ) { -// check if two points are equal -function equals( p1, p2 ) { + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { - return p1.x === p2.x && p1.y === p2.y; + const bone = this.bones[ i ]; -} + if ( bone.name === name ) { -// check if two segments intersect -function intersects( p1, q1, p2, q2 ) { + return bone; - const o1 = sign( area( p1, q1, p2 ) ); - const o2 = sign( area( p1, q1, q2 ) ); - const o3 = sign( area( p2, q2, p1 ) ); - const o4 = sign( area( p2, q2, q1 ) ); + } - if ( o1 !== o2 && o3 !== o4 ) return true; // general case + } - if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 - if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 - if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 - if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + return undefined; - return false; + } -} + dispose( ) { -// for collinear points p, q, r, check if point q lies on segment pr -function onSegment( p, q, r ) { + if ( this.boneTexture !== null ) { - return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); + this.boneTexture.dispose(); -} + this.boneTexture = null; -function sign( num ) { + } - return num > 0 ? 1 : num < 0 ? - 1 : 0; + } -} + fromJSON( json, bones ) { -// check if a polygon diagonal intersects any polygon segments -function intersectsPolygon( a, b ) { + this.uuid = json.uuid; - let p = a; - do { + for ( let i = 0, l = json.bones.length; i < l; i ++ ) { - if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects( p, p.next, a, b ) ) return true; - p = p.next; + const uuid = json.bones[ i ]; + let bone = bones[ uuid ]; - } while ( p !== a ); + if ( bone === undefined ) { - return false; + console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid ); + bone = new Bone(); -} + } -// check if a polygon diagonal is locally inside the polygon -function locallyInside( a, b ) { + this.bones.push( bone ); + this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); - return area( a.prev, a, a.next ) < 0 ? - area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : - area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; + } -} + this.init(); -// check if the middle point of a polygon diagonal is inside the polygon -function middleInside( a, b ) { + return this; - let p = a, - inside = false; - const px = ( a.x + b.x ) / 2, - py = ( a.y + b.y ) / 2; - do { + } - if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && - ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) - inside = ! inside; - p = p.next; + toJSON() { - } while ( p !== a ); + const data = { + metadata: { + version: 4.5, + type: 'Skeleton', + generator: 'Skeleton.toJSON' + }, + bones: [], + boneInverses: [] + }; - return inside; + data.uuid = this.uuid; -} + const bones = this.bones; + const boneInverses = this.boneInverses; -// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; -// if one belongs to the outer ring and another to a hole, it merges it into a single ring -function splitPolygon( a, b ) { + for ( let i = 0, l = bones.length; i < l; i ++ ) { - const a2 = new Node( a.i, a.x, a.y ), - b2 = new Node( b.i, b.x, b.y ), - an = a.next, - bp = b.prev; + const bone = bones[ i ]; + data.bones.push( bone.uuid ); - a.next = b; - b.prev = a; + const boneInverse = boneInverses[ i ]; + data.boneInverses.push( boneInverse.toArray() ); - a2.next = an; - an.prev = a2; + } + + return data; + + } + +} - b2.next = a2; - a2.prev = b2; +class InstancedBufferAttribute extends BufferAttribute { - bp.next = b2; - b2.prev = bp; + constructor( array, itemSize, normalized, meshPerAttribute = 1 ) { - return b2; + super( array, itemSize, normalized ); -} + this.isInstancedBufferAttribute = true; -// create a node and optionally link it with previous one (in a circular doubly linked list) -function insertNode( i, x, y, last ) { + this.meshPerAttribute = meshPerAttribute; - const p = new Node( i, x, y ); + } - if ( ! last ) { + copy( source ) { - p.prev = p; - p.next = p; + super.copy( source ); - } else { + this.meshPerAttribute = source.meshPerAttribute; - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; + return this; } - return p; + toJSON() { -} + const data = super.toJSON(); -function removeNode( p ) { + data.meshPerAttribute = this.meshPerAttribute; - p.next.prev = p.prev; - p.prev.next = p.next; + data.isInstancedBufferAttribute = true; - if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; - if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; + return data; -} + } -function Node( i, x, y ) { +} - // vertex index in coordinates array - this.i = i; +const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); +const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); - // vertex coordinates - this.x = x; - this.y = y; +const _instanceIntersects = []; - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; +const _mesh = /*@__PURE__*/ new Mesh(); - // z-order curve value - this.z = null; +class InstancedMesh extends Mesh { - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; + constructor( geometry, material, count ) { - // indicates whether this is a steiner point - this.steiner = false; + super( geometry, material ); -} + this.isInstancedMesh = true; -function signedArea( data, start, end, dim ) { + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); + this.instanceColor = null; - let sum = 0; - for ( let i = start, j = end - dim; i < end; i += dim ) { + this.count = count; - sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); - j = i; + this.frustumCulled = false; } - return sum; + copy( source, recursive ) { -} + super.copy( source, recursive ); -const ShapeUtils = { + this.instanceMatrix.copy( source.instanceMatrix ); - // calculate area of the contour polygon + if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); - area: function ( contour ) { + this.count = source.count; - const n = contour.length; - let a = 0.0; + return this; - for ( let p = n - 1, q = 0; q < n; p = q ++ ) { + } - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + getColorAt( index, color ) { - } + color.fromArray( this.instanceColor.array, index * 3 ); - return a * 0.5; + } - }, + getMatrixAt( index, matrix ) { - isClockWise: function ( pts ) { + matrix.fromArray( this.instanceMatrix.array, index * 16 ); - return ShapeUtils.area( pts ) < 0; + } - }, + raycast( raycaster, intersects ) { - triangulateShape: function ( contour, holes ) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; - const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] - const holeIndices = []; // array of hole indices - const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + _mesh.geometry = this.geometry; + _mesh.material = this.material; - removeDupEndPts( contour ); - addContour( vertices, contour ); + if ( _mesh.material === undefined ) return; - // + for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { - let holeIndex = contour.length; + // calculate the world matrix for each instance - holes.forEach( removeDupEndPts ); + this.getMatrixAt( instanceId, _instanceLocalMatrix ); - for ( let i = 0; i < holes.length; i ++ ) { + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); - holeIndices.push( holeIndex ); - holeIndex += holes[ i ].length; - addContour( vertices, holes[ i ] ); + // the mesh represents this single instance - } + _mesh.matrixWorld = _instanceWorldMatrix; - // + _mesh.raycast( raycaster, _instanceIntersects ); - const triangles = Earcut.triangulate( vertices, holeIndices ); + // process the result of raycast - // + for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { - for ( let i = 0; i < triangles.length; i += 3 ) { + const intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); - faces.push( triangles.slice( i, i + 3 ) ); + } - } + _instanceIntersects.length = 0; - return faces; + } } -}; + setColorAt( index, color ) { -function removeDupEndPts( points ) { + if ( this.instanceColor === null ) { - const l = points.length; + this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 ); - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + } - points.pop(); + color.toArray( this.instanceColor.array, index * 3 ); } -} + setMatrixAt( index, matrix ) { -function addContour( vertices, contour ) { + matrix.toArray( this.instanceMatrix.array, index * 16 ); - for ( let i = 0; i < contour.length; i ++ ) { + } - vertices.push( contour[ i ].x ); - vertices.push( contour[ i ].y ); + updateMorphTargets() { } -} + dispose() { -/** - * 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 - * depth: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline (including bevelOffset) is bevel - * bevelOffset: , // how far from shape outline does bevel start - * bevelSegments: , // number of bevel layers - * - * extrudePath: // curve to extrude shape along - * - * UVGenerator: // object that provides UV generator functions - * - * } - */ + this.dispatchEvent( { type: 'dispose' } ); -class ExtrudeGeometry extends BufferGeometry { + } - constructor( shapes, options ) { +} + +class LineBasicMaterial extends Material { + + constructor( parameters ) { super(); - this.type = 'ExtrudeGeometry'; + this.isLineBasicMaterial = true; - this.parameters = { - shapes: shapes, - options: options - }; + this.type = 'LineBasicMaterial'; - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + this.color = new Color( 0xffffff ); - const scope = this; + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - const verticesArray = []; - const uvArray = []; + this.fog = true; - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + this.setValues( parameters ); - const shape = shapes[ i ]; - addShape( shape ); + } - } - // build geometry + copy( source ) { - this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + super.copy( source ); - this.computeVertexNormals(); + this.color.copy( source.color ); - // functions + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - function addShape( shape ) { + this.fog = source.fog; - const placeholder = []; + return this; - // options + } - const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - const steps = options.steps !== undefined ? options.steps : 1; - let depth = options.depth !== undefined ? options.depth : 100; +} - let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; - let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; - let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; - let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; - let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; +const _start$1 = /*@__PURE__*/ new Vector3(); +const _end$1 = /*@__PURE__*/ new Vector3(); +const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _ray$1 = /*@__PURE__*/ new Ray(); +const _sphere$1 = /*@__PURE__*/ new Sphere(); - const extrudePath = options.extrudePath; +class Line extends Object3D { - const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { - // deprecated options + super(); - if ( options.amount !== undefined ) { + this.isLine = true; - console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' ); - depth = options.amount; + this.type = 'Line'; - } + this.geometry = geometry; + this.material = material; - // + this.updateMorphTargets(); - let extrudePts, extrudeByPath = false; - let splineTube, binormal, normal, position2; + } - if ( extrudePath ) { + copy( source, recursive ) { - extrudePts = extrudePath.getSpacedPoints( steps ); + super.copy( source, recursive ); - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + this.material = source.material; + this.geometry = source.geometry; - // SETUP TNB variables + return this; - // TODO1 - have a .isClosed in spline? + } - splineTube = extrudePath.computeFrenetFrames( steps, false ); + computeLineDistances() { - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + const geometry = this.geometry; - binormal = new Vector3(); - normal = new Vector3(); - position2 = new Vector3(); + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - // Safeguards if bevels are not enabled + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; - if ( ! bevelEnabled ) { + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; - bevelOffset = 0; + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); } - // Variables initialization + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - const shapePoints = shape.extractPoints( curveSegments ); + } else { - let vertices = shapePoints.shape; - const holes = shapePoints.holes; + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); - const reverse = ! ShapeUtils.isClockWise( vertices ); + } - if ( reverse ) { + return this; - vertices = vertices.reverse(); + } - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + raycast( raycaster, intersects ) { - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; - const ahole = holes[ h ]; + // Checking boundingSphere distance to ray - if ( ShapeUtils.isClockWise( ahole ) ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - holes[ h ] = ahole.reverse(); + _sphere$1.copy( geometry.boundingSphere ); + _sphere$1.applyMatrix4( matrixWorld ); + _sphere$1.radius += threshold; - } + if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return; - } + // - } + _inverseMatrix$1.copy( matrixWorld ).invert(); + _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; - const faces = ShapeUtils.triangulateShape( vertices, holes ); + const vStart = new Vector3(); + const vEnd = new Vector3(); + const interSegment = new Vector3(); + const interRay = new Vector3(); + const step = this.isLineSegments ? 2 : 1; - /* Vertices */ + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - const contour = vertices; // vertices has all points but contour has only points of circumference + if ( index !== null ) { - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - const ahole = holes[ h ]; + for ( let i = start, l = end - 1; i < l; i += step ) { - vertices = vertices.concat( ahole ); + const a = index.getX( i ); + const b = index.getX( i + 1 ); - } + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - function scalePt2( pt, vec, size ) { + if ( distSq > localThresholdSq ) continue; - if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - return vec.clone().multiplyScalar( size ).add( pt ); + const distance = raycaster.ray.origin.distanceTo( interRay ); - } + if ( distance < raycaster.near || distance > raycaster.far ) continue; - const vlen = vertices.length, flen = faces.length; + intersects.push( { + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - // Find directions for point movement + } ); + } - function getBevelVec( inPt, inPrev, inNext ) { + } else { - // 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. + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + for ( let i = start, l = end - 1; i < l; i += step ) { - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); - const v_prev_x = inPt.x - inPrev.x, - v_prev_y = inPt.y - inPrev.y; - const v_next_x = inNext.x - inPt.x, - v_next_y = inNext.y - inPt.y; + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + if ( distSq > localThresholdSq ) continue; - // check for collinear edges - const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + const distance = raycaster.ray.origin.distanceTo( interRay ); - // not collinear + if ( distance < raycaster.near || distance > raycaster.far ) continue; - // length of vectors for normalizing + intersects.push( { - const v_prev_len = Math.sqrt( v_prev_lensq ); - const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + 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 - // shift adjacent points by unit vectors to the left + } ); - const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + } - const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + } - // scaling factor for v_prev to intersection point + } - const 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 ); + updateMorphTargets() { - // vector from inPt to intersection point + const geometry = this.geometry; - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); - if ( v_trans_lensq <= 2 ) { + if ( keys.length > 0 ) { - return new Vector2( v_trans_x, v_trans_y ); + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - } else { + if ( morphAttribute !== undefined ) { - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - } + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - } else { + const name = morphAttribute[ m ].name || String( m ); - // handle special case of collinear edges + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; - let direction_eq = false; // assumes: opposite + } - if ( v_prev_x > Number.EPSILON ) { + } - if ( v_next_x > Number.EPSILON ) { + } - direction_eq = true; + } - } +} - } else { +const _start = /*@__PURE__*/ new Vector3(); +const _end = /*@__PURE__*/ new Vector3(); - if ( v_prev_x < - Number.EPSILON ) { +class LineSegments extends Line { - if ( v_next_x < - Number.EPSILON ) { + constructor( geometry, material ) { - direction_eq = true; + super( geometry, material ); - } + this.isLineSegments = true; - } else { + this.type = 'LineSegments'; - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + } - direction_eq = true; + computeLineDistances() { - } + const geometry = this.geometry; - } + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - if ( direction_eq ) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; - // 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 ); + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { - } else { + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); - // 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 ); + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); - } + } - } + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + } else { - } + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + } - const contourMovements = []; + return this; - for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + } - if ( j === il ) j = 0; - if ( k === il ) k = 0; +} - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) +class LineLoop extends Line { - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + constructor( geometry, material ) { - } + super( geometry, material ); - const holesMovements = []; - let oneHoleMovements, verticesMovements = contourMovements.concat(); + this.isLineLoop = true; - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + this.type = 'LineLoop'; - const ahole = holes[ h ]; + } - oneHoleMovements = []; +} - for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { +class PointsMaterial extends Material { - if ( j === il ) j = 0; - if ( k === il ) k = 0; + constructor( parameters ) { - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + super(); - } + this.isPointsMaterial = true; - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + this.type = 'PointsMaterial'; - } + this.color = new Color( 0xffffff ); + this.map = null; - // Loop bevelSegments, 1 for the front, 1 for the back + this.alphaMap = null; - for ( let b = 0; b < bevelSegments; b ++ ) { + this.size = 1; + this.sizeAttenuation = true; - //for ( b = bevelSegments; b > 0; b -- ) { + this.fog = true; - const t = b / bevelSegments; - const z = bevelThickness * Math.cos( t * Math.PI / 2 ); - const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + this.setValues( parameters ); - // contract shape + } - for ( let i = 0, il = contour.length; i < il; i ++ ) { + copy( source ) { - const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + super.copy( source ); - v( vert.x, vert.y, - z ); + this.color.copy( source.color ); - } + this.map = source.map; - // expand holes + this.alphaMap = source.alphaMap; - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - const ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + this.fog = source.fog; - for ( let i = 0, il = ahole.length; i < il; i ++ ) { + return this; - const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + } - v( vert.x, vert.y, - z ); +} - } +const _inverseMatrix = /*@__PURE__*/ new Matrix4(); +const _ray = /*@__PURE__*/ new Ray(); +const _sphere = /*@__PURE__*/ new Sphere(); +const _position$2 = /*@__PURE__*/ new Vector3(); - } +class Points extends Object3D { - } + constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) { - const bs = bevelSize + bevelOffset; + super(); - // Back facing vertices + this.isPoints = true; - for ( let i = 0; i < vlen; i ++ ) { + this.type = 'Points'; - const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + this.geometry = geometry; + this.material = material; - if ( ! extrudeByPath ) { + this.updateMorphTargets(); - v( vert.x, vert.y, 0 ); + } - } else { + copy( source, recursive ) { - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + super.copy( source, recursive ); - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + this.material = source.material; + this.geometry = source.geometry; - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + return this; - v( position2.x, position2.y, position2.z ); + } - } + raycast( raycaster, intersects ) { - } + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; - // Add stepped vertices... - // Including front facing vertices + // Checking boundingSphere distance to ray - for ( let s = 1; s <= steps; s ++ ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - for ( let i = 0; i < vlen; i ++ ) { + _sphere.copy( geometry.boundingSphere ); + _sphere.applyMatrix4( matrixWorld ); + _sphere.radius += threshold; - const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; - if ( ! extrudeByPath ) { + // + + _inverseMatrix.copy( matrixWorld ).invert(); + _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); - v( vert.x, vert.y, depth / steps * s ); + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; - } else { + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + if ( index !== null ) { - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + for ( let i = start, il = end; i < il; i ++ ) { - v( position2.x, position2.y, position2.z ); + const a = index.getX( i ); - } + _position$2.fromBufferAttribute( positionAttribute, a ); - } + testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); } + } else { - // Add bevel segments planes - - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( let b = bevelSegments - 1; b >= 0; b -- ) { + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); - const t = b / bevelSegments; - const z = bevelThickness * Math.cos( t * Math.PI / 2 ); - const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + for ( let i = start, l = end; i < l; i ++ ) { - // contract shape + _position$2.fromBufferAttribute( positionAttribute, i ); - for ( let i = 0, il = contour.length; i < il; i ++ ) { + testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); - const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, depth + z ); + } - } + } - // expand holes + } - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + updateMorphTargets() { - const ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + const geometry = this.geometry; - for ( let i = 0, il = ahole.length; i < il; i ++ ) { + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); - const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + if ( keys.length > 0 ) { - if ( ! extrudeByPath ) { + const morphAttribute = morphAttributes[ keys[ 0 ] ]; - v( vert.x, vert.y, depth + z ); + if ( morphAttribute !== undefined ) { - } else { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - } + const name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - /* Faces */ - - // Top and bottom faces - - buildLidFaces(); - - // Sides faces - - buildSideFaces(); + } + } - ///// Internal functions +} - function buildLidFaces() { +function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { - const start = verticesArray.length / 3; + const rayPointDistanceSq = _ray.distanceSqToPoint( point ); - if ( bevelEnabled ) { + if ( rayPointDistanceSq < localThresholdSq ) { - let layer = 0; // steps + 1 - let offset = vlen * layer; + const intersectPoint = new Vector3(); - // Bottom faces + _ray.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); - for ( let i = 0; i < flen; i ++ ) { + const distance = raycaster.ray.origin.distanceTo( intersectPoint ); - const face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + if ( distance < raycaster.near || distance > raycaster.far ) return; - } + intersects.push( { - layer = steps + bevelSegments * 2; - offset = vlen * layer; + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + object: object - // Top faces + } ); - for ( let i = 0; i < flen; i ++ ) { + } - const face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); +} - } +class VideoTexture extends Texture { - } else { + constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - // Bottom faces + super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - for ( let i = 0; i < flen; i ++ ) { + this.isVideoTexture = true; - const face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; - } + this.generateMipmaps = false; - // Top faces + const scope = this; - for ( let i = 0; i < flen; i ++ ) { + function updateVideo() { - const face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + scope.needsUpdate = true; + video.requestVideoFrameCallback( updateVideo ); - } + } - } + if ( 'requestVideoFrameCallback' in video ) { - scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + video.requestVideoFrameCallback( updateVideo ); - } + } - // Create faces for the z-sides of the shape + } - function buildSideFaces() { + clone() { - const start = verticesArray.length / 3; - let layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + return new this.constructor( this.image ).copy( this ); - for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + } - const ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + update() { - //, true - layeroffset += ahole.length; + const video = this.image; + const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; - } + if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { + this.needsUpdate = true; - scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + } + } - } +} - function sidewalls( contour, layeroffset ) { +class FramebufferTexture extends Texture { - let i = contour.length; + constructor( width, height, format ) { - while ( -- i >= 0 ) { + super( { width, height } ); - const j = i; - let k = i - 1; - if ( k < 0 ) k = contour.length - 1; + this.isFramebufferTexture = true; - //console.log('b', i,j, i-1, k,vertices.length); + this.format = format; - for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; - const slen1 = vlen * s; - const slen2 = vlen * ( s + 1 ); + this.generateMipmaps = false; - const a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + this.needsUpdate = true; - f4( a, b, c, d ); + } - } +} - } +class CompressedTexture extends Texture { - } + constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - function v( x, y, z ) { + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - placeholder.push( x ); - placeholder.push( y ); - placeholder.push( z ); + this.isCompressedTexture = true; - } + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - function f3( a, b, c ) { + this.flipY = false; - addVertex( a ); - addVertex( b ); - addVertex( c ); + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files - const nextIndex = verticesArray.length / 3; - const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + this.generateMipmaps = false; - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); + } - } +} - function f4( a, b, c, d ) { +class CanvasTexture extends Texture { - addVertex( a ); - addVertex( b ); - addVertex( d ); + constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - addVertex( b ); - addVertex( c ); - addVertex( d ); + super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.isCanvasTexture = true; - const nextIndex = verticesArray.length / 3; - const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + this.needsUpdate = true; - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 3 ] ); + } - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); - addUV( uvs[ 3 ] ); +} - } +/** + * Extensible curve object. + * + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following curves inherit from THREE.Curve: + * + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve + * + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * + * A series of curves can be represented as a THREE.CurvePath. + * + **/ - function addVertex( index ) { +class Curve { - verticesArray.push( placeholder[ index * 3 + 0 ] ); - verticesArray.push( placeholder[ index * 3 + 1 ] ); - verticesArray.push( placeholder[ index * 3 + 2 ] ); + constructor() { - } + this.type = 'Curve'; + this.arcLengthDivisions = 200; - function addUV( vector2 ) { + } - uvArray.push( vector2.x ); - uvArray.push( vector2.y ); + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] - } + getPoint( /* t, optionalTarget */ ) { - } + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; } - toJSON() { - - const data = BufferGeometry.prototype.toJSON.call( this ); + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - const shapes = this.parameters.shapes; - const options = this.parameters.options; + getPointAt( u, optionalTarget ) { - return toJSON( shapes, options, data ); + const t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); } -} + // Get sequence of points using getPoint( t ) -const WorldUVGenerator = { + getPoints( divisions = 5 ) { - generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + const points = []; - const a_x = vertices[ indexA * 3 ]; - const a_y = vertices[ indexA * 3 + 1 ]; - const b_x = vertices[ indexB * 3 ]; - const b_y = vertices[ indexB * 3 + 1 ]; - const c_x = vertices[ indexC * 3 ]; - const c_y = vertices[ indexC * 3 + 1 ]; + for ( let d = 0; d <= divisions; d ++ ) { - return [ - new Vector2( a_x, a_y ), - new Vector2( b_x, b_y ), - new Vector2( c_x, c_y ) - ]; + points.push( this.getPoint( d / divisions ) ); - }, + } - generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + return points; - const a_x = vertices[ indexA * 3 ]; - const a_y = vertices[ indexA * 3 + 1 ]; - const a_z = vertices[ indexA * 3 + 2 ]; - const b_x = vertices[ indexB * 3 ]; - const b_y = vertices[ indexB * 3 + 1 ]; - const b_z = vertices[ indexB * 3 + 2 ]; - const c_x = vertices[ indexC * 3 ]; - const c_y = vertices[ indexC * 3 + 1 ]; - const c_z = vertices[ indexC * 3 + 2 ]; - const d_x = vertices[ indexD * 3 ]; - const d_y = vertices[ indexD * 3 + 1 ]; - const d_z = vertices[ indexD * 3 + 2 ]; + } - if ( Math.abs( a_y - b_y ) < 0.01 ) { + // Get sequence of points using getPointAt( u ) - 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 ) - ]; + getSpacedPoints( divisions = 5 ) { - } else { + const points = []; - 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 ) - ]; + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPointAt( d / divisions ) ); } + return points; + } -}; + // Get total curve arc length -function toJSON( shapes, options, data ) { + getLength() { - data.shapes = []; + const lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - if ( Array.isArray( shapes ) ) { + } - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + // Get list of cumulative segment lengths - const shape = shapes[ i ]; + getLengths( divisions = this.arcLengthDivisions ) { - data.shapes.push( shape.uuid ); + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { + + return this.cacheArcLengths; } - } else { + this.needsUpdate = false; - data.shapes.push( shapes.uuid ); + const cache = []; + let current, last = this.getPoint( 0 ); + let sum = 0; - } + cache.push( 0 ); - if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); + for ( let p = 1; p <= divisions; p ++ ) { - return data; + current = this.getPoint( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; -} + } -class IcosahedronGeometry extends PolyhedronGeometry { + this.cacheArcLengths = cache; - constructor( radius = 1, detail = 0 ) { + return cache; // { sums: cache, sum: sum }; Sum is in the last element. - const t = ( 1 + Math.sqrt( 5 ) ) / 2; + } - const 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 - ]; + updateArcLengths() { - const 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 - ]; + this.needsUpdate = true; + this.getLengths(); - super( vertices, indices, radius, detail ); + } - this.type = 'IcosahedronGeometry'; + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - this.parameters = { - radius: radius, - detail: detail - }; + getUtoTmapping( u, distance ) { - } + const arcLengths = this.getLengths(); -} + let i = 0; + const il = arcLengths.length; -class LatheGeometry extends BufferGeometry { + let targetArcLength; // The targeted u distance value to get - constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { + if ( distance ) { - super(); + targetArcLength = distance; - this.type = 'LatheGeometry'; + } else { - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + targetArcLength = u * arcLengths[ il - 1 ]; - segments = Math.floor( segments ); + } - // clamp phiLength so it's in range of [ 0, 2PI ] + // binary search for the index with largest value smaller than target u distance - phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 ); + let low = 0, high = il - 1, comparison; - // buffers + while ( low <= high ) { - const indices = []; - const vertices = []; - const uvs = []; + 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 - // helper variables + comparison = arcLengths[ i ] - targetArcLength; - const inverseSegments = 1.0 / segments; - const vertex = new Vector3(); - const uv = new Vector2(); + if ( comparison < 0 ) { - // generate vertices and uvs + low = i + 1; - for ( let i = 0; i <= segments; i ++ ) { + } else if ( comparison > 0 ) { - const phi = phiStart + i * inverseSegments * phiLength; + high = i - 1; - const sin = Math.sin( phi ); - const cos = Math.cos( phi ); + } else { - for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { + high = i; + break; - // vertex + // DONE - vertex.x = points[ j ].x * sin; - vertex.y = points[ j ].y; - vertex.z = points[ j ].x * cos; + } - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // uv + i = high; - uv.x = i / segments; - uv.y = j / ( points.length - 1 ); + if ( arcLengths[ i ] === targetArcLength ) { - uvs.push( uv.x, uv.y ); + return i / ( il - 1 ); + } - } + // we could get finer grain at lengths, or use simple interpolation between two points - } + const lengthBefore = arcLengths[ i ]; + const lengthAfter = arcLengths[ i + 1 ]; - // indices + const segmentLength = lengthAfter - lengthBefore; - for ( let i = 0; i < segments; i ++ ) { + // determine where we are between the 'before' and 'after' points - for ( let j = 0; j < ( points.length - 1 ); j ++ ) { + const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - const base = j + i * points.length; + // add that fractional amount to t - const a = base; - const b = base + points.length; - const c = base + points.length + 1; - const d = base + 1; + const t = ( i + segmentFraction ) / ( il - 1 ); - // faces + return t; - indices.push( a, b, d ); - indices.push( b, c, d ); + } - } + // 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 - } + getTangent( t, optionalTarget ) { - // build geometry + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + // Capping in case of danger - // generate normals + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - this.computeVertexNormals(); + const pt1 = this.getPoint( t1 ); + const pt2 = this.getPoint( t2 ); - // 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). + const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + + tangent.copy( pt2 ).sub( pt1 ).normalize(); - if ( phiLength === Math.PI * 2 ) { + return tangent; - const normals = this.attributes.normal.array; - const n1 = new Vector3(); - const n2 = new Vector3(); - const n = new Vector3(); + } - // this is the buffer offset for the last line of vertices + getTangentAt( u, optionalTarget ) { - const base = segments * points.length * 3; + const t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); - for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) { + } - // select the normal of the vertex in the first line + computeFrenetFrames( segments, closed ) { - n1.x = normals[ j + 0 ]; - n1.y = normals[ j + 1 ]; - n1.z = normals[ j + 2 ]; + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf - // select the normal of the vertex in the last line + const normal = new Vector3(); - n2.x = normals[ base + j + 0 ]; - n2.y = normals[ base + j + 1 ]; - n2.z = normals[ base + j + 2 ]; + const tangents = []; + const normals = []; + const binormals = []; - // average normals + const vec = new Vector3(); + const mat = new Matrix4(); - n.addVectors( n1, n2 ).normalize(); + // compute the tangent vectors for each segment on the curve - // assign the new values to both normals + for ( let i = 0; i <= segments; i ++ ) { - 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; + const u = i / segments; - } + tangents[ i ] = this.getTangentAt( u, new Vector3() ); } - } + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component -} + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs( tangents[ 0 ].x ); + const ty = Math.abs( tangents[ 0 ].y ); + const tz = Math.abs( tangents[ 0 ].z ); -class OctahedronGeometry extends PolyhedronGeometry { + if ( tx <= min ) { - constructor( radius = 1, detail = 0 ) { + min = tx; + normal.set( 1, 0, 0 ); - const vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, - 0, - 1, 0, 0, 0, 1, 0, 0, - 1 - ]; + } - const 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 - ]; + if ( ty <= min ) { - super( vertices, indices, radius, detail ); + min = ty; + normal.set( 0, 1, 0 ); - this.type = 'OctahedronGeometry'; + } - this.parameters = { - radius: radius, - detail: detail - }; + if ( tz <= min ) { - } + normal.set( 0, 0, 1 ); -} + } -/** - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html - */ + vec.crossVectors( tangents[ 0 ], normal ).normalize(); -function ParametricGeometry( func, slices, stacks ) { + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - BufferGeometry.call( this ); - this.type = 'ParametricGeometry'; + // compute the slowly-varying normal and binormal vectors for each segment on the curve - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + for ( let i = 1; i <= segments; i ++ ) { - // buffers + normals[ i ] = normals[ i - 1 ].clone(); - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + binormals[ i ] = binormals[ i - 1 ].clone(); - const EPS = 0.00001; + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); - const normal = new Vector3(); + if ( vec.length() > Number.EPSILON ) { - const p0 = new Vector3(), p1 = new Vector3(); - const pu = new Vector3(), pv = new Vector3(); + vec.normalize(); - if ( func.length < 3 ) { + const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors - console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' ); + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - } + } - // generate vertices, normals and uvs + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - const sliceCount = slices + 1; + } - for ( let i = 0; i <= stacks; i ++ ) { + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - const v = i / stacks; + if ( closed === true ) { - for ( let j = 0; j <= slices; j ++ ) { + let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; - const u = j / slices; + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { - // vertex + theta = - theta; - func( u, v, p0 ); - vertices.push( p0.x, p0.y, p0.z ); + } - // normal + for ( let i = 1; i <= segments; i ++ ) { - // approximate tangent vectors via finite differences + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - if ( u - EPS >= 0 ) { + } - func( u - EPS, v, p1 ); - pu.subVectors( p0, p1 ); + } - } else { + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; - func( u + EPS, v, p1 ); - pu.subVectors( p1, p0 ); + } - } + clone() { - if ( v - EPS >= 0 ) { + return new this.constructor().copy( this ); - func( u, v - EPS, p1 ); - pv.subVectors( p0, p1 ); + } - } else { + copy( source ) { - func( u, v + EPS, p1 ); - pv.subVectors( p1, p0 ); + this.arcLengthDivisions = source.arcLengthDivisions; - } + return this; - // cross product of tangent vectors returns surface normal + } - normal.crossVectors( pu, pv ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + toJSON() { - // uv + const data = { + metadata: { + version: 4.5, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; - uvs.push( u, v ); + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; - } + return data; } - // generate indices - - for ( let i = 0; i < stacks; i ++ ) { + fromJSON( json ) { - for ( let j = 0; j < slices; j ++ ) { + this.arcLengthDivisions = json.arcLengthDivisions; - const a = i * sliceCount + j; - const b = i * sliceCount + j + 1; - const c = ( i + 1 ) * sliceCount + j + 1; - const d = ( i + 1 ) * sliceCount + j; + return this; - // faces one and two + } - indices.push( a, b, d ); - indices.push( b, c, d ); +} - } +class EllipseCurve extends Curve { - } + constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { - // build geometry + super(); - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.isEllipseCurve = true; -} + this.type = 'EllipseCurve'; -ParametricGeometry.prototype = Object.create( BufferGeometry.prototype ); -ParametricGeometry.prototype.constructor = ParametricGeometry; + this.aX = aX; + this.aY = aY; -class RingGeometry extends BufferGeometry { + this.xRadius = xRadius; + this.yRadius = yRadius; - constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; - super(); + this.aClockwise = aClockwise; - this.type = 'RingGeometry'; + this.aRotation = aRotation; - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - thetaSegments = Math.max( 3, thetaSegments ); - phiSegments = Math.max( 1, phiSegments ); + getPoint( t, optionalTarget ) { - // buffers + const point = optionalTarget || new Vector2(); - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - // some helper variables + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - let radius = innerRadius; - const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - const vertex = new Vector3(); - const uv = new Vector2(); + if ( deltaAngle < Number.EPSILON ) { - // generate vertices, normals and uvs + if ( samePoints ) { - for ( let j = 0; j <= phiSegments; j ++ ) { + deltaAngle = 0; - for ( let i = 0; i <= thetaSegments; i ++ ) { + } else { - // values are generate from the inside of the ring to the outside + deltaAngle = twoPi; - const segment = thetaStart + i / thetaSegments * thetaLength; + } - // vertex + } - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + if ( this.aClockwise === true && ! samePoints ) { - vertices.push( vertex.x, vertex.y, vertex.z ); + if ( deltaAngle === twoPi ) { - // normal + deltaAngle = - twoPi; - normals.push( 0, 0, 1 ); + } else { - // uv + deltaAngle = deltaAngle - twoPi; - uv.x = ( vertex.x / outerRadius + 1 ) / 2; - uv.y = ( vertex.y / outerRadius + 1 ) / 2; + } - uvs.push( uv.x, uv.y ); + } - } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos( angle ); + let y = this.aY + this.yRadius * Math.sin( angle ); - // increase the radius for next row of vertices + if ( this.aRotation !== 0 ) { - radius += radiusStep; + const cos = Math.cos( this.aRotation ); + const sin = Math.sin( this.aRotation ); - } + const tx = x - this.aX; + const ty = y - this.aY; - // indices + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; - for ( let j = 0; j < phiSegments; j ++ ) { + } - const thetaSegmentLevel = j * ( thetaSegments + 1 ); + return point.set( x, y ); - for ( let i = 0; i < thetaSegments; i ++ ) { + } - const segment = i + thetaSegmentLevel; + copy( source ) { - const a = segment; - const b = segment + thetaSegments + 1; - const c = segment + thetaSegments + 2; - const d = segment + 1; + super.copy( source ); - // faces + this.aX = source.aX; + this.aY = source.aY; - indices.push( a, b, d ); - indices.push( b, c, d ); + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; - } + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; - } + this.aClockwise = source.aClockwise; - // build geometry + this.aRotation = source.aRotation; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + return this; } -} - -class ShapeGeometry extends BufferGeometry { + toJSON() { - constructor( shapes, curveSegments = 12 ) { + const data = super.toJSON(); - super(); - this.type = 'ShapeGeometry'; + data.aX = this.aX; + data.aY = this.aY; - this.parameters = { - shapes: shapes, - curveSegments: curveSegments - }; + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; - // buffers + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + data.aClockwise = this.aClockwise; - // helper variables + data.aRotation = this.aRotation; - let groupStart = 0; - let groupCount = 0; + return data; - // allow single and array values for "shapes" parameter + } - if ( Array.isArray( shapes ) === false ) { + fromJSON( json ) { - addShape( shapes ); + super.fromJSON( json ); - } else { + this.aX = json.aX; + this.aY = json.aY; - for ( let i = 0; i < shapes.length; i ++ ) { + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; - addShape( shapes[ i ] ); + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; - this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + this.aClockwise = json.aClockwise; - groupStart += groupCount; - groupCount = 0; + this.aRotation = json.aRotation; - } + return this; - } + } - // build geometry +} - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); +class ArcCurve extends EllipseCurve { + constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - // helper functions + super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - function addShape( shape ) { + this.isArcCurve = true; - const indexOffset = vertices.length / 3; - const points = shape.extractPoints( curveSegments ); + this.type = 'ArcCurve'; - let shapeVertices = points.shape; - const shapeHoles = points.holes; + } - // check direction of vertices +} - if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { +/** + * 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 + */ - shapeVertices = shapeVertices.reverse(); - } +/* +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 - for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { +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. +*/ - const shapeHole = shapeHoles[ i ]; +function CubicPoly() { - if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; - shapeHoles[ i ] = shapeHole.reverse(); + /* + * 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. + */ + function init( x0, x1, t0, t1 ) { - } + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; - } + } - const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); + return { - // join vertices of inner and outer paths to a single array + initCatmullRom: function ( x0, x1, x2, x3, tension ) { - for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); - const shapeHole = shapeHoles[ i ]; - shapeVertices = shapeVertices.concat( shapeHole ); + }, - } + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { - // vertices, normals, uvs + // compute tangents when parameterized in [t1,t2] + let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; - const vertex = shapeVertices[ i ]; + init( x1, x2, t1, t2 ); - vertices.push( vertex.x, vertex.y, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( vertex.x, vertex.y ); // world uvs + }, - } + calc: function ( t ) { - // incides + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; - for ( let i = 0, l = faces.length; i < l; i ++ ) { + } - const face = faces[ i ]; + }; - const a = face[ 0 ] + indexOffset; - const b = face[ 1 ] + indexOffset; - const c = face[ 2 ] + indexOffset; +} - indices.push( a, b, c ); - groupCount += 3; +// - } +const tmp = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); - } +class CatmullRomCurve3 extends Curve { - } + constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { - toJSON() { + super(); - const data = BufferGeometry.prototype.toJSON.call( this ); + this.isCatmullRomCurve3 = true; - const shapes = this.parameters.shapes; + this.type = 'CatmullRomCurve3'; - return toJSON$1( shapes, data ); + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; } -} + getPoint( t, optionalTarget = new Vector3() ) { -function toJSON$1( shapes, data ) { + const point = optionalTarget; - data.shapes = []; + const points = this.points; + const l = points.length; - if ( Array.isArray( shapes ) ) { + const p = ( l - ( this.closed ? 0 : 1 ) ) * t; + let intPoint = Math.floor( p ); + let weight = p - intPoint; - for ( let i = 0, l = shapes.length; i < l; i ++ ) { + if ( this.closed ) { - const shape = shapes[ i ]; + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; - data.shapes.push( shape.uuid ); + } else if ( weight === 0 && intPoint === l - 1 ) { - } + intPoint = l - 2; + weight = 1; - } else { + } - data.shapes.push( shapes.uuid ); + let p0, p3; // 4 points (p1 & p2 defined below) - } + if ( this.closed || intPoint > 0 ) { - return data; + p0 = points[ ( intPoint - 1 ) % l ]; -} + } else { -class SphereGeometry extends BufferGeometry { + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; - constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { + } - super(); - this.type = 'SphereGeometry'; + const p1 = points[ intPoint % l ]; + const p2 = points[ ( intPoint + 1 ) % l ]; - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + if ( this.closed || intPoint + 2 < l ) { - widthSegments = Math.max( 3, Math.floor( widthSegments ) ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) ); + p3 = points[ ( intPoint + 2 ) % l ]; - const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + } else { - let index = 0; - const grid = []; + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; - const vertex = new Vector3(); - const normal = new Vector3(); + } - // buffers + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + // init Centripetal / Chordal Catmull-Rom + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); - // generate vertices, normals and uvs + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; - for ( let iy = 0; iy <= heightSegments; iy ++ ) { + 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 ); - const verticesRow = []; + } else if ( this.curveType === 'catmullrom' ) { - const v = iy / heightSegments; + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); - // special case for the poles + } - let uOffset = 0; + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); - if ( iy == 0 && thetaStart == 0 ) { + return point; - uOffset = 0.5 / widthSegments; + } - } else if ( iy == heightSegments && thetaEnd == Math.PI ) { + copy( source ) { - uOffset = - 0.5 / widthSegments; + super.copy( source ); - } + this.points = []; - for ( let ix = 0; ix <= widthSegments; ix ++ ) { + for ( let i = 0, l = source.points.length; i < l; i ++ ) { - const u = ix / widthSegments; + const point = source.points[ i ]; - // vertex + this.points.push( point.clone() ); - vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); - vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + } - vertices.push( vertex.x, vertex.y, vertex.z ); + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; - // normal + return this; - normal.copy( vertex ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + } - // uv + toJSON() { - uvs.push( u + uOffset, 1 - v ); + const data = super.toJSON(); - verticesRow.push( index ++ ); + data.points = []; - } + for ( let i = 0, l = this.points.length; i < l; i ++ ) { - grid.push( verticesRow ); + const point = this.points[ i ]; + data.points.push( point.toArray() ); } - // indices + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; - for ( let iy = 0; iy < heightSegments; iy ++ ) { + return data; - for ( let ix = 0; ix < widthSegments; ix ++ ) { + } - const a = grid[ iy ][ ix + 1 ]; - const b = grid[ iy ][ ix ]; - const c = grid[ iy + 1 ][ ix ]; - const d = grid[ iy + 1 ][ ix + 1 ]; + fromJSON( json ) { - if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); - if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + super.fromJSON( json ); - } + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); } - // build geometry + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + return this; } } -class TetrahedronGeometry extends PolyhedronGeometry { - - constructor( radius = 1, detail = 0 ) { +/** + * Bezier Curves formulas obtained from + * https://en.wikipedia.org/wiki/B%C3%A9zier_curve + */ - const vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; +function CatmullRom( t, p0, p1, p2, p3 ) { - const indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + const v0 = ( p2 - p0 ) * 0.5; + const v1 = ( p3 - p1 ) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - super( vertices, indices, radius, detail ); +} - this.type = 'TetrahedronGeometry'; +// - this.parameters = { - radius: radius, - detail: detail - }; +function QuadraticBezierP0( t, p ) { - } + const k = 1 - t; + return k * k * p; } -/** - * 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 (including bevelOffset) is bevel - * bevelOffset: // how far from text outline does bevel start - * } - */ +function QuadraticBezierP1( t, p ) { -class TextGeometry extends ExtrudeGeometry { + return 2 * ( 1 - t ) * t * p; - constructor( text, parameters = {} ) { +} - const font = parameters.font; +function QuadraticBezierP2( t, p ) { - if ( ! ( font && font.isFont ) ) { + return t * t * p; - console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new BufferGeometry(); +} - } +function QuadraticBezier( t, p0, p1, p2 ) { - const shapes = font.generateShapes( text, parameters.size ); + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); - // translate parameters to ExtrudeGeometry API +} - parameters.depth = parameters.height !== undefined ? parameters.height : 50; +// - // defaults +function CubicBezierP0( t, p ) { - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + const k = 1 - t; + return k * k * k * p; - super( shapes, parameters ); +} - this.type = 'TextGeometry'; +function CubicBezierP1( t, p ) { - } + const k = 1 - t; + return 3 * k * k * t * p; } -class TorusGeometry extends BufferGeometry { +function CubicBezierP2( t, p ) { - constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) { + return 3 * ( 1 - t ) * t * t * p; - super(); - this.type = 'TorusGeometry'; +} - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; +function CubicBezierP3( t, p ) { - radialSegments = Math.floor( radialSegments ); - tubularSegments = Math.floor( tubularSegments ); + return t * t * t * p; - // buffers +} - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; +function CubicBezier( t, p0, p1, p2, p3 ) { - // helper variables + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); - const center = new Vector3(); - const vertex = new Vector3(); - const normal = new Vector3(); +} - // generate vertices, normals and uvs +class CubicBezierCurve extends Curve { - for ( let j = 0; j <= radialSegments; j ++ ) { + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { - for ( let i = 0; i <= tubularSegments; i ++ ) { + super(); - const u = i / tubularSegments * arc; - const v = j / radialSegments * Math.PI * 2; + this.isCubicBezierCurve = true; - // vertex + this.type = 'CubicBezierCurve'; - 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 ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // normal + getPoint( t, optionalTarget = new Vector2() ) { - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); - normal.subVectors( vertex, center ).normalize(); + const point = optionalTarget; - normals.push( normal.x, normal.y, normal.z ); + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - // uv + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + return point; - } + } - } + copy( source ) { - // generate indices + super.copy( source ); - for ( let j = 1; j <= radialSegments; j ++ ) { + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); - for ( let i = 1; i <= tubularSegments; i ++ ) { + return this; - // indices + } - const a = ( tubularSegments + 1 ) * j + i - 1; - const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; - const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; - const d = ( tubularSegments + 1 ) * j + i; + toJSON() { - // faces + const data = super.toJSON(); - indices.push( a, b, d ); - indices.push( b, c, d ); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - } + return data; - } + } - // build geometry + fromJSON( json ) { - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; } } -class TorusKnotGeometry extends BufferGeometry { +class CubicBezierCurve3 extends Curve { - constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { super(); - this.type = 'TorusKnotGeometry'; - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + this.isCubicBezierCurve3 = true; - tubularSegments = Math.floor( tubularSegments ); - radialSegments = Math.floor( radialSegments ); + this.type = 'CubicBezierCurve3'; - // buffers + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - const indices = []; - const vertices = []; - const normals = []; - const uvs = []; + } - // helper variables + getPoint( t, optionalTarget = new Vector3() ) { - const vertex = new Vector3(); - const normal = new Vector3(); + const point = optionalTarget; - const P1 = new Vector3(); - const P2 = new Vector3(); + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - const B = new Vector3(); - const T = new Vector3(); - const N = new Vector3(); + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); - // generate vertices, normals and uvs + return point; - for ( let i = 0; i <= tubularSegments; ++ i ) { + } - // the radian "u" is used to calculate the position on the torus curve of the current tubular segement + copy( source ) { - const u = i / tubularSegments * p * Math.PI * 2; + super.copy( source ); - // 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 + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); - calculatePositionOnCurve( u, p, q, radius, P1 ); - calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + return this; - // calculate orthonormal basis + } - T.subVectors( P2, P1 ); - N.addVectors( P2, P1 ); - B.crossVectors( T, N ); - N.crossVectors( B, T ); + toJSON() { - // normalize B, N. T can be ignored, we don't use it + const data = super.toJSON(); - B.normalize(); - N.normalize(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - for ( let j = 0; j <= radialSegments; ++ j ) { + return data; - // 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. + } - const v = j / radialSegments * Math.PI * 2; - const cx = - tube * Math.cos( v ); - const cy = tube * Math.sin( v ); + fromJSON( json ) { - // 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 + super.fromJSON( json ); - 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 ); + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + return this; - // 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.push( normal.x, normal.y, normal.z ); +class LineCurve extends Curve { - // uv + constructor( v1 = new Vector2(), v2 = new Vector2() ) { - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + super(); - } + this.isLineCurve = true; - } + this.type = 'LineCurve'; - // generate indices + this.v1 = v1; + this.v2 = v2; - for ( let j = 1; j <= tubularSegments; j ++ ) { + } - for ( let i = 1; i <= radialSegments; i ++ ) { + getPoint( t, optionalTarget = new Vector2() ) { - // indices + const point = optionalTarget; - const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - const b = ( radialSegments + 1 ) * j + ( i - 1 ); - const c = ( radialSegments + 1 ) * j + i; - const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + if ( t === 1 ) { - // faces + point.copy( this.v2 ); - indices.push( a, b, d ); - indices.push( b, c, d ); + } else { - } + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); } - // build geometry + return point; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + } - // this function calculates the current position on the torus curve + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { - function calculatePositionOnCurve( u, p, q, radius, position ) { + return this.getPoint( u, optionalTarget ); - const cu = Math.cos( u ); - const su = Math.sin( u ); - const quOverP = q / p * u; - const 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; + getTangent( t, optionalTarget ) { - } + const tangent = optionalTarget || new Vector2(); + + tangent.copy( this.v2 ).sub( this.v1 ).normalize(); + + return tangent; } -} + copy( source ) { -class TubeGeometry extends BufferGeometry { + super.copy( source ); - constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - super(); - this.type = 'TubeGeometry'; + return this; - this.parameters = { - path: path, - tubularSegments: tubularSegments, - radius: radius, - radialSegments: radialSegments, - closed: closed - }; + } - const frames = path.computeFrenetFrames( tubularSegments, closed ); + toJSON() { - // expose internals + const data = super.toJSON(); - this.tangents = frames.tangents; - this.normals = frames.normals; - this.binormals = frames.binormals; + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - // helper variables + return data; - const vertex = new Vector3(); - const normal = new Vector3(); - const uv = new Vector2(); - let P = new Vector3(); + } - // buffer + fromJSON( json ) { - const vertices = []; - const normals = []; - const uvs = []; - const indices = []; + super.fromJSON( json ); - // create buffer data + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - generateBufferData(); + return this; - // build geometry + } - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); +} - // functions +class LineCurve3 extends Curve { - function generateBufferData() { + constructor( v1 = new Vector3(), v2 = new Vector3() ) { - for ( let i = 0; i < tubularSegments; i ++ ) { + super(); - generateSegment( i ); + this.isLineCurve3 = true; - } + this.type = 'LineCurve3'; - // if the geometry is not closed, generate the last row of vertices and normals - // at the regular position on the given path - // - // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + this.v1 = v1; + this.v2 = v2; - generateSegment( ( closed === false ) ? tubularSegments : 0 ); + } + getPoint( t, optionalTarget = new Vector3() ) { - // uvs are generated in a separate function. - // this makes it easy compute correct values for closed geometries + const point = optionalTarget; - generateUVs(); + if ( t === 1 ) { - // finally create faces + point.copy( this.v2 ); - generateIndices(); + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); } - function generateSegment( i ) { + return point; - // we use getPointAt to sample evenly distributed points from the given path + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { - P = path.getPointAt( i / tubularSegments, P ); + return this.getPoint( u, optionalTarget ); - // retrieve corresponding normal and binormal + } + copy( source ) { - const N = frames.normals[ i ]; - const B = frames.binormals[ i ]; + super.copy( source ); - // generate normals and vertices for the current segment + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - for ( let j = 0; j <= radialSegments; j ++ ) { + return this; - const v = j / radialSegments * Math.PI * 2; + } + toJSON() { - const sin = Math.sin( v ); - const cos = - Math.cos( v ); + const data = super.toJSON(); - // normal + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - normal.x = ( cos * N.x + sin * B.x ); - normal.y = ( cos * N.y + sin * B.y ); - normal.z = ( cos * N.z + sin * B.z ); - normal.normalize(); + return data; - normals.push( normal.x, normal.y, normal.z ); + } + fromJSON( json ) { - // vertex + super.fromJSON( json ); - vertex.x = P.x + radius * normal.x; - vertex.y = P.y + radius * normal.y; - vertex.z = P.z + radius * normal.z; + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + return this; - } + } - } +} - function generateIndices() { +class QuadraticBezierCurve extends Curve { - for ( let j = 1; j <= tubularSegments; j ++ ) { + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { - for ( let i = 1; i <= radialSegments; i ++ ) { + super(); - const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - const b = ( radialSegments + 1 ) * j + ( i - 1 ); - const c = ( radialSegments + 1 ) * j + i; - const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + this.isQuadraticBezierCurve = true; - // faces + this.type = 'QuadraticBezierCurve'; - indices.push( a, b, d ); - indices.push( b, c, d ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - } + } - } + getPoint( t, optionalTarget = new Vector2() ) { - } + const point = optionalTarget; - function generateUVs() { + const v0 = this.v0, v1 = this.v1, v2 = this.v2; - for ( let i = 0; i <= tubularSegments; i ++ ) { + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); - for ( let j = 0; j <= radialSegments; j ++ ) { + return point; - uv.x = i / tubularSegments; - uv.y = j / radialSegments; + } - uvs.push( uv.x, uv.y ); + copy( source ) { - } + super.copy( source ); - } + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - } + return this; } + toJSON() { - const data = BufferGeometry.prototype.toJSON.call( this ); + const data = super.toJSON(); - data.path = this.parameters.path.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); return data; } -} + fromJSON( json ) { -class WireframeGeometry extends BufferGeometry { + super.fromJSON( json ); - constructor( geometry ) { + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - super(); - this.type = 'WireframeGeometry'; + return this; - if ( geometry.isGeometry === true ) { + } - console.error( 'THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - return; +} - } +class QuadraticBezierCurve3 extends Curve { - // buffer + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { - const vertices = []; + super(); - // helper variables + this.isQuadraticBezierCurve3 = true; - const edge = [ 0, 0 ], edges = {}; + this.type = 'QuadraticBezierCurve3'; - const vertex = new Vector3(); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - if ( geometry.index !== null ) { + } - // indexed BufferGeometry + getPoint( t, optionalTarget = new Vector3() ) { - const position = geometry.attributes.position; - const indices = geometry.index; - let groups = geometry.groups; + const point = optionalTarget; - if ( groups.length === 0 ) { + const v0 = this.v0, v1 = this.v1, v2 = this.v2; - groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); - } + return point; - // create a data structure that contains all eges without duplicates + } - for ( let o = 0, ol = groups.length; o < ol; ++ o ) { + copy( source ) { - const group = groups[ o ]; + super.copy( source ); - const start = group.start; - const count = group.count; + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - for ( let i = start, l = ( start + count ); i < l; i += 3 ) { + return this; - for ( let j = 0; j < 3; j ++ ) { + } - const edge1 = indices.getX( i + j ); - const edge2 = indices.getX( i + ( j + 1 ) % 3 ); - edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates - edge[ 1 ] = Math.max( edge1, edge2 ); + toJSON() { - const key = edge[ 0 ] + ',' + edge[ 1 ]; + const data = super.toJSON(); - if ( edges[ key ] === undefined ) { + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; + return data; - } + } - } + fromJSON( json ) { - } + super.fromJSON( json ); - } + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - // generate vertices + return this; - for ( const key in edges ) { + } - const e = edges[ key ]; +} - vertex.fromBufferAttribute( position, e.index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); +class SplineCurve extends Curve { - vertex.fromBufferAttribute( position, e.index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + constructor( points = [] ) { - } + super(); - } else { + this.isSplineCurve = true; - // non-indexed BufferGeometry + this.type = 'SplineCurve'; - const position = geometry.attributes.position; + this.points = points; - for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { + } - for ( let j = 0; j < 3; j ++ ) { + getPoint( t, optionalTarget = new Vector2() ) { - // three edges per triangle, an edge is represented as (index1, index2) - // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) + const point = optionalTarget; - const index1 = 3 * i + j; - vertex.fromBufferAttribute( position, index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + const points = this.points; + const p = ( points.length - 1 ) * t; - const index2 = 3 * i + ( ( j + 1 ) % 3 ); - vertex.fromBufferAttribute( position, index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + const intPoint = Math.floor( p ); + const weight = p - intPoint; - } + const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + const p1 = points[ intPoint ]; + const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - } + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); - } + return point; - // build geometry + } - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + copy( source ) { - } + super.copy( source ); -} + this.points = []; -var Geometries = /*#__PURE__*/Object.freeze({ - __proto__: null, - BoxGeometry: BoxGeometry, - BoxBufferGeometry: BoxGeometry, - CircleGeometry: CircleGeometry, - CircleBufferGeometry: CircleGeometry, - ConeGeometry: ConeGeometry, - ConeBufferGeometry: ConeGeometry, - CylinderGeometry: CylinderGeometry, - CylinderBufferGeometry: CylinderGeometry, - DodecahedronGeometry: DodecahedronGeometry, - DodecahedronBufferGeometry: DodecahedronGeometry, - EdgesGeometry: EdgesGeometry, - ExtrudeGeometry: ExtrudeGeometry, - ExtrudeBufferGeometry: ExtrudeGeometry, - IcosahedronGeometry: IcosahedronGeometry, - IcosahedronBufferGeometry: IcosahedronGeometry, - LatheGeometry: LatheGeometry, - LatheBufferGeometry: LatheGeometry, - OctahedronGeometry: OctahedronGeometry, - OctahedronBufferGeometry: OctahedronGeometry, - ParametricGeometry: ParametricGeometry, - ParametricBufferGeometry: ParametricGeometry, - PlaneGeometry: PlaneGeometry, - PlaneBufferGeometry: PlaneGeometry, - PolyhedronGeometry: PolyhedronGeometry, - PolyhedronBufferGeometry: PolyhedronGeometry, - RingGeometry: RingGeometry, - RingBufferGeometry: RingGeometry, - ShapeGeometry: ShapeGeometry, - ShapeBufferGeometry: ShapeGeometry, - SphereGeometry: SphereGeometry, - SphereBufferGeometry: SphereGeometry, - TetrahedronGeometry: TetrahedronGeometry, - TetrahedronBufferGeometry: TetrahedronGeometry, - TextGeometry: TextGeometry, - TextBufferGeometry: TextGeometry, - TorusGeometry: TorusGeometry, - TorusBufferGeometry: TorusGeometry, - TorusKnotGeometry: TorusKnotGeometry, - TorusKnotBufferGeometry: TorusKnotGeometry, - TubeGeometry: TubeGeometry, - TubeBufferGeometry: TubeGeometry, - WireframeGeometry: WireframeGeometry -}); + for ( let i = 0, l = source.points.length; i < l; i ++ ) { -/** - * parameters = { - * color: - * } - */ + const point = source.points[ i ]; -class ShadowMaterial extends Material { + this.points.push( point.clone() ); - constructor( parameters ) { + } - super(); + return this; - this.type = 'ShadowMaterial'; + } - this.color = new Color( 0x000000 ); - this.transparent = true; + toJSON() { - this.setValues( parameters ); + const data = super.toJSON(); - } + data.points = []; - copy( source ) { + for ( let i = 0, l = this.points.length; i < l; i ++ ) { - super.copy( source ); + const point = this.points[ i ]; + data.points.push( point.toArray() ); - this.color.copy( source.color ); + } - return this; + return data; } -} + fromJSON( json ) { -ShadowMaterial.prototype.isShadowMaterial = true; + super.fromJSON( json ); -class RawShaderMaterial extends ShaderMaterial { + this.points = []; - constructor( parameters ) { + for ( let i = 0, l = json.points.length; i < l; i ++ ) { - super( parameters ); + const point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); - this.type = 'RawShaderMaterial'; + } + + return this; } } -RawShaderMaterial.prototype.isRawShaderMaterial = true; - -/** - * 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( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * 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: , - * - * flatShading: - * } - */ +var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve +}); -function MeshStandardMaterial( parameters ) { +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - Material.call( this ); +class CurvePath extends Curve { - this.defines = { 'STANDARD': '' }; + constructor() { - this.type = 'MeshStandardMaterial'; + super(); - this.color = new Color( 0xffffff ); // diffuse - this.roughness = 1.0; - this.metalness = 0.0; + this.type = 'CurvePath'; - this.map = null; + this.curves = []; + this.autoClose = false; // Automatically closes the path - this.lightMap = null; - this.lightMapIntensity = 1.0; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + add( curve ) { - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + this.curves.push( curve ); - this.bumpMap = null; - this.bumpScale = 1; + } - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + closePath() { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + // Add a line curve if start and end of lines are not connected + const startPoint = this.curves[ 0 ].getPoint( 0 ); + const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); - this.roughnessMap = null; + if ( ! startPoint.equals( endPoint ) ) { - this.metalnessMap = null; + this.curves.push( new LineCurve( endPoint, startPoint ) ); - this.alphaMap = null; + } - this.envMap = null; - this.envMapIntensity = 1.0; + } - this.refractionRatio = 0.98; + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + getPoint( t, optionalTarget ) { - this.flatShading = false; + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; - this.vertexTangents = false; + // To think about boundaries points. - this.setValues( parameters ); + while ( i < curveLengths.length ) { -} + if ( curveLengths[ i ] >= d ) { -MeshStandardMaterial.prototype = Object.create( Material.prototype ); -MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; + const diff = curveLengths[ i ] - d; + const curve = this.curves[ i ]; -MeshStandardMaterial.prototype.isMeshStandardMaterial = true; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; -MeshStandardMaterial.prototype.copy = function ( source ) { + return curve.getPointAt( u, optionalTarget ); - Material.prototype.copy.call( this, source ); + } - this.defines = { 'STANDARD': '' }; + i ++; - this.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + } - this.map = source.map; + return null; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + // loop where sum != 0, sum > d , sum+1 , - * clearcoatMap: new THREE.Texture( ), - * clearcoatRoughness: , - * clearcoatRoughnessMap: new THREE.Texture( ), - * clearcoatNormalScale: , - * clearcoatNormalMap: new THREE.Texture( ), - * - * reflectivity: , - * ior: , - * - * sheen: , - * - * transmission: , - * transmissionMap: new THREE.Texture( ) - * } - */ + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { -function MeshPhysicalMaterial( parameters ) { + sums += this.curves[ i ].getLength(); + lengths.push( sums ); - MeshStandardMaterial.call( this ); + } - this.defines = { + this.cacheLengths = lengths; - 'STANDARD': '', - 'PHYSICAL': '' + return lengths; - }; + } - this.type = 'MeshPhysicalMaterial'; + getSpacedPoints( divisions = 40 ) { - this.clearcoat = 0.0; - this.clearcoatMap = null; - this.clearcoatRoughness = 0.0; - this.clearcoatRoughnessMap = null; - this.clearcoatNormalScale = new Vector2( 1, 1 ); - this.clearcoatNormalMap = null; + const points = []; - this.reflectivity = 0.5; // maps to F0 = 0.04 + for ( let i = 0; i <= divisions; i ++ ) { - Object.defineProperty( this, 'ior', { - get: function () { + points.push( this.getPoint( i / divisions ) ); - return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity ); + } - }, - set: function ( ior ) { + if ( this.autoClose ) { - this.reflectivity = MathUtils.clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 ); + points.push( points[ 0 ] ); } - } ); - this.sheen = null; // null will disable sheen bsdf + return points; - this.transmission = 0.0; - this.transmissionMap = null; + } - this.setValues( parameters ); + getPoints( divisions = 12 ) { -} + const points = []; + let last; -MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); -MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; + for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) { -MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; + const curve = curves[ i ]; + const resolution = curve.isEllipseCurve ? divisions * 2 + : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1 + : curve.isSplineCurve ? divisions * curve.points.length + : divisions; -MeshPhysicalMaterial.prototype.copy = function ( source ) { + const pts = curve.getPoints( resolution ); - MeshStandardMaterial.prototype.copy.call( this, source ); + for ( let j = 0; j < pts.length; j ++ ) { - this.defines = { + const point = pts[ j ]; - 'STANDARD': '', - 'PHYSICAL': '' + if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates - }; + points.push( point ); + last = point; - this.clearcoat = source.clearcoat; - this.clearcoatMap = source.clearcoatMap; - this.clearcoatRoughness = source.clearcoatRoughness; - this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; - this.clearcoatNormalMap = source.clearcoatNormalMap; - this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + } - this.reflectivity = source.reflectivity; + } - if ( source.sheen ) { + if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { - this.sheen = ( this.sheen || new Color() ).copy( source.sheen ); + points.push( points[ 0 ] ); - } else { + } - this.sheen = null; + return points; } - this.transmission = source.transmission; - this.transmissionMap = source.transmissionMap; + copy( source ) { - return this; + super.copy( source ); -}; + this.curves = []; -/** - * 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( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.MultiplyOperation, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * flatShading: - * } - */ + for ( let i = 0, l = source.curves.length; i < l; i ++ ) { -class MeshPhongMaterial extends Material { + const curve = source.curves[ i ]; - constructor( parameters ) { + this.curves.push( curve.clone() ); - super(); + } - this.type = 'MeshPhongMaterial'; + this.autoClose = source.autoClose; - this.color = new Color( 0xffffff ); // diffuse - this.specular = new Color( 0x111111 ); - this.shininess = 30; + return this; - this.map = null; + } - this.lightMap = null; - this.lightMapIntensity = 1.0; + toJSON() { - this.aoMap = null; - this.aoMapIntensity = 1.0; + const data = super.toJSON(); - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + data.autoClose = this.autoClose; + data.curves = []; - this.bumpMap = null; - this.bumpScale = 1; + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + const curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + } - this.specularMap = null; + return data; - this.alphaMap = null; + } - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + fromJSON( json ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + super.fromJSON( json ); - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.autoClose = json.autoClose; + this.curves = []; - this.flatShading = false; + for ( let i = 0, l = json.curves.length; i < l; i ++ ) { - this.setValues( parameters ); + const curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); - } + } - copy( source ) { + return this; - super.copy( source ); + } - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; +} - this.map = source.map; +class Path extends CurvePath { - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + constructor( points ) { - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + super(); - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + this.type = 'Path'; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + this.currentPoint = new Vector2(); - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + if ( points ) { - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + this.setFromPoints( points ); - this.specularMap = source.specularMap; + } - this.alphaMap = source.alphaMap; + } - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + setFromPoints( points ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + this.moveTo( points[ 0 ].x, points[ 0 ].y ); + + for ( let i = 1, l = points.length; i < l; i ++ ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.lineTo( points[ i ].x, points[ i ].y ); - this.flatShading = source.flatShading; + } return this; } -} + moveTo( x, y ) { -MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? -/** - * parameters = { - * color: , - * - * map: new THREE.Texture( ), - * gradientMap: 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( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * alphaMap: new THREE.Texture( ), - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + return this; -class MeshToonMaterial extends Material { + } - constructor( parameters ) { + lineTo( x, y ) { - super(); + const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - this.defines = { 'TOON': '' }; + this.currentPoint.set( x, y ); - this.type = 'MeshToonMaterial'; + return this; - this.color = new Color( 0xffffff ); + } - this.map = null; - this.gradientMap = null; + quadraticCurveTo( aCPx, aCPy, aX, aY ) { - this.lightMap = null; - this.lightMapIntensity = 1.0; + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - this.aoMap = null; - this.aoMapIntensity = 1.0; + this.curves.push( curve ); - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + this.currentPoint.set( aX, aY ); - this.bumpMap = null; - this.bumpScale = 1; + return this; - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + } - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - this.alphaMap = null; + const curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + this.curves.push( curve ); - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.currentPoint.set( aX, aY ); - this.setValues( parameters ); + return this; } - copy( source ) { + splineThru( pts /*Array of Vector*/ ) { - super.copy( source ); + const npts = [ this.currentPoint.clone() ].concat( pts ); - this.color.copy( source.color ); + const curve = new SplineCurve( npts ); + this.curves.push( curve ); - this.map = source.map; - this.gradientMap = source.gradientMap; + this.currentPoint.copy( pts[ pts.length - 1 ] ); - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + return this; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + } - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + return this; - this.alphaMap = source.alphaMap; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); return this; } -} + ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { -MeshToonMaterial.prototype.isMeshToonMaterial = true; + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; -/** - * parameters = { - * opacity: , - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * flatShading: - * } - */ + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); -class MeshNormalMaterial extends Material { + return this; - constructor( parameters ) { + } - super(); + absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - this.type = 'MeshNormalMaterial'; + const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - this.bumpMap = null; - this.bumpScale = 1; + if ( this.curves.length > 0 ) { - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + // if a previous curve is present, attempt to join + const firstPoint = curve.getPoint( 0 ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + if ( ! firstPoint.equals( this.currentPoint ) ) { - this.wireframe = false; - this.wireframeLinewidth = 1; + this.lineTo( firstPoint.x, firstPoint.y ); - this.fog = false; + } - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + } - this.flatShading = false; + this.curves.push( curve ); - this.setValues( parameters ); + const lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + return this; } @@ -31831,25 +32843,27 @@ class MeshNormalMaterial extends Material { super.copy( source ); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + this.currentPoint.copy( source.currentPoint ); - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + return this; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + toJSON() { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + const data = super.toJSON(); - this.flatShading = source.flatShading; + data.currentPoint = this.currentPoint.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.currentPoint.fromArray( json.currentPoint ); return this; @@ -31857,1292 +32871,1139 @@ class MeshNormalMaterial extends Material { } -MeshNormalMaterial.prototype.isMeshNormalMaterial = true; +class LatheGeometry extends BufferGeometry { -/** - * 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.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { -class MeshLambertMaterial extends Material { + super(); - constructor( parameters ) { + this.type = 'LatheGeometry'; - super(); + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; - this.type = 'MeshLambertMaterial'; + segments = Math.floor( segments ); - this.color = new Color( 0xffffff ); // diffuse + // clamp phiLength so it's in range of [ 0, 2PI ] - this.map = null; + phiLength = clamp( phiLength, 0, Math.PI * 2 ); - this.lightMap = null; - this.lightMapIntensity = 1.0; + // buffers - this.aoMap = null; - this.aoMapIntensity = 1.0; + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + // helper variables - this.specularMap = null; + const inverseSegments = 1.0 / segments; + const vertex = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; - this.alphaMap = null; + // pre-compute normals for initial "meridian" - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + switch ( j ) { - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + case 0: // special handling for 1st vertex on path - this.setValues( parameters ); + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; - } + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; - copy( source ) { + prevNormal.copy( normal ); - super.copy( source ); + normal.normalize(); - this.color.copy( source.color ); + initNormals.push( normal.x, normal.y, normal.z ); - this.map = source.map; + break; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + case ( points.length - 1 ): // special handling for last Vertex on path - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z ); - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + break; - this.specularMap = source.specularMap; + default: // default handling for all vertices in between - this.alphaMap = source.alphaMap; + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + curNormal.copy( normal ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; - return this; + normal.normalize(); - } + initNormals.push( normal.x, normal.y, normal.z ); -} + prevNormal.copy( curNormal ); -MeshLambertMaterial.prototype.isMeshLambertMaterial = true; + } -/** - * parameters = { - * color: , - * opacity: , - * - * matcap: new THREE.Texture( ), - * - * map: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * alphaMap: new THREE.Texture( ), - * - * skinning: , - * morphTargets: , - * morphNormals: - * - * flatShading: - * } - */ + } -class MeshMatcapMaterial extends Material { + // generate vertices, uvs and normals - constructor( parameters ) { + for ( let i = 0; i <= segments; i ++ ) { - super(); + const phi = phiStart + i * inverseSegments * phiLength; - this.defines = { 'MATCAP': '' }; + const sin = Math.sin( phi ); + const cos = Math.cos( phi ); - this.type = 'MeshMatcapMaterial'; + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { - this.color = new Color( 0xffffff ); // diffuse + // vertex - this.matcap = null; + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; - this.map = null; + vertices.push( vertex.x, vertex.y, vertex.z ); - this.bumpMap = null; - this.bumpScale = 1; + // uv - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + uvs.push( uv.x, uv.y ); - this.alphaMap = null; + // normal - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + const x = initNormals[ 3 * j + 0 ] * sin; + const y = initNormals[ 3 * j + 1 ]; + const z = initNormals[ 3 * j + 0 ] * cos; - this.flatShading = false; + normals.push( x, y, z ); - this.setValues( parameters ); + } - } + } + // indices - copy( source ) { + for ( let i = 0; i < segments; i ++ ) { - super.copy( source ); + for ( let j = 0; j < ( points.length - 1 ); j ++ ) { - this.defines = { 'MATCAP': '' }; + const base = j + i * points.length; - this.color.copy( source.color ); + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; - this.matcap = source.matcap; + // faces - this.map = source.map; + indices.push( a, b, d ); + indices.push( c, d, b ); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + } - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + } - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + // build geometry - this.alphaMap = source.alphaMap; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + } - this.flatShading = source.flatShading; + static fromJSON( data ) { - return this; + return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength ); } } -MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true; - -/** - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ - -class LineDashedMaterial extends LineBasicMaterial { +class CapsuleGeometry extends LatheGeometry { - constructor( parameters ) { + constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) { - super(); + const path = new Path(); + path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 ); + path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 ); - this.type = 'LineDashedMaterial'; + super( path.getPoints( capSegments ), radialSegments ); - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + this.type = 'CapsuleGeometry'; - this.setValues( parameters ); + this.parameters = { + radius: radius, + height: length, + capSegments: capSegments, + radialSegments: radialSegments, + }; } - copy( source ) { - - super.copy( source ); - - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + static fromJSON( data ) { - return this; + return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments ); } } -LineDashedMaterial.prototype.isLineDashedMaterial = true; +class CircleGeometry extends BufferGeometry { -var Materials = /*#__PURE__*/Object.freeze({ - __proto__: null, - ShadowMaterial: ShadowMaterial, - SpriteMaterial: SpriteMaterial, - RawShaderMaterial: RawShaderMaterial, - ShaderMaterial: ShaderMaterial, - PointsMaterial: PointsMaterial, - MeshPhysicalMaterial: MeshPhysicalMaterial, - MeshStandardMaterial: MeshStandardMaterial, - MeshPhongMaterial: MeshPhongMaterial, - MeshToonMaterial: MeshToonMaterial, - MeshNormalMaterial: MeshNormalMaterial, - MeshLambertMaterial: MeshLambertMaterial, - MeshDepthMaterial: MeshDepthMaterial, - MeshDistanceMaterial: MeshDistanceMaterial, - MeshBasicMaterial: MeshBasicMaterial, - MeshMatcapMaterial: MeshMatcapMaterial, - LineDashedMaterial: LineDashedMaterial, - LineBasicMaterial: LineBasicMaterial, - Material: Material -}); + constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) { -const AnimationUtils = { + super(); - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function ( array, from, to ) { + this.type = 'CircleGeometry'; - if ( AnimationUtils.isTypedArray( array ) ) { + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - // in ios9 array.subarray(from, undefined) will return empty array - // but array.subarray(from) or array.subarray(from, len) is correct - return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); + segments = Math.max( 3, segments ); - } + // buffers - return array.slice( from, to ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - }, + // helper variables - // converts an array to a specific type - convertArray: function ( array, type, forceClone ) { + const vertex = new Vector3(); + const uv = new Vector2(); - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) return array; + // center point - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); - return new type( array ); // create typed array + for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { - } + const segment = thetaStart + s / segments * thetaLength; - return Array.prototype.slice.call( array ); // create Array + // vertex - }, + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - isTypedArray: function ( object ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + // normal - }, + normals.push( 0, 0, 1 ); - // returns an array by which times and values can be sorted - getKeyframeOrder: function ( times ) { + // uvs - function compareTime( i, j ) { + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; - return times[ i ] - times[ j ]; + uvs.push( uv.x, uv.y ); } - const n = times.length; - const result = new Array( n ); - for ( let i = 0; i !== n; ++ i ) result[ i ] = i; - - result.sort( compareTime ); - - return result; - - }, - - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function ( values, stride, order ) { - - const nValues = values.length; - const result = new values.constructor( nValues ); - - for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - - const srcOffset = order[ i ] * stride; - - for ( let j = 0; j !== stride; ++ j ) { + // indices - result[ dstOffset ++ ] = values[ srcOffset + j ]; + for ( let i = 1; i <= segments; i ++ ) { - } + indices.push( i, i + 1, 0 ); } - return result; - - }, + // build geometry - // function for parsing AOS keyframe formats - flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) { + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - let i = 1, key = jsonKeys[ 0 ]; + } - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + static fromJSON( data ) { - key = jsonKeys[ i ++ ]; + return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength ); - } + } - if ( key === undefined ) return; // no data +} - let value = key[ valuePropertyName ]; - if ( value === undefined ) return; // no data +class CylinderGeometry extends BufferGeometry { - if ( Array.isArray( value ) ) { + constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { - do { + super(); - value = key[ valuePropertyName ]; + this.type = 'CylinderGeometry'; - if ( value !== undefined ) { + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - times.push( key.time ); - values.push.apply( values, value ); // push all elements + const scope = this; - } + radialSegments = Math.floor( radialSegments ); + heightSegments = Math.floor( heightSegments ); - key = jsonKeys[ i ++ ]; + // buffers - } while ( key !== undefined ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - } else if ( value.toArray !== undefined ) { + // helper variables - // ...assume THREE.Math-ish + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; - do { + // generate geometry - value = key[ valuePropertyName ]; + generateTorso(); - if ( value !== undefined ) { + if ( openEnded === false ) { - times.push( key.time ); - value.toArray( values, values.length ); + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); - } + } - key = jsonKeys[ i ++ ]; + // build geometry - } while ( key !== undefined ); + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } else { + function generateTorso() { - // otherwise push as-is + const normal = new Vector3(); + const vertex = new Vector3(); - do { + let groupCount = 0; - value = key[ valuePropertyName ]; + // this will be used to calculate the normal + const slope = ( radiusBottom - radiusTop ) / height; - if ( value !== undefined ) { + // generate vertices, normals and uvs - times.push( key.time ); - values.push( value ); + for ( let y = 0; y <= heightSegments; y ++ ) { - } + const indexRow = []; - key = jsonKeys[ i ++ ]; + const v = y / heightSegments; - } while ( key !== undefined ); + // calculate the radius of the current row - } + const radius = v * ( radiusBottom - radiusTop ) + radiusTop; - }, + for ( let x = 0; x <= radialSegments; x ++ ) { - subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) { + const u = x / radialSegments; - const clip = sourceClip.clone(); + const theta = u * thetaLength + thetaStart; - clip.name = name; + const sinTheta = Math.sin( theta ); + const cosTheta = Math.cos( theta ); - const tracks = []; + // vertex - for ( let i = 0; i < clip.tracks.length; ++ i ) { + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); - const track = clip.tracks[ i ]; - const valueSize = track.getValueSize(); + // normal - const times = []; - const values = []; + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - for ( let j = 0; j < track.times.length; ++ j ) { + // uv - const frame = track.times[ j ] * fps; + uvs.push( u, 1 - v ); - if ( frame < startFrame || frame >= endFrame ) continue; + // save index of vertex in respective row - times.push( track.times[ j ] ); + indexRow.push( index ++ ); - for ( let k = 0; k < valueSize; ++ k ) { + } - values.push( track.values[ j * valueSize + k ] ); + // now save vertices of the row in our index array - } + indexArray.push( indexRow ); } - if ( times.length === 0 ) continue; + // generate indices - track.times = AnimationUtils.convertArray( times, track.times.constructor ); - track.values = AnimationUtils.convertArray( values, track.values.constructor ); + for ( let x = 0; x < radialSegments; x ++ ) { - tracks.push( track ); + for ( let y = 0; y < heightSegments; y ++ ) { - } + // we use the index array to access the correct indices - clip.tracks = tracks; + const a = indexArray[ y ][ x ]; + const b = indexArray[ y + 1 ][ x ]; + const c = indexArray[ y + 1 ][ x + 1 ]; + const d = indexArray[ y ][ x + 1 ]; - // find minimum .times value across all tracks in the trimmed clip + // faces - let minStartTime = Infinity; + indices.push( a, b, d ); + indices.push( b, c, d ); - for ( let i = 0; i < clip.tracks.length; ++ i ) { + // update group counter - if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { + groupCount += 6; - minStartTime = clip.tracks[ i ].times[ 0 ]; + } } - } + // add a group to the geometry. this will ensure multi material support - // shift all tracks such that clip begins at t=0 + scope.addGroup( groupStart, groupCount, 0 ); - for ( let i = 0; i < clip.tracks.length; ++ i ) { + // calculate new start value for groups - clip.tracks[ i ].shift( - 1 * minStartTime ); + groupStart += groupCount; } - clip.resetDuration(); - - return clip; + function generateCap( top ) { - }, + // save the index of the first center vertex + const centerIndexStart = index; - makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { + const uv = new Vector2(); + const vertex = new Vector3(); - if ( fps <= 0 ) fps = 30; + let groupCount = 0; - const numTracks = referenceClip.tracks.length; - const referenceTime = referenceFrame / fps; + const radius = ( top === true ) ? radiusTop : radiusBottom; + const sign = ( top === true ) ? 1 : - 1; - // Make each track's values relative to the values at the reference frame - for ( let i = 0; i < numTracks; ++ 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 - const referenceTrack = referenceClip.tracks[ i ]; - const referenceTrackType = referenceTrack.ValueTypeName; + for ( let x = 1; x <= radialSegments; x ++ ) { - // Skip this track if it's non-numeric - if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; + // vertex - // Find the track in the target clip whose name and type matches the reference track - const targetTrack = targetClip.tracks.find( function ( track ) { + vertices.push( 0, halfHeight * sign, 0 ); - return track.name === referenceTrack.name - && track.ValueTypeName === referenceTrackType; + // normal - } ); + normals.push( 0, sign, 0 ); - if ( targetTrack === undefined ) continue; + // uv - let referenceOffset = 0; - const referenceValueSize = referenceTrack.getValueSize(); + uvs.push( 0.5, 0.5 ); - if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + // increase index - referenceOffset = referenceValueSize / 3; + index ++; } - let targetOffset = 0; - const targetValueSize = targetTrack.getValueSize(); - - if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + // save the index of the last center vertex + const centerIndexEnd = index; - targetOffset = targetValueSize / 3; + // now we generate the surrounding vertices, normals and uvs - } + for ( let x = 0; x <= radialSegments; x ++ ) { - const lastIndex = referenceTrack.times.length - 1; - let referenceValue; + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; - // Find the value to subtract out of the track - if ( referenceTime <= referenceTrack.times[ 0 ] ) { + const cosTheta = Math.cos( theta ); + const sinTheta = Math.sin( theta ); - // Reference frame is earlier than the first keyframe, so just use the first keyframe - const startIndex = referenceOffset; - const endIndex = referenceValueSize - referenceOffset; - referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex ); + // vertex - } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); - // Reference frame is after the last keyframe, so just use the last keyframe - const startIndex = lastIndex * referenceValueSize + referenceOffset; - const endIndex = startIndex + referenceValueSize - referenceOffset; - referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex ); + // normal - } else { + normals.push( 0, sign, 0 ); - // Interpolate to the reference value - const interpolant = referenceTrack.createInterpolant(); - const startIndex = referenceOffset; - const endIndex = referenceValueSize - referenceOffset; - interpolant.evaluate( referenceTime ); - referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex ); + // uv - } + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); - // Conjugate the quaternion - if ( referenceTrackType === 'quaternion' ) { + // increase index - const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); - referenceQuat.toArray( referenceValue ); + index ++; } - // Subtract the reference value from all of the track values - - const numTimes = targetTrack.times.length; - for ( let j = 0; j < numTimes; ++ j ) { + // generate indices - const valueStart = j * targetValueSize + targetOffset; + for ( let x = 0; x < radialSegments; x ++ ) { - if ( referenceTrackType === 'quaternion' ) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; - // Multiply the conjugate for quaternion track types - Quaternion.multiplyQuaternionsFlat( - targetTrack.values, - valueStart, - referenceValue, - 0, - targetTrack.values, - valueStart - ); + if ( top === true ) { - } else { + // face top - const valueEnd = targetValueSize - targetOffset * 2; + indices.push( i, i + 1, c ); - // Subtract each value for all other numeric track types - for ( let k = 0; k < valueEnd; ++ k ) { + } else { - targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; + // face bottom - } + indices.push( i + 1, i, c ); } + groupCount += 3; + } - } + // add a group to the geometry. this will ensure multi material support - targetClip.blendMode = AdditiveAnimationBlendMode; + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); - return targetClip; + // calculate new start value for groups - } + groupStart += groupCount; -}; + } -/** - * 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 - * - */ + } -function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + static fromJSON( data ) { - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + } } -Object.assign( Interpolant.prototype, { - - evaluate: function ( t ) { - - const pp = this.parameterPositions; - let i1 = this._cachedIndex, - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; - - validate_interval: { - - seek: { - - let right; +class ConeGeometry extends CylinderGeometry { - linear_scan: { + constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - for ( let giveUpAt = i1 + 2; ; ) { + this.type = 'ConeGeometry'; - if ( t1 === undefined ) { + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - if ( t < t0 ) break forward_scan; + } - // after end + static fromJSON( data ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); - } + } - if ( i1 === giveUpAt ) break; // this loop +} - t0 = t1; - t1 = pp[ ++ i1 ]; +class PolyhedronGeometry extends BufferGeometry { - if ( t < t1 ) { + constructor( vertices = [], indices = [], radius = 1, detail = 0 ) { - // we have arrived at the sought interval - break seek; + super(); - } + this.type = 'PolyhedronGeometry'; - } + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + // default buffer data - } + const vertexBuffer = []; + const uvBuffer = []; - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + // the subdivision creates the vertex buffer data - // looping? + subdivide( detail ); - const t1global = pp[ 1 ]; + // all vertices should lie on a conceptual sphere with a given radius - if ( t < t1global ) { + applyRadius( radius ); - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + // finally, create the uv data - } + generateUVs(); - // linear reverse scan + // build non-indexed geometry - for ( let giveUpAt = i1 - 2; ; ) { + this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); - if ( t0 === undefined ) { + if ( detail === 0 ) { - // before start + this.computeVertexNormals(); // flat normals - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + } else { - } + this.normalizeNormals(); // smooth normals - if ( i1 === giveUpAt ) break; // this loop + } - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + // helper functions - if ( t >= t0 ) { + function subdivide( detail ) { - // we have arrived at the sought interval - break seek; + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); - } + // iterate over all faces and apply a subdivison with the given detail value - } + for ( let i = 0; i < indices.length; i += 3 ) { - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + // get the vertices of the face - } + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); - // the interval is valid + // perform subdivision - break validate_interval; + subdivideFace( a, b, c, detail ); - } // linear scan + } - // binary search + } - while ( i1 < right ) { + function subdivideFace( a, b, c, detail ) { - const mid = ( i1 + right ) >>> 1; + const cols = detail + 1; - if ( t < pp[ mid ] ) { + // we use this multidimensional array as a data structure for creating the subdivision - right = mid; + const v = []; - } else { + // construct all of the vertices for this subdivision - i1 = mid + 1; + for ( let i = 0; i <= cols; i ++ ) { - } + v[ i ] = []; - } + const aj = a.clone().lerp( c, i / cols ); + const bj = b.clone().lerp( c, i / cols ); - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + const rows = cols - i; - // check boundary cases, again + for ( let j = 0; j <= rows; j ++ ) { - if ( t0 === undefined ) { + if ( j === 0 && i === cols ) { - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + v[ i ][ j ] = aj; - } + } else { - if ( t1 === undefined ) { + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + } } - } // seek - - this._cachedIndex = i1; - - this.intervalChanged_( i1, t0, t1 ); - - } // validate_interval - - return this.interpolate_( i1, t0, t, t1 ); - - }, + } - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + // construct all of the faces - // --- Protected interface + for ( let i = 0; i < cols; i ++ ) { - DefaultSettings_: {}, + for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - getSettings_: function () { + const k = Math.floor( j / 2 ); - return this.settings || this.DefaultSettings_; + if ( j % 2 === 0 ) { - }, + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); - copySampleValue_: function ( index ) { + } else { - // copies a sample value to the result buffer + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + } - for ( let i = 0; i !== stride; ++ i ) { + } - result[ i ] = values[ offset + i ]; + } } - return result; - - }, - - // Template methods for derived classes: - - interpolate_: function ( /* i1, t0, t, t1 */ ) { - - throw new Error( 'call to abstract method' ); - // implementations shall return this.resultBuffer - - }, - - intervalChanged_: function ( /* i1, t0, t1 */ ) { - - // empty - - } - -} ); + function applyRadius( radius ) { -// DECLARE ALIAS AFTER assign prototype -Object.assign( Interpolant.prototype, { + const vertex = new Vector3(); - //( 0, t, t0 ), returns this.resultBuffer - beforeStart_: Interpolant.prototype.copySampleValue_, + // iterate over the entire buffer and apply the radius to each vertex - //( N-1, tN-1, t ), returns this.resultBuffer - afterEnd_: Interpolant.prototype.copySampleValue_, + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { -} ); + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; -/** - * 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. - */ + vertex.normalize().multiplyScalar( radius ); -function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + } - this._weightPrev = - 0; - this._offsetPrev = - 0; - this._weightNext = - 0; - this._offsetNext = - 0; + } -} + function generateUVs() { -CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + const vertex = new Vector3(); - constructor: CubicInterpolant, + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { - DefaultSettings_: { + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding + const u = azimuth( vertex ) / 2 / Math.PI + 0.5; + const v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); - }, + } - intervalChanged_: function ( i1, t0, t1 ) { + correctUVs(); - const pp = this.parameterPositions; - let iPrev = i1 - 2, - iNext = i1 + 1, + correctSeam(); - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + } - if ( tPrev === undefined ) { + function correctSeam() { - switch ( this.getSettings_().endingStart ) { + // handle case when face straddles the seam, see #3269 - case ZeroSlopeEnding: + for ( let i = 0; i < uvBuffer.length; i += 6 ) { - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + // uv data of a single face - break; + const x0 = uvBuffer[ i + 0 ]; + const x1 = uvBuffer[ i + 2 ]; + const x2 = uvBuffer[ i + 4 ]; - case WrapAroundEnding: + const max = Math.max( x0, x1, x2 ); + const min = Math.min( x0, x1, x2 ); - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + // 0.9 is somewhat arbitrary - break; + if ( max > 0.9 && min < 0.1 ) { - default: // ZeroCurvatureEnding + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + } } } - if ( tNext === undefined ) { - - switch ( this.getSettings_().endingEnd ) { - - case ZeroSlopeEnding: - - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; - - break; - - case WrapAroundEnding: + function pushVertex( vertex ) { - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); - break; + } - default: // ZeroCurvatureEnding + function getVertexByIndex( index, vertex ) { - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + const stride = index * 3; - } + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; } - const halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; - - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + function correctUVs() { - }, + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); - interpolate_: function ( i1, t0, t, t1 ) { + const centroid = new Vector3(); - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); - // evaluate polynomials + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); - const sP = - wP * ppp + 2 * wP * pp - wP * p; - const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; - const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - const sN = wN * ppp - wN * pp; + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); - // combine data linearly + const azi = azimuth( centroid ); - for ( let i = 0; i !== stride; ++ i ) { + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; + } } - return result; + function correctUV( uv, stride, vector, azimuth ) { - } + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { -} ); + uvBuffer[ stride ] = uv.x - 1; -function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + } - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { -} + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; -LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + } - constructor: LinearInterpolant, + } - interpolate_: function ( i1, t0, t, t1 ) { + // Angle around the Y axis, counter-clockwise when looking from above. - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + function azimuth( vector ) { - offset1 = i1 * stride, - offset0 = offset1 - stride, + return Math.atan2( vector.z, - vector.x ); - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + } - for ( let i = 0; i !== stride; ++ i ) { - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + // Angle above the XZ plane. - } + function inclination( vector ) { - return result; + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - } + } -} ); + } -/** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - */ + static fromJSON( data ) { -function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details ); - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + } } -DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { +class DodecahedronGeometry extends PolyhedronGeometry { - constructor: DiscreteInterpolant, + constructor( radius = 1, detail = 0 ) { - interpolate_: function ( i1 /*, t0, t, t1 */ ) { + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + const r = 1 / t; - return this.copySampleValue_( i1 - 1 ); + const 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, -class KeyframeTrack { + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, - constructor( name, times, values, interpolation ) { + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; - if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); - if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); + const 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 + ]; - this.name = name; + super( vertices, indices, radius, detail ); - this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); + this.type = 'DodecahedronGeometry'; - this.setInterpolation( interpolation || this.DefaultInterpolation ); + this.parameters = { + radius: radius, + detail: detail + }; } - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): - - static toJSON( track ) { - - const trackType = track.constructor; - - let json; + static fromJSON( data ) { - // derived classes can define a static toJSON method - if ( trackType.toJSON !== this.toJSON ) { + return new DodecahedronGeometry( data.radius, data.detail ); - json = trackType.toJSON( track ); + } - } else { +} - // by default, we assume the data can be serialized as-is - json = { +const _v0 = /*@__PURE__*/ new Vector3(); +const _v1$1 = /*@__PURE__*/ new Vector3(); +const _normal = /*@__PURE__*/ new Vector3(); +const _triangle = /*@__PURE__*/ new Triangle(); - 'name': track.name, - 'times': AnimationUtils.convertArray( track.times, Array ), - 'values': AnimationUtils.convertArray( track.values, Array ) +class EdgesGeometry extends BufferGeometry { - }; + constructor( geometry = null, thresholdAngle = 1 ) { - const interpolation = track.getInterpolation(); + super(); - if ( interpolation !== track.DefaultInterpolation ) { + this.type = 'EdgesGeometry'; - json.interpolation = interpolation; + this.parameters = { + geometry: geometry, + thresholdAngle: thresholdAngle + }; - } + if ( geometry !== null ) { - } + const precisionPoints = 4; + const precision = Math.pow( 10, precisionPoints ); + const thresholdDot = Math.cos( DEG2RAD * thresholdAngle ); - json.type = track.ValueTypeName; // mandatory + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute( 'position' ); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; - return json; + const indexArr = [ 0, 0, 0 ]; + const vertKeys = [ 'a', 'b', 'c' ]; + const hashes = new Array( 3 ); - } + const edgeData = {}; + const vertices = []; + for ( let i = 0; i < indexCount; i += 3 ) { - InterpolantFactoryMethodDiscrete( result ) { + if ( indexAttr ) { - return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); + indexArr[ 0 ] = indexAttr.getX( i ); + indexArr[ 1 ] = indexAttr.getX( i + 1 ); + indexArr[ 2 ] = indexAttr.getX( i + 2 ); - } + } else { - InterpolantFactoryMethodLinear( result ) { + indexArr[ 0 ] = i; + indexArr[ 1 ] = i + 1; + indexArr[ 2 ] = i + 2; - return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); + } - } + const { a, b, c } = _triangle; + a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); + b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); + c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); + _triangle.getNormal( _normal ); - InterpolantFactoryMethodSmooth( result ) { + // create hashes for the edge from the vertices + hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; + hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; + hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; - return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + // skip degenerate triangles + if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { - } + continue; - setInterpolation( interpolation ) { + } - let factoryMethod; + // iterate over every edge + for ( let j = 0; j < 3; j ++ ) { - switch ( interpolation ) { + // get the first and next vertex making up the edge + const jNext = ( j + 1 ) % 3; + const vecHash0 = hashes[ j ]; + const vecHash1 = hashes[ jNext ]; + const v0 = _triangle[ vertKeys[ j ] ]; + const v1 = _triangle[ vertKeys[ jNext ] ]; - case InterpolateDiscrete: + const hash = `${ vecHash0 }_${ vecHash1 }`; + const reverseHash = `${ vecHash1 }_${ vecHash0 }`; - factoryMethod = this.InterpolantFactoryMethodDiscrete; + if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { - break; + // if we found a sibling edge add it into the vertex array if + // it meets the angle threshold and delete the edge from the map. + if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { - case InterpolateLinear: + vertices.push( v0.x, v0.y, v0.z ); + vertices.push( v1.x, v1.y, v1.z ); - factoryMethod = this.InterpolantFactoryMethodLinear; + } - break; + edgeData[ reverseHash ] = null; - case InterpolateSmooth: + } else if ( ! ( hash in edgeData ) ) { - factoryMethod = this.InterpolantFactoryMethodSmooth; + // if we've already got an edge here then skip adding a new one + edgeData[ hash ] = { - break; + index0: indexArr[ j ], + index1: indexArr[ jNext ], + normal: _normal.clone(), - } + }; - if ( factoryMethod === undefined ) { + } - const 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 ) { + // iterate over all remaining, unmatched edges and add them to the vertex array + for ( const key in edgeData ) { - this.setInterpolation( this.DefaultInterpolation ); + if ( edgeData[ key ] ) { - } else { + const { index0, index1 } = edgeData[ key ]; + _v0.fromBufferAttribute( positionAttr, index0 ); + _v1$1.fromBufferAttribute( positionAttr, index1 ); - throw new Error( message ); // fatal, in this case + vertices.push( _v0.x, _v0.y, _v0.z ); + vertices.push( _v1$1.x, _v1$1.y, _v1$1.z ); } } - console.warn( 'THREE.KeyframeTrack:', message ); - return this; + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); } - this.createInterpolant = factoryMethod; + } - return this; +} - } +class Shape extends Path { - getInterpolation() { + constructor( points ) { - switch ( this.createInterpolant ) { + super( points ); - case this.InterpolantFactoryMethodDiscrete: + this.uuid = generateUUID(); - return InterpolateDiscrete; + this.type = 'Shape'; - case this.InterpolantFactoryMethodLinear: + this.holes = []; - return InterpolateLinear; + } - case this.InterpolantFactoryMethodSmooth: + getPointsHoles( divisions ) { - return InterpolateSmooth; + const holesPts = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); } + return holesPts; + } - getValueSize() { + // get points of shape and holes (keypoints based on segments parameter) - return this.values.length / this.times.length; + extractPoints( divisions ) { + + return { + + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + + }; } - // move all keyframes either forwards or backwards in time - shift( timeOffset ) { + copy( source ) { - if ( timeOffset !== 0.0 ) { + super.copy( source ); - const times = this.times; + this.holes = []; - for ( let i = 0, n = times.length; i !== n; ++ i ) { + for ( let i = 0, l = source.holes.length; i < l; i ++ ) { - times[ i ] += timeOffset; + const hole = source.holes[ i ]; - } + this.holes.push( hole.clone() ); } @@ -33150,2658 +34011,2853 @@ class KeyframeTrack { } - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale( timeScale ) { - - if ( timeScale !== 1.0 ) { + toJSON() { - const times = this.times; + const data = super.toJSON(); - for ( let i = 0, n = times.length; i !== n; ++ i ) { + data.uuid = this.uuid; + data.holes = []; - times[ i ] *= timeScale; + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { - } + const hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); } - return this; + return data; } - // 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( startTime, endTime ) { + fromJSON( json ) { - const times = this.times, - nKeys = times.length; + super.fromJSON( json ); - let from = 0, - to = nKeys - 1; + this.uuid = json.uuid; + this.holes = []; - while ( from !== nKeys && times[ from ] < startTime ) { + for ( let i = 0, l = json.holes.length; i < l; i ++ ) { - ++ from; + const hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); } - while ( to !== - 1 && times[ to ] > endTime ) { + return this; - -- to; + } - } +} - ++ to; // inclusive -> exclusive bound +/** + * Port from https://github.com/mapbox/earcut (v2.2.2) + */ - if ( from !== 0 || to !== nKeys ) { +const Earcut = { - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) { + triangulate: function ( data, holeIndices, dim = 2 ) { - to = Math.max( to, 1 ); - from = to - 1; + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; + let outerNode = linkedList( data, 0, outerLen, dim, true ); + const triangles = []; + + if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + + let minX, minY, maxX, maxY, x, y, invSize; + + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if ( data.length > 80 * dim ) { + + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; + + for ( let i = dim; i < outerLen; i += dim ) { + + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; } - const stride = this.getValueSize(); - this.times = AnimationUtils.arraySlice( times, from, to ); - this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride ); + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 1 / invSize : 0; } - return this; + earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); + + return triangles; } - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate() { +}; - let valid = true; +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList( data, start, end, dim, clockwise ) { - const valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { + let i, last; - console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); - valid = false; + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { - } + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); - const times = this.times, - values = this.values, + } else { - nKeys = times.length; + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); - if ( nKeys === 0 ) { + } - console.error( 'THREE.KeyframeTrack: Track is empty.', this ); - valid = false; + if ( last && equals( last, last.next ) ) { - } + removeNode( last ); + last = last.next; - let prevTime = null; + } - for ( let i = 0; i !== nKeys; i ++ ) { + return last; - const currTime = times[ i ]; +} - if ( typeof currTime === 'number' && isNaN( currTime ) ) { +// eliminate colinear or duplicate points +function filterPoints( start, end ) { - console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); - valid = false; - break; + if ( ! start ) return start; + if ( ! end ) end = start; - } + let p = start, + again; + do { - if ( prevTime !== null && prevTime > currTime ) { + again = false; - console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); - valid = false; - break; + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { - } + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; - prevTime = currTime; + } else { + + p = p.next; } - if ( values !== undefined ) { + } while ( again || p !== end ); - if ( AnimationUtils.isTypedArray( values ) ) { + return end; - for ( let i = 0, n = values.length; i !== n; ++ i ) { +} - const value = values[ i ]; +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { - if ( isNaN( value ) ) { + if ( ! ear ) return; - console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); - valid = false; - break; + // interlink polygon nodes in z-order + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); - } + let stop = ear, + prev, next; - } + // iterate through ears, slicing them one by one + while ( ear.prev !== ear.next ) { - } + prev = ear.prev; + next = ear.next; + + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + + // cut off the triangle + triangles.push( prev.i / dim ); + triangles.push( ear.i / dim ); + triangles.push( next.i / dim ); + + removeNode( ear ); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; } - return valid; + ear = next; - } + // if we looped through the whole remaining polygon and can't find any more ears + if ( ear === stop ) { - // 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() { + // try filtering points and slicing again + if ( ! pass ) { - // times or values may be shared with other tracks, so overwriting is unsafe - const times = AnimationUtils.arraySlice( this.times ), - values = AnimationUtils.arraySlice( this.values ), - stride = this.getValueSize(), + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); - smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + // if this didn't work, try curing all small self-intersections locally - lastIndex = times.length - 1; + } else if ( pass === 1 ) { - let writeIndex = 1; + ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); - for ( let i = 1; i < lastIndex; ++ i ) { + // as a last resort, try splitting the remaining polygon into two - let keep = false; + } else if ( pass === 2 ) { - const time = times[ i ]; - const timeNext = times[ i + 1 ]; + splitEarcut( ear, triangles, dim, minX, minY, invSize ); - // remove adjacent keyframes scheduled at the same time + } - if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { + break; - if ( ! smoothInterpolation ) { + } - // remove unnecessary keyframes same as their neighbors + } - const offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; +} - for ( let j = 0; j !== stride; ++ j ) { +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar( ear ) { - const value = values[ offset + j ]; + const a = ear.prev, + b = ear, + c = ear.next; - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - keep = true; - break; + // now make sure we don't have other points inside the potential ear + let p = ear.next.next; - } + while ( p !== ear.prev ) { - } + if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.next; - } else { + } - keep = true; + return true; - } +} - } +function isEarHashed( ear, minX, minY, invSize ) { - // in-place compaction + const a = ear.prev, + b = ear, + c = ear.next; - if ( keep ) { + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - if ( i !== writeIndex ) { + // triangle bbox; min & max are calculated like this for speed + const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), + minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), + maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), + maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); - times[ writeIndex ] = times[ i ]; + // z-order range for the current triangle bbox; + const minZ = zOrder( minTX, minTY, minX, minY, invSize ), + maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); - const readOffset = i * stride, - writeOffset = writeIndex * stride; + let p = ear.prevZ, + n = ear.nextZ; - for ( let j = 0; j !== stride; ++ j ) { + // look for points inside the triangle in both directions + while ( p && p.z >= minZ && n && n.z <= maxZ ) { - values[ writeOffset + j ] = values[ readOffset + j ]; + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; - } + if ( n !== ear.prev && n !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && + area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; - } + } - ++ writeIndex; + // look for remaining points in decreasing z-order + while ( p && p.z >= minZ ) { - } + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; - } + } - // flush last keyframe (compaction looks ahead) + // look for remaining points in increasing z-order + while ( n && n.z <= maxZ ) { - if ( lastIndex > 0 ) { + if ( n !== ear.prev && n !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && + area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; - times[ writeIndex ] = times[ lastIndex ]; + } - for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { + return true; - values[ writeOffset + j ] = values[ readOffset + j ]; +} - } +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections( start, triangles, dim ) { - ++ writeIndex; + let p = start; + do { - } + const a = p.prev, + b = p.next.next; - if ( writeIndex !== times.length ) { + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { - this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + triangles.push( a.i / dim ); + triangles.push( p.i / dim ); + triangles.push( b.i / dim ); - } else { + // remove two nodes involved + removeNode( p ); + removeNode( p.next ); - this.times = times; - this.values = values; + p = start = b; } - return this; + p = p.next; - } + } while ( p !== start ); - clone() { + return filterPoints( p ); - const times = AnimationUtils.arraySlice( this.times, 0 ); - const values = AnimationUtils.arraySlice( this.values, 0 ); +} - const TypedKeyframeTrack = this.constructor; - const track = new TypedKeyframeTrack( this.name, times, values ); +// try splitting polygon into two and triangulate them independently +function splitEarcut( start, triangles, dim, minX, minY, invSize ) { - // Interpolant argument to constructor is not saved, so copy the factory method directly. - track.createInterpolant = this.createInterpolant; + // look for a valid diagonal that divides the polygon into two + let a = start; + do { - return track; + let b = a.next.next; + while ( b !== a.prev ) { - } + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { -} + // split the polygon in two by the diagonal + let c = splitPolygon( a, b ); -KeyframeTrack.prototype.TimeBufferType = Float32Array; -KeyframeTrack.prototype.ValueBufferType = Float32Array; -KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + // filter colinear points around the cuts + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); -/** - * A Track of Boolean keyframe values. - */ -class BooleanKeyframeTrack extends KeyframeTrack {} + // run earcut on each half + earcutLinked( a, triangles, dim, minX, minY, invSize ); + earcutLinked( c, triangles, dim, minX, minY, invSize ); + return; -BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; -BooleanKeyframeTrack.prototype.ValueBufferType = Array; -BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; -BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; -BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + } -/** - * A Track of keyframe values that represent color. - */ -class ColorKeyframeTrack extends KeyframeTrack {} + b = b.next; -ColorKeyframeTrack.prototype.ValueTypeName = 'color'; + } -/** - * A Track of numeric keyframe values. - */ -class NumberKeyframeTrack extends KeyframeTrack {} + a = a.next; -NumberKeyframeTrack.prototype.ValueTypeName = 'number'; + } while ( a !== start ); -/** - * Spherical linear unit quaternion interpolant. - */ +} -function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles( data, holeIndices, outerNode, dim ) { - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + const queue = []; + let i, len, start, end, list; -} + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { -QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); - constructor: QuaternionLinearInterpolant, + } - interpolate_: function ( i1, t0, t, t1 ) { + queue.sort( compareX ); - const result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { - alpha = ( t - t0 ) / ( t1 - t0 ); + eliminateHole( queue[ i ], outerNode ); + outerNode = filterPoints( outerNode, outerNode.next ); - let offset = i1 * stride; + } - for ( let end = offset + stride; offset !== end; offset += 4 ) { + return outerNode; - Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); +} - } +function compareX( a, b ) { - return result; + return a.x - b.x; - } +} -} ); +// find a bridge between vertices that connects hole with an outer ring and link it +function eliminateHole( hole, outerNode ) { -/** - * A Track of quaternion keyframe values. - */ -class QuaternionKeyframeTrack extends KeyframeTrack { + outerNode = findHoleBridge( hole, outerNode ); + if ( outerNode ) { - InterpolantFactoryMethodLinear( result ) { + const b = splitPolygon( outerNode, hole ); - return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); + // filter collinear points around the cuts + filterPoints( outerNode, outerNode.next ); + filterPoints( b, b.next ); } } -QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; -// ValueBufferType is inherited -QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; -QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - -/** - * A Track that interpolates Strings - */ -class StringKeyframeTrack extends KeyframeTrack {} +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge( hole, outerNode ) { -StringKeyframeTrack.prototype.ValueTypeName = 'string'; -StringKeyframeTrack.prototype.ValueBufferType = Array; -StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; -StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; -StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = - Infinity, m; -/** - * A Track of vectored keyframe values. - */ -class VectorKeyframeTrack extends KeyframeTrack {} + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { -VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { -class AnimationClip { + const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); + if ( x <= hx && x > qx ) { - constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) { + qx = x; + if ( x === hx ) { - this.name = name; - this.tracks = tracks; - this.duration = duration; - this.blendMode = blendMode; + if ( hy === p.y ) return p; + if ( hy === p.next.y ) return p.next; - this.uuid = MathUtils.generateUUID(); + } - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { + m = p.x < p.next.x ? p : p.next; - this.resetDuration(); + } } - } - + p = p.next; - static parse( json ) { + } while ( p !== outerNode ); - const tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); + if ( ! m ) return null; - for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { + if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint - tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point - } + const stop = m, + mx = m.x, + my = m.y; + let tanMin = Infinity, tan; - const clip = new this( json.name, json.duration, tracks, json.blendMode ); - clip.uuid = json.uuid; + p = m; - return clip; + do { - } + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { - static toJSON( clip ) { + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential - const tracks = [], - clipTracks = clip.tracks; + if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { - const json = { + m = p; + tanMin = tan; - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks, - 'uuid': clip.uuid, - 'blendMode': clip.blendMode + } - }; + } - for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { + p = p.next; - tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + } while ( p !== stop ); - } + return m; - return json; +} - } +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector( m, p ) { - static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { + return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; - const numMorphTargets = morphTargetSequence.length; - const tracks = []; +} - for ( let i = 0; i < numMorphTargets; i ++ ) { +// interlink polygon nodes in z-order +function indexCurve( start, minX, minY, invSize ) { - let times = []; - let values = []; + let p = start; + do { - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); + if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; - values.push( 0, 1, 0 ); + } while ( p !== start ); - const order = AnimationUtils.getKeyframeOrder( times ); - times = AnimationUtils.sortedArray( times, 1, order ); - values = AnimationUtils.sortedArray( values, 1, order ); + p.prevZ.nextZ = null; + p.prevZ = null; - // 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 ) { + sortLinked( p ); - times.push( numMorphTargets ); - values.push( values[ 0 ] ); +} - } +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked( list ) { - tracks.push( - new NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); + let i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; - } + do { - return new this( name, - 1, tracks ); + p = list; + list = null; + tail = null; + numMerges = 0; - } + while ( p ) { - static findByName( objectOrClipArray, name ) { + numMerges ++; + q = p; + pSize = 0; + for ( i = 0; i < inSize; i ++ ) { - let clipArray = objectOrClipArray; + pSize ++; + q = q.nextZ; + if ( ! q ) break; - if ( ! Array.isArray( objectOrClipArray ) ) { + } - const o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + qSize = inSize; - } + while ( pSize > 0 || ( qSize > 0 && q ) ) { - for ( let i = 0; i < clipArray.length; i ++ ) { + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { - if ( clipArray[ i ].name === name ) { + e = p; + p = p.nextZ; + pSize --; - return clipArray[ i ]; + } else { - } + e = q; + q = q.nextZ; + qSize --; - } + } - return null; + if ( tail ) tail.nextZ = e; + else list = e; - } + e.prevZ = tail; + tail = e; - static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { + } - const animationToMorphTargets = {}; + p = q; - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - const pattern = /^([\w-]*?)([\d]+)$/; + } - // sort morph target names into animation groups based - // patterns like Walk_001, Walk_002, Run_001, Run_002 - for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { + tail.nextZ = null; + inSize *= 2; - const morphTarget = morphTargets[ i ]; - const parts = morphTarget.name.match( pattern ); + } while ( numMerges > 1 ); - if ( parts && parts.length > 1 ) { + return list; - const name = parts[ 1 ]; +} - let animationMorphTargets = animationToMorphTargets[ name ]; +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder( x, y, minX, minY, invSize ) { - if ( ! animationMorphTargets ) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * ( x - minX ) * invSize; + y = 32767 * ( y - minY ) * invSize; - animationToMorphTargets[ name ] = animationMorphTargets = []; + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; - } + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; - animationMorphTargets.push( morphTarget ); + return x | ( y << 1 ); - } +} - } +// find the leftmost node of a polygon ring +function getLeftmost( start ) { - const clips = []; + let p = start, + leftmost = start; + do { - for ( const name in animationToMorphTargets ) { + if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; + p = p.next; - clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + } while ( p !== start ); - } + return leftmost; - return clips; +} - } +// check if a point lies within a convex triangle +function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { - // parse the animation.hierarchy format - static parseAnimation( animation, bones ) { + return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && + ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && + ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; - if ( ! animation ) { +} - console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); - return null; +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal( a, b ) { - } + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges + ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible + ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case - const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { +} - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { +// signed area of a triangle +function area( p, q, r ) { - const times = []; - const values = []; + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); - AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); +} - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { +// check if two points are equal +function equals( p1, p2 ) { - destTracks.push( new trackType( trackName, times, values ) ); + return p1.x === p2.x && p1.y === p2.y; - } +} - } +// check if two segments intersect +function intersects( p1, q1, p2, q2 ) { - }; + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); - const tracks = []; + if ( o1 !== o2 && o3 !== o4 ) return true; // general case - const clipName = animation.name || 'default'; - const fps = animation.fps || 30; - const blendMode = animation.blendMode; + if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 - // automatic length determination in AnimationClip. - let duration = animation.length || - 1; + return false; - const hierarchyTracks = animation.hierarchy || []; +} - for ( let h = 0; h < hierarchyTracks.length; h ++ ) { +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment( p, q, r ) { - const animationKeys = hierarchyTracks[ h ].keys; + return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); - // skip empty tracks - if ( ! animationKeys || animationKeys.length === 0 ) continue; +} - // process morph targets - if ( animationKeys[ 0 ].morphTargets ) { +function sign( num ) { - // figure out all morph targets used in this track - const morphTargetNames = {}; + return num > 0 ? 1 : num < 0 ? - 1 : 0; - let k; +} - for ( k = 0; k < animationKeys.length; k ++ ) { +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon( a, b ) { - if ( animationKeys[ k ].morphTargets ) { + let p = a; + do { - for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) return true; + p = p.next; - morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; + } while ( p !== a ); - } + return false; - } +} - } +// check if a polygon diagonal is locally inside the polygon +function locallyInside( a, b ) { - // create a track for each morph target with all zero - // morphTargetInfluences except for the keys in which - // the morphTarget is named. - for ( const morphTargetName in morphTargetNames ) { + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; - const times = []; - const values = []; +} - for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside( a, b ) { - const animationKey = animationKeys[ k ]; + let p = a, + inside = false; + const px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; + do { - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) + inside = ! inside; + p = p.next; - } + } while ( p !== a ); - tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + return inside; - } +} - duration = morphTargetNames.length * ( fps || 1.0 ); +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon( a, b ) { - } else { + const a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; - // ...assume skeletal animation + a.next = b; + b.prev = a; - const boneName = '.bones[' + bones[ h ].name + ']'; + a2.next = an; + an.prev = a2; - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + b2.next = a2; + a2.prev = b2; - addNonemptyTrack( - QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + bp.next = b2; + b2.prev = bp; - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + return b2; - } +} - } +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode( i, x, y, last ) { - if ( tracks.length === 0 ) { + const p = new Node( i, x, y ); - return null; + if ( ! last ) { - } + p.prev = p; + p.next = p; - const clip = new this( clipName, duration, tracks, blendMode ); + } else { - return clip; + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; } - resetDuration() { + return p; - const tracks = this.tracks; - let duration = 0; +} - for ( let i = 0, n = tracks.length; i !== n; ++ i ) { +function removeNode( p ) { - const track = this.tracks[ i ]; + p.next.prev = p.prev; + p.prev.next = p.next; - duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; - } +} - this.duration = duration; +function Node( i, x, y ) { - return this; + // vertex index in coordinates array + this.i = i; - } + // vertex coordinates + this.x = x; + this.y = y; - trim() { + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; - for ( let i = 0; i < this.tracks.length; i ++ ) { + // z-order curve value + this.z = null; - this.tracks[ i ].trim( 0, this.duration ); + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; - } + // indicates whether this is a steiner point + this.steiner = false; - return this; +} - } +function signedArea( data, start, end, dim ) { - validate() { + let sum = 0; + for ( let i = start, j = end - dim; i < end; i += dim ) { - let valid = true; + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; - for ( let i = 0; i < this.tracks.length; i ++ ) { + } - valid = valid && this.tracks[ i ].validate(); + return sum; - } +} - return valid; +class ShapeUtils { - } + // calculate area of the contour polygon - optimize() { + static area( contour ) { - for ( let i = 0; i < this.tracks.length; i ++ ) { + const n = contour.length; + let a = 0.0; - this.tracks[ i ].optimize(); + for ( let p = n - 1, q = 0; q < n; p = q ++ ) { + + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; } - return this; + return a * 0.5; } - clone() { + static isClockWise( pts ) { - const tracks = []; + return ShapeUtils.area( pts ) < 0; - for ( let i = 0; i < this.tracks.length; i ++ ) { + } - tracks.push( this.tracks[ i ].clone() ); + static triangulateShape( contour, holes ) { - } + const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + const holeIndices = []; // array of hole indices + const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] - return new this.constructor( this.name, this.duration, tracks, this.blendMode ); + removeDupEndPts( contour ); + addContour( vertices, contour ); - } + // - toJSON() { + let holeIndex = contour.length; - return this.constructor.toJSON( this ); + holes.forEach( removeDupEndPts ); - } + for ( let i = 0; i < holes.length; i ++ ) { -} + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); -function getTrackTypeForValueTypeName( typeName ) { + } - switch ( typeName.toLowerCase() ) { + // - case 'scalar': - case 'double': - case 'float': - case 'number': - case 'integer': + const triangles = Earcut.triangulate( vertices, holeIndices ); - return NumberKeyframeTrack; + // - case 'vector': - case 'vector2': - case 'vector3': - case 'vector4': + for ( let i = 0; i < triangles.length; i += 3 ) { - return VectorKeyframeTrack; + faces.push( triangles.slice( i, i + 3 ) ); - case 'color': + } - return ColorKeyframeTrack; + return faces; - case 'quaternion': + } - return QuaternionKeyframeTrack; +} - case 'bool': - case 'boolean': +function removeDupEndPts( points ) { - return BooleanKeyframeTrack; + const l = points.length; - case 'string': + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - return StringKeyframeTrack; + points.pop(); } - throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); - } -function parseKeyframeTrack( json ) { +function addContour( vertices, contour ) { - if ( json.type === undefined ) { + for ( let i = 0; i < contour.length; i ++ ) { - throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); } - const trackType = getTrackTypeForValueTypeName( json.type ); +} - if ( json.times === undefined ) { +/** + * 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 + * depth: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline (including bevelOffset) is bevel + * bevelOffset: , // how far from shape outline does bevel start + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ - const times = [], values = []; +class ExtrudeGeometry extends BufferGeometry { - AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) { - json.times = times; - json.values = values; + super(); - } + this.type = 'ExtrudeGeometry'; - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { + this.parameters = { + shapes: shapes, + options: options + }; - return trackType.parse( json ); + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - } else { + const scope = this; - // by default, we assume a constructor compatible with the base - return new trackType( json.name, json.times, json.values, json.interpolation ); + const verticesArray = []; + const uvArray = []; - } + for ( let i = 0, l = shapes.length; i < l; i ++ ) { -} + const shape = shapes[ i ]; + addShape( shape ); -const Cache = { + } - enabled: false, + // build geometry - files: {}, + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); - add: function ( key, file ) { + this.computeVertexNormals(); - if ( this.enabled === false ) return; + // functions - // console.log( 'THREE.Cache', 'Adding key:', key ); + function addShape( shape ) { - this.files[ key ] = file; + const placeholder = []; - }, + // options - get: function ( key ) { + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; - if ( this.enabled === false ) return; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - // console.log( 'THREE.Cache', 'Checking key:', key ); + const extrudePath = options.extrudePath; - return this.files[ key ]; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; - }, + // - remove: function ( key ) { + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; - delete this.files[ key ]; + if ( extrudePath ) { - }, + extrudePts = extrudePath.getSpacedPoints( steps ); - clear: function () { + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - this.files = {}; + // SETUP TNB variables - } + // TODO1 - have a .isClosed in spline? -}; + splineTube = extrudePath.computeFrenetFrames( steps, false ); -function LoadingManager( onLoad, onProgress, onError ) { + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - const scope = this; + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + + } - let isLoading = false; - let itemsLoaded = 0; - let itemsTotal = 0; - let urlModifier = undefined; - const handlers = []; + // Safeguards if bevels are not enabled - // Refer to #5689 for the reason why we don't set .onStart - // in the constructor + if ( ! bevelEnabled ) { - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; - this.itemStart = function ( url ) { + } - itemsTotal ++; + // Variables initialization - if ( isLoading === false ) { + const shapePoints = shape.extractPoints( curveSegments ); - if ( scope.onStart !== undefined ) { + let vertices = shapePoints.shape; + const holes = shapePoints.holes; - scope.onStart( url, itemsLoaded, itemsTotal ); + const reverse = ! ShapeUtils.isClockWise( vertices ); - } + if ( reverse ) { - } + vertices = vertices.reverse(); - isLoading = true; + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - }; + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - this.itemEnd = function ( url ) { + const ahole = holes[ h ]; - itemsLoaded ++; + if ( ShapeUtils.isClockWise( ahole ) ) { - if ( scope.onProgress !== undefined ) { + holes[ h ] = ahole.reverse(); - scope.onProgress( url, itemsLoaded, itemsTotal ); + } - } + } - if ( itemsLoaded === itemsTotal ) { + } - isLoading = false; - if ( scope.onLoad !== undefined ) { + const faces = ShapeUtils.triangulateShape( vertices, holes ); - scope.onLoad(); + /* Vertices */ - } + const contour = vertices; // vertices has all points but contour has only points of circumference - } + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - }; + const ahole = holes[ h ]; - this.itemError = function ( url ) { + vertices = vertices.concat( ahole ); - if ( scope.onError !== undefined ) { + } - scope.onError( url ); - } + function scalePt2( pt, vec, size ) { - }; + if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); - this.resolveURL = function ( url ) { + return vec.clone().multiplyScalar( size ).add( pt ); - if ( urlModifier ) { + } - return urlModifier( url ); + const vlen = vertices.length, flen = faces.length; - } - return url; + // Find directions for point movement - }; - this.setURLModifier = function ( transform ) { + function getBevelVec( inPt, inPrev, inNext ) { - urlModifier = transform; + // 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. - return this; + let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt - }; + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - this.addHandler = function ( regex, loader ) { + const v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; - handlers.push( regex, loader ); + const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - return this; + // check for collinear edges + const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - }; + if ( Math.abs( collinear0 ) > Number.EPSILON ) { - this.removeHandler = function ( regex ) { + // not collinear - const index = handlers.indexOf( regex ); + // length of vectors for normalizing - if ( index !== - 1 ) { + const v_prev_len = Math.sqrt( v_prev_lensq ); + const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - handlers.splice( index, 2 ); + // shift adjacent points by unit vectors to the left - } + const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - return this; + const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - }; + // scaling factor for v_prev to intersection point + + const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + // vector from inPt to intersection point - this.getHandler = function ( file ) { + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - for ( let i = 0, l = handlers.length; i < l; i += 2 ) { + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { - const regex = handlers[ i ]; - const loader = handlers[ i + 1 ]; + return new Vector2( v_trans_x, v_trans_y ); - if ( regex.global ) regex.lastIndex = 0; // see #17920 + } else { - if ( regex.test( file ) ) { + shrink_by = Math.sqrt( v_trans_lensq / 2 ); - return loader; + } - } + } else { - } + // handle special case of collinear edges - return null; + let direction_eq = false; // assumes: opposite - }; + if ( v_prev_x > Number.EPSILON ) { -} + if ( v_next_x > Number.EPSILON ) { -const DefaultLoadingManager = new LoadingManager(); + direction_eq = true; -function Loader( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + } else { - this.crossOrigin = 'anonymous'; - this.withCredentials = false; - this.path = ''; - this.resourcePath = ''; - this.requestHeader = {}; + if ( v_prev_x < - Number.EPSILON ) { -} + if ( v_next_x < - Number.EPSILON ) { -Object.assign( Loader.prototype, { + direction_eq = true; - load: function ( /* url, onLoad, onProgress, onError */ ) {}, + } - loadAsync: function ( url, onProgress ) { + } else { - const scope = this; + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { - return new Promise( function ( resolve, reject ) { + direction_eq = true; - scope.load( url, resolve, onProgress, reject ); + } - } ); + } - }, + } - parse: function ( /* data */ ) {}, + if ( direction_eq ) { - setCrossOrigin: function ( crossOrigin ) { + // 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 ); - this.crossOrigin = crossOrigin; - return this; + } 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 ); - setWithCredentials: function ( value ) { + } - this.withCredentials = value; - return this; + } - }, + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - setPath: function ( path ) { + } - this.path = path; - return this; - }, + const contourMovements = []; - setResourcePath: function ( resourcePath ) { + for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - this.resourcePath = resourcePath; - return this; + if ( j === il ) j = 0; + if ( k === il ) k = 0; - }, + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) - setRequestHeader: function ( requestHeader ) { + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - this.requestHeader = requestHeader; - return this; + } - } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); -} ); + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { -const loading = {}; + const ahole = holes[ h ]; -function FileLoader( manager ) { + oneHoleMovements = []; - Loader.call( this, manager ); + for ( let 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; -FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - constructor: FileLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - if ( url === undefined ) url = ''; + } - if ( this.path !== undefined ) url = this.path + url; - url = this.manager.resolveURL( url ); + // Loop bevelSegments, 1 for the front, 1 for the back - const scope = this; + for ( let b = 0; b < bevelSegments; b ++ ) { - const cached = Cache.get( url ); + //for ( b = bevelSegments; b > 0; b -- ) { - if ( cached !== undefined ) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; - scope.manager.itemStart( url ); + // contract shape - setTimeout( function () { + for ( let i = 0, il = contour.length; i < il; i ++ ) { - if ( onLoad ) onLoad( cached ); + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - scope.manager.itemEnd( url ); + v( vert.x, vert.y, - z ); - }, 0 ); + } - return cached; + // expand holes - } + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - // Check if request is duplicate + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - if ( loading[ url ] !== undefined ) { + for ( let i = 0, il = ahole.length; i < il; i ++ ) { - loading[ url ].push( { + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - onLoad: onLoad, - onProgress: onProgress, - onError: onError + v( vert.x, vert.y, - z ); - } ); + } - return; + } - } + } - // Check for data: URI - const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/; - const dataUriRegexResult = url.match( dataUriRegex ); - let request; + const bs = bevelSize + bevelOffset; - // Safari can not handle Data URIs through XMLHttpRequest so process manually - if ( dataUriRegexResult ) { + // Back facing vertices - const mimeType = dataUriRegexResult[ 1 ]; - const isBase64 = !! dataUriRegexResult[ 2 ]; + for ( let i = 0; i < vlen; i ++ ) { - let data = dataUriRegexResult[ 3 ]; - data = decodeURIComponent( data ); + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - if ( isBase64 ) data = atob( data ); + if ( ! extrudeByPath ) { - try { + v( vert.x, vert.y, 0 ); - let response; - const responseType = ( this.responseType || '' ).toLowerCase(); + } else { - switch ( responseType ) { + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - case 'arraybuffer': - case 'blob': + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - const view = new Uint8Array( data.length ); + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - for ( let i = 0; i < data.length; i ++ ) { + v( position2.x, position2.y, position2.z ); - view[ i ] = data.charCodeAt( i ); + } - } + } - if ( responseType === 'blob' ) { + // Add stepped vertices... + // Including front facing vertices - response = new Blob( [ view.buffer ], { type: mimeType } ); + for ( let s = 1; s <= steps; s ++ ) { - } else { + for ( let i = 0; i < vlen; i ++ ) { - response = view.buffer; + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - } + if ( ! extrudeByPath ) { - break; + v( vert.x, vert.y, depth / steps * s ); - case 'document': + } else { - const parser = new DOMParser(); - response = parser.parseFromString( data, mimeType ); + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - break; + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - case 'json': + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); - response = JSON.parse( data ); + v( position2.x, position2.y, position2.z ); - break; + } - default: // 'text' or other + } - response = data; + } - break; - } + // Add bevel segments planes - // Wait for next browser tick like standard XMLHttpRequest event dispatching does - setTimeout( function () { + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( let b = bevelSegments - 1; b >= 0; b -- ) { - if ( onLoad ) onLoad( response ); + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; - scope.manager.itemEnd( url ); + // contract shape - }, 0 ); + for ( let i = 0, il = contour.length; i < il; i ++ ) { - } catch ( error ) { + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); - // Wait for next browser tick like standard XMLHttpRequest event dispatching does - setTimeout( function () { + } - if ( onError ) onError( error ); + // expand holes - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - }, 0 ); + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - } + for ( let i = 0, il = ahole.length; i < il; i ++ ) { - } else { + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - // Initialise array for duplicate requests + if ( ! extrudeByPath ) { - loading[ url ] = []; + v( vert.x, vert.y, depth + z ); - loading[ url ].push( { + } else { - onLoad: onLoad, - onProgress: onProgress, - onError: onError + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - } ); + } - request = new XMLHttpRequest(); + } - request.open( 'GET', url, true ); + } - request.addEventListener( 'load', function ( event ) { + } - const response = this.response; + /* Faces */ - const callbacks = loading[ url ]; + // Top and bottom faces - delete loading[ url ]; + buildLidFaces(); - if ( this.status === 200 || this.status === 0 ) { + // Sides faces - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + buildSideFaces(); - if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); - // Add to cache only on HTTP success, so that we do not cache - // error response bodies as proper responses to requests. - Cache.add( url, response ); + ///// Internal functions - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + function buildLidFaces() { - const callback = callbacks[ i ]; - if ( callback.onLoad ) callback.onLoad( response ); + const start = verticesArray.length / 3; - } + if ( bevelEnabled ) { - scope.manager.itemEnd( url ); + let layer = 0; // steps + 1 + let offset = vlen * layer; - } else { + // Bottom faces - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + for ( let i = 0; i < flen; i ++ ) { - const callback = callbacks[ i ]; - if ( callback.onError ) callback.onError( event ); + const face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); } - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + layer = steps + bevelSegments * 2; + offset = vlen * layer; - } + // Top faces - }, false ); + for ( let i = 0; i < flen; i ++ ) { - request.addEventListener( 'progress', function ( event ) { + const face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - const callbacks = loading[ url ]; + } - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + } else { - const callback = callbacks[ i ]; - if ( callback.onProgress ) callback.onProgress( event ); + // Bottom faces - } + for ( let i = 0; i < flen; i ++ ) { - }, false ); + const face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - request.addEventListener( 'error', function ( event ) { + } - const callbacks = loading[ url ]; + // Top faces - delete loading[ url ]; + for ( let i = 0; i < flen; i ++ ) { - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + const face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - const callback = callbacks[ i ]; - if ( callback.onError ) callback.onError( event ); + } } - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); - - }, false ); - - request.addEventListener( 'abort', function ( event ) { + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); - const callbacks = loading[ url ]; + } - delete loading[ url ]; + // Create faces for the z-sides of the shape - for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + function buildSideFaces() { - const callback = callbacks[ i ]; - if ( callback.onError ) callback.onError( event ); + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - } + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + const ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - }, false ); + //, true + layeroffset += ahole.length; - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + } - if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); - for ( const header in this.requestHeader ) { + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); - request.setRequestHeader( header, this.requestHeader[ header ] ); } - request.send( null ); + function sidewalls( contour, layeroffset ) { - } + let i = contour.length; - scope.manager.itemStart( url ); + while ( -- i >= 0 ) { - return request; + const j = i; + let k = i - 1; + if ( k < 0 ) k = contour.length - 1; - }, + //console.log('b', i,j, i-1, k,vertices.length); - setResponseType: function ( value ) { + for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { - this.responseType = value; - return this; + const slen1 = vlen * s; + const slen2 = vlen * ( s + 1 ); - }, + const a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; - setMimeType: function ( value ) { + f4( a, b, c, d ); - this.mimeType = value; - return this; + } - } + } -} ); + } -class AnimationLoader extends Loader { + function v( x, y, z ) { - constructor( manager ) { + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); - super( manager ); + } - } - load( url, onLoad, onProgress, onError ) { + function f3( a, b, c ) { - const scope = this; + addVertex( a ); + addVertex( b ); + addVertex( c ); - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); - try { + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); - onLoad( scope.parse( JSON.parse( text ) ) ); + } - } catch ( e ) { + function f4( a, b, c, d ) { - if ( onError ) { + addVertex( a ); + addVertex( b ); + addVertex( d ); - onError( e ); + addVertex( b ); + addVertex( c ); + addVertex( d ); - } else { - console.error( e ); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); - } + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); - scope.manager.itemError( url ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); } - }, onProgress, onError ); + function addVertex( index ) { - } + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); - parse( json ) { + } - const animations = []; - for ( let i = 0; i < json.length; i ++ ) { + function addUV( vector2 ) { - const clip = AnimationClip.parse( json[ i ] ); + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); - animations.push( clip ); + } } - return animations; - } -} - -/** - * Abstract Base class to block based textures loader (dds, pvr, ...) - * - * Sub classes have to implement the parse() method which will be used in load(). - */ - -function CompressedTextureLoader( manager ) { + toJSON() { - Loader.call( this, manager ); + const data = super.toJSON(); -} + const shapes = this.parameters.shapes; + const options = this.parameters.options; -CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + return toJSON$1( shapes, options, data ); - constructor: CompressedTextureLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + static fromJSON( data, shapes ) { - const scope = this; + const geometryShapes = []; - const images = []; + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { - const texture = new CompressedTexture(); + const shape = shapes[ data.shapes[ j ] ]; - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); + geometryShapes.push( shape ); - let loaded = 0; + } - function loadTexture( i ) { + const extrudePath = data.options.extrudePath; - loader.load( url[ i ], function ( buffer ) { + if ( extrudePath !== undefined ) { - const texDatas = scope.parse( buffer, true ); + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + } - loaded += 1; + return new ExtrudeGeometry( geometryShapes, data.options ); - if ( loaded === 6 ) { + } - if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; +} - texture.image = images; - texture.format = texDatas.format; - texture.needsUpdate = true; +const WorldUVGenerator = { - if ( onLoad ) onLoad( texture ); + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { - } + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; - }, onProgress, onError ); + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; - } + }, - if ( Array.isArray( url ) ) { + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { - for ( let i = 0, il = url.length; i < il; ++ i ) { + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const a_z = vertices[ indexA * 3 + 2 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const b_z = vertices[ indexB * 3 + 2 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + const c_z = vertices[ indexC * 3 + 2 ]; + const d_x = vertices[ indexD * 3 ]; + const d_y = vertices[ indexD * 3 + 1 ]; + const d_z = vertices[ indexD * 3 + 2 ]; - loadTexture( i ); + if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) { - } + 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 ) + ]; } else { - // compressed cubemap texture stored in a single DDS file - - loader.load( url, function ( buffer ) { - - const texDatas = scope.parse( buffer, true ); + 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 ) + ]; - if ( texDatas.isCubemap ) { + } - const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + } - for ( let f = 0; f < faces; f ++ ) { +}; - images[ f ] = { mipmaps: [] }; +function toJSON$1( shapes, options, data ) { - for ( let i = 0; i < texDatas.mipmapCount; i ++ ) { + data.shapes = []; - 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; + if ( Array.isArray( shapes ) ) { - } + for ( let i = 0, l = shapes.length; i < l; i ++ ) { - } + const shape = shapes[ i ]; - texture.image = images; + data.shapes.push( shape.uuid ); - } else { + } - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + } else { - } + data.shapes.push( shapes.uuid ); - if ( texDatas.mipmapCount === 1 ) { + } - texture.minFilter = LinearFilter; + data.options = Object.assign( {}, options ); - } + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); - texture.format = texDatas.format; - texture.needsUpdate = true; + return data; - if ( onLoad ) onLoad( texture ); +} - }, onProgress, onError ); +class IcosahedronGeometry extends PolyhedronGeometry { - } + constructor( radius = 1, detail = 0 ) { - return texture; + const t = ( 1 + Math.sqrt( 5 ) ) / 2; - } + const 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 + ]; -} ); + const 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 + ]; -class ImageLoader extends Loader { + super( vertices, indices, radius, detail ); - constructor( manager ) { + this.type = 'IcosahedronGeometry'; - super( manager ); + this.parameters = { + radius: radius, + detail: detail + }; } - load( url, onLoad, onProgress, onError ) { - - if ( this.path !== undefined ) url = this.path + url; - - url = this.manager.resolveURL( url ); + static fromJSON( data ) { - const scope = this; + return new IcosahedronGeometry( data.radius, data.detail ); - const cached = Cache.get( url ); + } - if ( cached !== undefined ) { +} - scope.manager.itemStart( url ); +class OctahedronGeometry extends PolyhedronGeometry { - setTimeout( function () { + constructor( radius = 1, detail = 0 ) { - if ( onLoad ) onLoad( cached ); + const vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, + 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; - scope.manager.itemEnd( url ); + const 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 + ]; - }, 0 ); + super( vertices, indices, radius, detail ); - return cached; + this.type = 'OctahedronGeometry'; - } + this.parameters = { + radius: radius, + detail: detail + }; - const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + } - function onImageLoad() { + static fromJSON( data ) { - image.removeEventListener( 'load', onImageLoad, false ); - image.removeEventListener( 'error', onImageError, false ); + return new OctahedronGeometry( data.radius, data.detail ); - Cache.add( url, this ); + } - if ( onLoad ) onLoad( this ); +} - scope.manager.itemEnd( url ); +class RingGeometry extends BufferGeometry { - } + constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { - function onImageError( event ) { + super(); - image.removeEventListener( 'load', onImageLoad, false ); - image.removeEventListener( 'error', onImageError, false ); + this.type = 'RingGeometry'; - if ( onError ) onError( event ); + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + thetaSegments = Math.max( 3, thetaSegments ); + phiSegments = Math.max( 1, phiSegments ); - } + // buffers - image.addEventListener( 'load', onImageLoad, false ); - image.addEventListener( 'error', onImageError, false ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - if ( url.substr( 0, 5 ) !== 'data:' ) { + // some helper variables - if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + let radius = innerRadius; + const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + const vertex = new Vector3(); + const uv = new Vector2(); - } + // generate vertices, normals and uvs - scope.manager.itemStart( url ); + for ( let j = 0; j <= phiSegments; j ++ ) { - image.src = url; + for ( let i = 0; i <= thetaSegments; i ++ ) { - return image; + // values are generate from the inside of the ring to the outside - } + const segment = thetaStart + i / thetaSegments * thetaLength; -} + // vertex -class CubeTextureLoader extends Loader { + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - constructor( manager ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - super( manager ); + // normal - } + normals.push( 0, 0, 1 ); - load( urls, onLoad, onProgress, onError ) { + // uv - const texture = new CubeTexture(); + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; - const loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + uvs.push( uv.x, uv.y ); - let loaded = 0; + } - function loadTexture( i ) { + // increase the radius for next row of vertices - loader.load( urls[ i ], function ( image ) { + radius += radiusStep; - texture.images[ i ] = image; + } - loaded ++; + // indices - if ( loaded === 6 ) { + for ( let j = 0; j < phiSegments; j ++ ) { - texture.needsUpdate = true; + const thetaSegmentLevel = j * ( thetaSegments + 1 ); - if ( onLoad ) onLoad( texture ); + for ( let i = 0; i < thetaSegments; i ++ ) { - } + const segment = i + thetaSegmentLevel; - }, undefined, onError ); + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; - } + // faces - for ( let i = 0; i < urls.length; ++ i ) { + indices.push( a, b, d ); + indices.push( b, c, d ); - loadTexture( i ); + } } - return texture; + // build geometry - } + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); -} + } -/** - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - * - * Sub classes have to implement the parse() method which will be used in load(). - */ + static fromJSON( data ) { -function DataTextureLoader( manager ) { + return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength ); - Loader.call( this, manager ); + } } -DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - - constructor: DataTextureLoader, - - load: function ( url, onLoad, onProgress, onError ) { - - const scope = this; - - const texture = new DataTexture(); +class ShapeGeometry extends BufferGeometry { - const loader = new FileLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.setRequestHeader( this.requestHeader ); - loader.setPath( this.path ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( buffer ) { + constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) { - const texData = scope.parse( buffer ); + super(); - if ( ! texData ) return; + this.type = 'ShapeGeometry'; - if ( texData.image !== undefined ) { + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; - texture.image = texData.image; + // buffers - } else if ( texData.data !== undefined ) { + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + // helper variables - } + let groupStart = 0; + let groupCount = 0; - texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; - texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + // allow single and array values for "shapes" parameter - texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; - texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + if ( Array.isArray( shapes ) === false ) { - texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + addShape( shapes ); - if ( texData.encoding !== undefined ) { + } else { - texture.encoding = texData.encoding; + for ( let i = 0; i < shapes.length; i ++ ) { - } + addShape( shapes[ i ] ); - if ( texData.flipY !== undefined ) { + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support - texture.flipY = texData.flipY; + groupStart += groupCount; + groupCount = 0; } - if ( texData.format !== undefined ) { + } - texture.format = texData.format; + // build geometry - } + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - if ( texData.type !== undefined ) { - texture.type = texData.type; + // helper functions - } + function addShape( shape ) { - if ( texData.mipmaps !== undefined ) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints( curveSegments ); - texture.mipmaps = texData.mipmaps; - texture.minFilter = LinearMipmapLinearFilter; // presumably... + let shapeVertices = points.shape; + const shapeHoles = points.holes; - } + // check direction of vertices - if ( texData.mipmapCount === 1 ) { + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { - texture.minFilter = LinearFilter; + shapeVertices = shapeVertices.reverse(); } - texture.needsUpdate = true; + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { - if ( onLoad ) onLoad( texture, texData ); + const shapeHole = shapeHoles[ i ]; - }, onProgress, onError ); + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + shapeHoles[ i ] = shapeHole.reverse(); - return texture; + } - } + } -} ); + const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); -function TextureLoader( manager ) { + // join vertices of inner and outer paths to a single array - Loader.call( this, manager ); + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { -} + const shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); -TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + } - constructor: TextureLoader, + // vertices, normals, uvs - load: function ( url, onLoad, onProgress, onError ) { + for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { - const texture = new Texture(); + const vertex = shapeVertices[ i ]; - const loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs - loader.load( url, function ( image ) { + } - texture.image = image; + // incides - // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. - const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; + for ( let i = 0, l = faces.length; i < l; i ++ ) { - texture.format = isJPEG ? RGBFormat : RGBAFormat; - texture.needsUpdate = true; + const face = faces[ i ]; - if ( onLoad !== undefined ) { + const a = face[ 0 ] + indexOffset; + const b = face[ 1 ] + indexOffset; + const c = face[ 2 ] + indexOffset; - onLoad( texture ); + indices.push( a, b, c ); + groupCount += 3; } - }, onProgress, onError ); - - return texture; + } } -} ); + toJSON() { -/** - * Extensible curve object. - * - * Some common of curve methods: - * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) - * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following curves inherit from THREE.Curve: - * - * -- 2D curves -- - * THREE.ArcCurve - * THREE.CubicBezierCurve - * THREE.EllipseCurve - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.SplineCurve - * - * -- 3D curves -- - * THREE.CatmullRomCurve3 - * THREE.CubicBezierCurve3 - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * - * A series of curves can be represented as a THREE.CurvePath. - * - **/ + const data = super.toJSON(); -function Curve() { + const shapes = this.parameters.shapes; - this.type = 'Curve'; + return toJSON( shapes, data ); - this.arcLengthDivisions = 200; + } -} + static fromJSON( data, shapes ) { -Object.assign( Curve.prototype, { + const geometryShapes = []; - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { - getPoint: function ( /* t, optionalTarget */ ) { + const shape = shapes[ data.shapes[ j ] ]; - console.warn( 'THREE.Curve: .getPoint() not implemented.' ); - return null; + geometryShapes.push( shape ); - }, + } - // Get point at relative position in curve according to arc length - // - u [0 .. 1] + return new ShapeGeometry( geometryShapes, data.curveSegments ); - getPointAt: function ( u, optionalTarget ) { + } - const t = this.getUtoTmapping( u ); - return this.getPoint( t, optionalTarget ); +} - }, +function toJSON( shapes, data ) { - // Get sequence of points using getPoint( t ) + data.shapes = []; - getPoints: function ( divisions = 5 ) { + if ( Array.isArray( shapes ) ) { - const points = []; + for ( let i = 0, l = shapes.length; i < l; i ++ ) { - for ( let d = 0; d <= divisions; d ++ ) { + const shape = shapes[ i ]; - points.push( this.getPoint( d / divisions ) ); + data.shapes.push( shape.uuid ); } - return points; - - }, - - // Get sequence of points using getPointAt( u ) + } else { - getSpacedPoints: function ( divisions = 5 ) { + data.shapes.push( shapes.uuid ); - const points = []; + } - for ( let d = 0; d <= divisions; d ++ ) { + return data; - points.push( this.getPointAt( d / divisions ) ); +} - } +class SphereGeometry extends BufferGeometry { - return points; + constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { - }, + super(); - // Get total curve arc length + this.type = 'SphereGeometry'; - getLength: function () { + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - const lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; + widthSegments = Math.max( 3, Math.floor( widthSegments ) ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) ); - }, + const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); - // Get list of cumulative segment lengths + let index = 0; + const grid = []; - getLengths: function ( divisions ) { + const vertex = new Vector3(); + const normal = new Vector3(); - if ( divisions === undefined ) divisions = this.arcLengthDivisions; + // buffers - if ( this.cacheArcLengths && - ( this.cacheArcLengths.length === divisions + 1 ) && - ! this.needsUpdate ) { + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - return this.cacheArcLengths; + // generate vertices, normals and uvs - } + for ( let iy = 0; iy <= heightSegments; iy ++ ) { - this.needsUpdate = false; + const verticesRow = []; - const cache = []; - let current, last = this.getPoint( 0 ); - let sum = 0; + const v = iy / heightSegments; - cache.push( 0 ); + // special case for the poles - for ( let p = 1; p <= divisions; p ++ ) { + let uOffset = 0; - current = this.getPoint( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + if ( iy == 0 && thetaStart == 0 ) { - } + uOffset = 0.5 / widthSegments; - this.cacheArcLengths = cache; + } else if ( iy == heightSegments && thetaEnd == Math.PI ) { - return cache; // { sums: cache, sum: sum }; Sum is in the last element. + uOffset = - 0.5 / widthSegments; - }, + } - updateArcLengths: function () { + for ( let ix = 0; ix <= widthSegments; ix ++ ) { - this.needsUpdate = true; - this.getLengths(); + const u = ix / widthSegments; - }, + // vertex - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - getUtoTmapping: function ( u, distance ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - const arcLengths = this.getLengths(); + // normal - let i = 0; - const il = arcLengths.length; + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - let targetArcLength; // The targeted u distance value to get + // uv - if ( distance ) { + uvs.push( u + uOffset, 1 - v ); - targetArcLength = distance; + verticesRow.push( index ++ ); - } else { + } - targetArcLength = u * arcLengths[ il - 1 ]; + grid.push( verticesRow ); } - // binary search for the index with largest value smaller than target u distance + // indices - let low = 0, high = il - 1, comparison; + for ( let iy = 0; iy < heightSegments; iy ++ ) { - while ( low <= high ) { + for ( let ix = 0; ix < widthSegments; ix ++ ) { - 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 + const a = grid[ iy ][ ix + 1 ]; + const b = grid[ iy ][ ix ]; + const c = grid[ iy + 1 ][ ix ]; + const d = grid[ iy + 1 ][ ix + 1 ]; - comparison = arcLengths[ i ] - targetArcLength; + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); - if ( comparison < 0 ) { + } - low = i + 1; + } - } else if ( comparison > 0 ) { + // build geometry - high = i - 1; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } else { + } - high = i; - break; + static fromJSON( data ) { - // DONE + return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); - } + } - } +} - i = high; +class TetrahedronGeometry extends PolyhedronGeometry { - if ( arcLengths[ i ] === targetArcLength ) { + constructor( radius = 1, detail = 0 ) { - return i / ( il - 1 ); + const vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - } + const indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; - // we could get finer grain at lengths, or use simple interpolation between two points + super( vertices, indices, radius, detail ); - const lengthBefore = arcLengths[ i ]; - const lengthAfter = arcLengths[ i + 1 ]; + this.type = 'TetrahedronGeometry'; - const segmentLength = lengthAfter - lengthBefore; + this.parameters = { + radius: radius, + detail: detail + }; - // determine where we are between the 'before' and 'after' points + } - const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + static fromJSON( data ) { - // add that fractional amount to t + return new TetrahedronGeometry( data.radius, data.detail ); - const t = ( i + segmentFraction ) / ( il - 1 ); + } - return t; +} - }, +class TorusGeometry extends BufferGeometry { - // 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 + constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) { - getTangent: function ( t, optionalTarget ) { + super(); - const delta = 0.0001; - let t1 = t - delta; - let t2 = t + delta; + this.type = 'TorusGeometry'; - // Capping in case of danger + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; + radialSegments = Math.floor( radialSegments ); + tubularSegments = Math.floor( tubularSegments ); - const pt1 = this.getPoint( t1 ); - const pt2 = this.getPoint( t2 ); + // buffers - const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - tangent.copy( pt2 ).sub( pt1 ).normalize(); + // helper variables - return tangent; + const center = new Vector3(); + const vertex = new Vector3(); + const normal = new Vector3(); - }, + // generate vertices, normals and uvs - getTangentAt: function ( u, optionalTarget ) { + for ( let j = 0; j <= radialSegments; j ++ ) { - const t = this.getUtoTmapping( u ); - return this.getTangent( t, optionalTarget ); + for ( let i = 0; i <= tubularSegments; i ++ ) { - }, + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; - computeFrenetFrames: function ( segments, closed ) { + // vertex - // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + 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 ); - const normal = new Vector3(); + vertices.push( vertex.x, vertex.y, vertex.z ); - const tangents = []; - const normals = []; - const binormals = []; + // normal - const vec = new Vector3(); - const mat = new Matrix4(); + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); - // compute the tangent vectors for each segment on the curve + normals.push( normal.x, normal.y, normal.z ); - for ( let i = 0; i <= segments; i ++ ) { + // uv - const u = i / segments; + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - tangents[ i ] = this.getTangentAt( u, new Vector3() ); - tangents[ i ].normalize(); + } } - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the minimum tangent xyz component + // generate indices - normals[ 0 ] = new Vector3(); - binormals[ 0 ] = new Vector3(); - let min = Number.MAX_VALUE; - const tx = Math.abs( tangents[ 0 ].x ); - const ty = Math.abs( tangents[ 0 ].y ); - const tz = Math.abs( tangents[ 0 ].z ); + for ( let j = 1; j <= radialSegments; j ++ ) { - if ( tx <= min ) { + for ( let i = 1; i <= tubularSegments; i ++ ) { - min = tx; - normal.set( 1, 0, 0 ); + // indices - } + const a = ( tubularSegments + 1 ) * j + i - 1; + const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + const d = ( tubularSegments + 1 ) * j + i; - if ( ty <= min ) { + // faces - min = ty; - normal.set( 0, 1, 0 ); + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry - } + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - if ( tz <= min ) { + } - normal.set( 0, 0, 1 ); + static fromJSON( data ) { - } + return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc ); - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + } - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); +} +class TorusKnotGeometry extends BufferGeometry { - // compute the slowly-varying normal and binormal vectors for each segment on the curve + constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { - for ( let i = 1; i <= segments; i ++ ) { + super(); - normals[ i ] = normals[ i - 1 ].clone(); + this.type = 'TorusKnotGeometry'; - binormals[ i ] = binormals[ i - 1 ].clone(); + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + tubularSegments = Math.floor( tubularSegments ); + radialSegments = Math.floor( radialSegments ); - if ( vec.length() > Number.EPSILON ) { + // buffers - vec.normalize(); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + // helper variables - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + const vertex = new Vector3(); + const normal = new Vector3(); - } + const P1 = new Vector3(); + const P2 = new Vector3(); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + const B = new Vector3(); + const T = new Vector3(); + const N = new Vector3(); - } + // generate vertices, normals and uvs - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + for ( let i = 0; i <= tubularSegments; ++ i ) { - if ( closed === true ) { + // the radian "u" is used to calculate the position on the torus curve of the current tubular segment - let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); - theta /= segments; + const u = i / tubularSegments * p * Math.PI * 2; - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + // 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 - theta = - theta; + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); - } + // calculate orthonormal basis - for ( let i = 1; i <= segments; i ++ ) { + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + // normalize B, N. T can be ignored, we don't use it - } + B.normalize(); + N.normalize(); - } + for ( let j = 0; j <= radialSegments; ++ j ) { - return { - tangents: tangents, - normals: normals, - binormals: binormals - }; + // 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. - }, + const v = j / radialSegments * Math.PI * 2; + const cx = - tube * Math.cos( v ); + const cy = tube * Math.sin( v ); - clone: function () { + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve - return new this.constructor().copy( this ); + 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 ); - }, + vertices.push( vertex.x, vertex.y, vertex.z ); - copy: function ( source ) { + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) - this.arcLengthDivisions = source.arcLengthDivisions; + normal.subVectors( vertex, P1 ).normalize(); - return this; + normals.push( normal.x, normal.y, normal.z ); - }, + // uv - toJSON: function () { + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - const data = { - metadata: { - version: 4.5, - type: 'Curve', - generator: 'Curve.toJSON' } - }; - data.arcLengthDivisions = this.arcLengthDivisions; - data.type = this.type; + } - return data; + // generate indices - }, + for ( let j = 1; j <= tubularSegments; j ++ ) { - fromJSON: function ( json ) { + for ( let i = 1; i <= radialSegments; i ++ ) { - this.arcLengthDivisions = json.arcLengthDivisions; + // indices - return this; + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; - } + // faces -} ); + indices.push( a, b, d ); + indices.push( b, c, d ); -class EllipseCurve extends Curve { + } - constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { + } - super(); + // build geometry - this.type = 'EllipseCurve'; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - this.aX = aX; - this.aY = aY; + // this function calculates the current position on the torus curve - this.xRadius = xRadius; - this.yRadius = yRadius; + function calculatePositionOnCurve( u, p, q, radius, position ) { - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + const cu = Math.cos( u ); + const su = Math.sin( u ); + const quOverP = q / p * u; + const cs = Math.cos( quOverP ); - this.aClockwise = aClockwise; + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; - this.aRotation = aRotation; + } } - getPoint( t, optionalTarget ) { + static fromJSON( data ) { - const point = optionalTarget || new Vector2(); + return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q ); - const twoPi = Math.PI * 2; - let deltaAngle = this.aEndAngle - this.aStartAngle; - const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + } - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) deltaAngle += twoPi; - while ( deltaAngle > twoPi ) deltaAngle -= twoPi; +} - if ( deltaAngle < Number.EPSILON ) { +class TubeGeometry extends BufferGeometry { - if ( samePoints ) { + constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { - deltaAngle = 0; + super(); - } else { + this.type = 'TubeGeometry'; - deltaAngle = twoPi; + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; - } + const frames = path.computeFrenetFrames( tubularSegments, closed ); - } + // expose internals - if ( this.aClockwise === true && ! samePoints ) { + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; - if ( deltaAngle === twoPi ) { + // helper variables - deltaAngle = - twoPi; + const vertex = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); - } else { + // buffer - deltaAngle = deltaAngle - twoPi; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; - } + // create buffer data - } + generateBufferData(); - const angle = this.aStartAngle + t * deltaAngle; - let x = this.aX + this.xRadius * Math.cos( angle ); - let y = this.aY + this.yRadius * Math.sin( angle ); + // build geometry - if ( this.aRotation !== 0 ) { + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - const cos = Math.cos( this.aRotation ); - const sin = Math.sin( this.aRotation ); + // functions - const tx = x - this.aX; - const ty = y - this.aY; + function generateBufferData() { - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + for ( let i = 0; i < tubularSegments; i ++ ) { - } + generateSegment( i ); - return point.set( x, y ); + } - } + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) - copy( source ) { + generateSegment( ( closed === false ) ? tubularSegments : 0 ); - super.copy( source ); + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries - this.aX = source.aX; - this.aY = source.aY; + generateUVs(); - this.xRadius = source.xRadius; - this.yRadius = source.yRadius; + // finally create faces - this.aStartAngle = source.aStartAngle; - this.aEndAngle = source.aEndAngle; + generateIndices(); - this.aClockwise = source.aClockwise; + } - this.aRotation = source.aRotation; + function generateSegment( i ) { - return this; + // we use getPointAt to sample evenly distributed points from the given path - } + P = path.getPointAt( i / tubularSegments, P ); - toJSON() { + // retrieve corresponding normal and binormal - const data = super.toJSON(); + const N = frames.normals[ i ]; + const B = frames.binormals[ i ]; - data.aX = this.aX; - data.aY = this.aY; + // generate normals and vertices for the current segment - data.xRadius = this.xRadius; - data.yRadius = this.yRadius; + for ( let j = 0; j <= radialSegments; j ++ ) { - data.aStartAngle = this.aStartAngle; - data.aEndAngle = this.aEndAngle; + const v = j / radialSegments * Math.PI * 2; - data.aClockwise = this.aClockwise; + const sin = Math.sin( v ); + const cos = - Math.cos( v ); - data.aRotation = this.aRotation; + // normal - return data; + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); - } + normals.push( normal.x, normal.y, normal.z ); - fromJSON( json ) { + // vertex - super.fromJSON( json ); + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; - this.aX = json.aX; - this.aY = json.aY; + vertices.push( vertex.x, vertex.y, vertex.z ); - this.xRadius = json.xRadius; - this.yRadius = json.yRadius; + } - this.aStartAngle = json.aStartAngle; - this.aEndAngle = json.aEndAngle; + } - this.aClockwise = json.aClockwise; + function generateIndices() { - this.aRotation = json.aRotation; + for ( let j = 1; j <= tubularSegments; j ++ ) { - return this; + for ( let i = 1; i <= radialSegments; i ++ ) { - } + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; -} + // faces -EllipseCurve.prototype.isEllipseCurve = true; + indices.push( a, b, d ); + indices.push( b, c, d ); -class ArcCurve extends EllipseCurve { + } - constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + } - super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + } - this.type = 'ArcCurve'; + function generateUVs() { - } + for ( let i = 0; i <= tubularSegments; i ++ ) { -} + for ( let j = 0; j <= radialSegments; j ++ ) { -ArcCurve.prototype.isArcCurve = true; + uv.x = i / tubularSegments; + uv.y = j / radialSegments; -/** - * 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 - */ + uvs.push( uv.x, uv.y ); + } -/* -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. -*/ + } -function CubicPoly() { + } - let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + toJSON() { - /* - * 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. - */ - function init( x0, x1, t0, t1 ) { + const data = super.toJSON(); - c0 = x0; - c1 = t0; - c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; - c3 = 2 * x0 - 2 * x1 + t0 + t1; + data.path = this.parameters.path.toJSON(); - } + return data; - return { + } - initCatmullRom: function ( x0, x1, x2, x3, tension ) { + static fromJSON( data ) { - init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + // This only works for built-in curves (e.g. CatmullRomCurve3). + // User defined curves or instances of CurvePath will not be deserialized. + return new TubeGeometry( + new Curves[ data.path.type ]().fromJSON( data.path ), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); - }, + } - initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { +} - // compute tangents when parameterized in [t1,t2] - let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; - let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; +class WireframeGeometry extends BufferGeometry { - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; + constructor( geometry = null ) { - init( x1, x2, t1, t2 ); + super(); - }, + this.type = 'WireframeGeometry'; - calc: function ( t ) { + this.parameters = { + geometry: geometry + }; - const t2 = t * t; - const t3 = t2 * t; - return c0 + c1 * t + c2 * t2 + c3 * t3; + if ( geometry !== null ) { - } + // buffer - }; + const vertices = []; + const edges = new Set(); -} + // helper variables -// + const start = new Vector3(); + const end = new Vector3(); -const tmp = new Vector3(); -const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); + if ( geometry.index !== null ) { -class CatmullRomCurve3 extends Curve { + // indexed BufferGeometry - constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; - super(); + if ( groups.length === 0 ) { - this.type = 'CatmullRomCurve3'; + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; - this.points = points; - this.closed = closed; - this.curveType = curveType; - this.tension = tension; + } - } + // create a data structure that contains all edges without duplicates - getPoint( t, optionalTarget = new Vector3() ) { + for ( let o = 0, ol = groups.length; o < ol; ++ o ) { - const point = optionalTarget; + const group = groups[ o ]; - const points = this.points; - const l = points.length; + const groupStart = group.start; + const groupCount = group.count; - const p = ( l - ( this.closed ? 0 : 1 ) ) * t; - let intPoint = Math.floor( p ); - let weight = p - intPoint; + for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) { - if ( this.closed ) { + for ( let j = 0; j < 3; j ++ ) { - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + const index1 = indices.getX( i + j ); + const index2 = indices.getX( i + ( j + 1 ) % 3 ); - } else if ( weight === 0 && intPoint === l - 1 ) { + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); - intPoint = l - 2; - weight = 1; + if ( isUniqueEdge( start, end, edges ) === true ) { - } + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); - let p0, p3; // 4 points (p1 & p2 defined below) + } - if ( this.closed || intPoint > 0 ) { + } - p0 = points[ ( intPoint - 1 ) % l ]; + } - } else { + } - // extrapolate first point - tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); - p0 = tmp; + } else { - } + // non-indexed BufferGeometry - const p1 = points[ intPoint % l ]; - const p2 = points[ ( intPoint + 1 ) % l ]; + const position = geometry.attributes.position; - if ( this.closed || intPoint + 2 < l ) { + for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { - p3 = points[ ( intPoint + 2 ) % l ]; + for ( let j = 0; j < 3; j ++ ) { - } else { + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) - // extrapolate last point - tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); - p3 = tmp; + const index1 = 3 * i + j; + const index2 = 3 * i + ( ( j + 1 ) % 3 ); - } + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); - if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + if ( isUniqueEdge( start, end, edges ) === true ) { - // init Centripetal / Chordal Catmull-Rom - const pow = this.curveType === 'chordal' ? 0.5 : 0.25; - let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); - let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); - let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); - // safety check for repeated points - if ( dt1 < 1e-4 ) dt1 = 1.0; - if ( dt0 < 1e-4 ) dt0 = dt1; - if ( dt2 < 1e-4 ) dt2 = dt1; + } - 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.curveType === 'catmullrom' ) { + } - px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); - py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); - pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + } - } + // build geometry - point.set( - px.calc( weight ), - py.calc( weight ), - pz.calc( weight ) - ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - return point; + } } - copy( source ) { +} - super.copy( source ); +function isUniqueEdge( start, end, edges ) { - this.points = []; + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge - for ( let i = 0, l = source.points.length; i < l; i ++ ) { + if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) { - const point = source.points[ i ]; + return false; - this.points.push( point.clone() ); + } else { - } + edges.add( hash1 ); + edges.add( hash2 ); + return true; - this.closed = source.closed; - this.curveType = source.curveType; - this.tension = source.tension; + } - return this; +} - } +var Geometries = /*#__PURE__*/Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry, + CapsuleGeometry: CapsuleGeometry, + CircleGeometry: CircleGeometry, + ConeGeometry: ConeGeometry, + CylinderGeometry: CylinderGeometry, + DodecahedronGeometry: DodecahedronGeometry, + EdgesGeometry: EdgesGeometry, + ExtrudeGeometry: ExtrudeGeometry, + IcosahedronGeometry: IcosahedronGeometry, + LatheGeometry: LatheGeometry, + OctahedronGeometry: OctahedronGeometry, + PlaneGeometry: PlaneGeometry, + PolyhedronGeometry: PolyhedronGeometry, + RingGeometry: RingGeometry, + ShapeGeometry: ShapeGeometry, + SphereGeometry: SphereGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TorusGeometry: TorusGeometry, + TorusKnotGeometry: TorusKnotGeometry, + TubeGeometry: TubeGeometry, + WireframeGeometry: WireframeGeometry +}); - toJSON() { +class ShadowMaterial extends Material { - const data = super.toJSON(); + constructor( parameters ) { - data.points = []; + super(); - for ( let i = 0, l = this.points.length; i < l; i ++ ) { + this.isShadowMaterial = true; - const point = this.points[ i ]; - data.points.push( point.toArray() ); + this.type = 'ShadowMaterial'; - } + this.color = new Color( 0x000000 ); + this.transparent = true; - data.closed = this.closed; - data.curveType = this.curveType; - data.tension = this.tension; + this.fog = true; - return data; + this.setValues( parameters ); } - fromJSON( json ) { - - super.fromJSON( json ); - - this.points = []; - - for ( let i = 0, l = json.points.length; i < l; i ++ ) { + copy( source ) { - const point = json.points[ i ]; - this.points.push( new Vector3().fromArray( point ) ); + super.copy( source ); - } + this.color.copy( source.color ); - this.closed = json.closed; - this.curveType = json.curveType; - this.tension = json.tension; + this.fog = source.fog; return this; @@ -35809,279 +36865,276 @@ class CatmullRomCurve3 extends Curve { } -CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; - -/** - * Bezier Curves formulas obtained from - * http://en.wikipedia.org/wiki/Bézier_curve - */ - -function CatmullRom( t, p0, p1, p2, p3 ) { +class RawShaderMaterial extends ShaderMaterial { - const v0 = ( p2 - p0 ) * 0.5; - const v1 = ( p3 - p1 ) * 0.5; - const t2 = t * t; - const t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + constructor( parameters ) { -} + super( parameters ); -// + this.isRawShaderMaterial = true; -function QuadraticBezierP0( t, p ) { + this.type = 'RawShaderMaterial'; - const k = 1 - t; - return k * k * p; + } } -function QuadraticBezierP1( t, p ) { +class MeshStandardMaterial extends Material { - return 2 * ( 1 - t ) * t * p; + constructor( parameters ) { -} + super(); -function QuadraticBezierP2( t, p ) { + this.isMeshStandardMaterial = true; - return t * t * p; + this.defines = { 'STANDARD': '' }; -} + this.type = 'MeshStandardMaterial'; -function QuadraticBezier( t, p0, p1, p2 ) { + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 1.0; + this.metalness = 0.0; - return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + - QuadraticBezierP2( t, p2 ); + this.map = null; -} + this.lightMap = null; + this.lightMapIntensity = 1.0; -// + this.aoMap = null; + this.aoMapIntensity = 1.0; -function CubicBezierP0( t, p ) { + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - const k = 1 - t; - return k * k * k * p; + this.bumpMap = null; + this.bumpScale = 1; -} + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); -function CubicBezierP1( t, p ) { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - const k = 1 - t; - return 3 * k * k * t * p; + this.roughnessMap = null; -} + this.metalnessMap = null; -function CubicBezierP2( t, p ) { + this.alphaMap = null; - return 3 * ( 1 - t ) * t * t * p; + this.envMap = null; + this.envMapIntensity = 1.0; -} + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; -function CubicBezierP3( t, p ) { + this.flatShading = false; - return t * t * t * p; + this.fog = true; -} + this.setValues( parameters ); -function CubicBezier( t, p0, p1, p2, p3 ) { + } - return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + - CubicBezierP3( t, p3 ); + copy( source ) { -} + super.copy( source ); -class CubicBezierCurve extends Curve { + this.defines = { 'STANDARD': '' }; - constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; - super(); + this.map = source.map; - this.type = 'CubicBezierCurve'; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - } + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - getPoint( t, optionalTarget = new Vector2() ) { + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - const point = optionalTarget; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - point.set( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) - ); + this.roughnessMap = source.roughnessMap; - return point; + this.metalnessMap = source.metalnessMap; - } + this.alphaMap = source.alphaMap; - copy( source ) { + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; - super.copy( source ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - this.v3.copy( source.v3 ); + this.flatShading = source.flatShading; + + this.fog = source.fog; return this; } - toJSON() { +} - const data = super.toJSON(); +class MeshPhysicalMaterial extends MeshStandardMaterial { - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); + constructor( parameters ) { - return data; + super(); - } + this.isMeshPhysicalMaterial = true; - fromJSON( json ) { + this.defines = { - super.fromJSON( json ); + 'STANDARD': '', + 'PHYSICAL': '' - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); - this.v3.fromArray( json.v3 ); + }; - return this; + this.type = 'MeshPhysicalMaterial'; - } + this.clearcoatMap = null; + this.clearcoatRoughness = 0.0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2( 1, 1 ); + this.clearcoatNormalMap = null; -} + this.ior = 1.5; -CubicBezierCurve.prototype.isCubicBezierCurve = true; + Object.defineProperty( this, 'reflectivity', { + get: function () { -class CubicBezierCurve3 extends Curve { + return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) ); - constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { + }, + set: function ( reflectivity ) { - super(); + this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity ); - this.type = 'CubicBezierCurve3'; + } + } ); - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; - } + this.sheenColor = new Color( 0x000000 ); + this.sheenColorMap = null; + this.sheenRoughness = 1.0; + this.sheenRoughnessMap = null; - getPoint( t, optionalTarget = new Vector3() ) { + this.transmissionMap = null; - const point = optionalTarget; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = 0.0; + this.attenuationColor = new Color( 1, 1, 1 ); - const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + this.specularIntensity = 1.0; + this.specularIntensityMap = null; + this.specularColor = new Color( 1, 1, 1 ); + this.specularColorMap = null; - point.set( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), - CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) - ); + this._sheen = 0.0; + this._clearcoat = 0; + this._iridescence = 0; + this._transmission = 0; - return point; + this.setValues( parameters ); } - copy( source ) { - - super.copy( source ); - - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - this.v3.copy( source.v3 ); + get sheen() { - return this; + return this._sheen; } - toJSON() { - - const data = super.toJSON(); + set sheen( value ) { - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); + if ( this._sheen > 0 !== value > 0 ) { - return data; + this.version ++; - } + } - fromJSON( json ) { + this._sheen = value; - super.fromJSON( json ); + } - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); - this.v3.fromArray( json.v3 ); + get clearcoat() { - return this; + return this._clearcoat; } -} - -CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; - -class LineCurve extends Curve { + set clearcoat( value ) { - constructor( v1 = new Vector2(), v2 = new Vector2() ) { + if ( this._clearcoat > 0 !== value > 0 ) { - super(); + this.version ++; - this.type = 'LineCurve'; + } - this.v1 = v1; - this.v2 = v2; + this._clearcoat = value; } - getPoint( t, optionalTarget = new Vector2() ) { + get iridescence() { - const point = optionalTarget; + return this._iridescence; - if ( t === 1 ) { + } - point.copy( this.v2 ); + set iridescence( value ) { - } else { + if ( this._iridescence > 0 !== value > 0 ) { - point.copy( this.v2 ).sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + this.version ++; } - return point; + this._iridescence = value; } - // Line curve is linear, so we can overwrite default getPointAt - getPointAt( u, optionalTarget ) { + get transmission() { - return this.getPoint( u, optionalTarget ); + return this._transmission; } - getTangent( t, optionalTarget ) { + set transmission( value ) { - const tangent = optionalTarget || new Vector2(); + if ( this._transmission > 0 !== value > 0 ) { - tangent.copy( this.v2 ).sub( this.v1 ).normalize(); + this.version ++; - return tangent; + } + + this._transmission = value; } @@ -36089,30 +37142,46 @@ class LineCurve extends Curve { super.copy( source ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - - return this; + this.defines = { - } + 'STANDARD': '', + 'PHYSICAL': '' - toJSON() { + }; - const data = super.toJSON(); + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.ior = source.ior; - return data; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; - } + this.sheen = source.sheen; + this.sheenColor.copy( source.sheenColor ); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; - fromJSON( json ) { + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; - super.fromJSON( json ); + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy( source.attenuationColor ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy( source.specularColor ); + this.specularColorMap = source.specularColorMap; return this; @@ -36120,71 +37189,113 @@ class LineCurve extends Curve { } -LineCurve.prototype.isLineCurve = true; - -class LineCurve3 extends Curve { +class MeshPhongMaterial extends Material { - constructor( v1 = new Vector3(), v2 = new Vector3() ) { + constructor( parameters ) { super(); - this.type = 'LineCurve3'; - this.isLineCurve3 = true; + this.isMeshPhongMaterial = true; - this.v1 = v1; - this.v2 = v2; + this.type = 'MeshPhongMaterial'; - } - getPoint( t, optionalTarget = new Vector3() ) { + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; - const point = optionalTarget; + this.map = null; - if ( t === 1 ) { + this.lightMap = null; + this.lightMapIntensity = 1.0; - point.copy( this.v2 ); + this.aoMap = null; + this.aoMapIntensity = 1.0; - } else { + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - point.copy( this.v2 ).sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + this.bumpMap = null; + this.bumpScale = 1; - } + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - return point; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - } - // Line curve is linear, so we can overwrite default getPointAt - getPointAt( u, optionalTarget ) { + this.specularMap = null; - return this.getPoint( u, optionalTarget ); + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); } + copy( source ) { super.copy( source ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; - return this; + this.map = source.map; - } - toJSON() { + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - const data = super.toJSON(); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - return data; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - } - fromJSON( json ) { + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - super.fromJSON( json ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + 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.flatShading = source.flatShading; + + this.fog = source.fog; return this; @@ -36192,32 +37303,54 @@ class LineCurve3 extends Curve { } -class QuadraticBezierCurve extends Curve { +class MeshToonMaterial extends Material { - constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { + constructor( parameters ) { super(); - this.type = 'QuadraticBezierCurve'; + this.isMeshToonMaterial = true; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + this.defines = { 'TOON': '' }; - } + this.type = 'MeshToonMaterial'; - getPoint( t, optionalTarget = new Vector2() ) { + this.color = new Color( 0xffffff ); - const point = optionalTarget; + this.map = null; + this.gradientMap = null; - const v0 = this.v0, v1 = this.v1, v2 = this.v2; + this.lightMap = null; + this.lightMapIntensity = 1.0; - point.set( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ) - ); + this.aoMap = null; + this.aoMapIntensity = 1.0; - return point; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); } @@ -36225,33 +37358,40 @@ class QuadraticBezierCurve extends Curve { super.copy( source ); - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); + this.color.copy( source.color ); - return this; + this.map = source.map; + this.gradientMap = source.gradientMap; - } + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - toJSON() { + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - const data = super.toJSON(); + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - return data; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - } + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - fromJSON( json ) { + this.alphaMap = source.alphaMap; - super.fromJSON( json ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + this.fog = source.fog; return this; @@ -36259,35 +37399,33 @@ class QuadraticBezierCurve extends Curve { } -QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; - -class QuadraticBezierCurve3 extends Curve { +class MeshNormalMaterial extends Material { - constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { + constructor( parameters ) { super(); - this.type = 'QuadraticBezierCurve3'; + this.isMeshNormalMaterial = true; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + this.type = 'MeshNormalMaterial'; - } + this.bumpMap = null; + this.bumpScale = 1; - getPoint( t, optionalTarget = new Vector3() ) { + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - const point = optionalTarget; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - const v0 = this.v0, v1 = this.v1, v2 = this.v2; + this.wireframe = false; + this.wireframeLinewidth = 1; - point.set( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ), - QuadraticBezier( t, v0.z, v1.z, v2.z ) - ); + this.flatShading = false; - return point; + this.setValues( parameters ); } @@ -36295,75 +37433,82 @@ class QuadraticBezierCurve3 extends Curve { super.copy( source ); - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - - return this; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - } + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - toJSON() { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - const data = super.toJSON(); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + this.flatShading = source.flatShading; - return data; + return this; } - fromJSON( json ) { +} - super.fromJSON( json ); +class MeshLambertMaterial extends Material { - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); + constructor( parameters ) { - return this; + super(); - } + this.isMeshLambertMaterial = true; -} + this.type = 'MeshLambertMaterial'; -QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true; + this.color = new Color( 0xffffff ); // diffuse -class SplineCurve extends Curve { + this.map = null; - constructor( points = [] ) { + this.lightMap = null; + this.lightMapIntensity = 1.0; - super(); + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.type = 'SplineCurve'; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - this.points = points; + this.bumpMap = null; + this.bumpScale = 1; - } + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - getPoint( t, optionalTarget = new Vector2() ) { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - const point = optionalTarget; + this.specularMap = null; - const points = this.points; - const p = ( points.length - 1 ) * t; + this.alphaMap = null; - const intPoint = Math.floor( p ); - const weight = p - intPoint; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; - const p1 = points[ intPoint ]; - const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - point.set( - CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), - CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) - ); + this.flatShading = false; - return point; + this.fog = true; + + this.setValues( parameters ); } @@ -36371,1389 +37516,1387 @@ class SplineCurve extends Curve { super.copy( source ); - this.points = []; + this.color.copy( source.color ); - for ( let i = 0, l = source.points.length; i < l; i ++ ) { + this.map = source.map; - const point = source.points[ i ]; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.points.push( point.clone() ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - } + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - return this; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - } + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - toJSON() { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - const data = super.toJSON(); + this.specularMap = source.specularMap; - data.points = []; + this.alphaMap = source.alphaMap; - for ( let i = 0, l = this.points.length; i < l; i ++ ) { + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - const point = this.points[ i ]; - data.points.push( point.toArray() ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.flatShading = source.flatShading; - return data; + this.fog = source.fog; + + return this; } - fromJSON( json ) { +} - super.fromJSON( json ); +class MeshMatcapMaterial extends Material { - this.points = []; + constructor( parameters ) { - for ( let i = 0, l = json.points.length; i < l; i ++ ) { + super(); - const point = json.points[ i ]; - this.points.push( new Vector2().fromArray( point ) ); + this.isMeshMatcapMaterial = true; - } + this.defines = { 'MATCAP': '' }; - return this; + this.type = 'MeshMatcapMaterial'; - } + this.color = new Color( 0xffffff ); // diffuse -} + this.matcap = null; -SplineCurve.prototype.isSplineCurve = true; + this.map = null; -var Curves = /*#__PURE__*/Object.freeze({ - __proto__: null, - ArcCurve: ArcCurve, - CatmullRomCurve3: CatmullRomCurve3, - CubicBezierCurve: CubicBezierCurve, - CubicBezierCurve3: CubicBezierCurve3, - EllipseCurve: EllipseCurve, - LineCurve: LineCurve, - LineCurve3: LineCurve3, - QuadraticBezierCurve: QuadraticBezierCurve, - QuadraticBezierCurve3: QuadraticBezierCurve3, - SplineCurve: SplineCurve -}); + this.bumpMap = null; + this.bumpScale = 1; -/************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); -class CurvePath extends Curve { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - constructor() { + this.alphaMap = null; - super(); + this.flatShading = false; - this.type = 'CurvePath'; + this.fog = true; - this.curves = []; - this.autoClose = false; // Automatically closes the path + this.setValues( parameters ); } - add( curve ) { - - this.curves.push( curve ); - } + copy( source ) { - closePath() { + super.copy( source ); - // Add a line curve if start and end of lines are not connected - const startPoint = this.curves[ 0 ].getPoint( 0 ); - const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + this.defines = { 'MATCAP': '' }; - if ( ! startPoint.equals( endPoint ) ) { + this.color.copy( source.color ); - this.curves.push( new LineCurve( endPoint, startPoint ) ); + this.matcap = source.matcap; - } + this.map = source.map; - } + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - // 1. Length of each sub path have to be known - // 2. Locate and identify type of curve - // 3. Get t for the curve - // 4. Return curve.getPointAt(t') + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - getPoint( t ) { + this.alphaMap = source.alphaMap; - const d = t * this.getLength(); - const curveLengths = this.getCurveLengths(); - let i = 0; + this.flatShading = source.flatShading; - // To think about boundaries points. + this.fog = source.fog; - while ( i < curveLengths.length ) { + return this; - if ( curveLengths[ i ] >= d ) { + } - const diff = curveLengths[ i ] - d; - const curve = this.curves[ i ]; +} - const segmentLength = curve.getLength(); - const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; +class LineDashedMaterial extends LineBasicMaterial { - return curve.getPointAt( u ); + constructor( parameters ) { - } + super(); - i ++; + this.isLineDashedMaterial = true; - } + this.type = 'LineDashedMaterial'; - return null; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; - // loop where sum != 0, sum > d , sum+1 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { + } - points.push( points[ 0 ] ); + return result; - } +} - return points; +// function for parsing AOS keyframe formats +function flattenJSON( jsonKeys, times, values, valuePropertyName ) { - } + let i = 1, key = jsonKeys[ 0 ]; - copy( source ) { + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { - super.copy( source ); + key = jsonKeys[ i ++ ]; - this.curves = []; + } - for ( let i = 0, l = source.curves.length; i < l; i ++ ) { + if ( key === undefined ) return; // no data - const curve = source.curves[ i ]; + let value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - this.curves.push( curve.clone() ); + if ( Array.isArray( value ) ) { - } + do { - this.autoClose = source.autoClose; + value = key[ valuePropertyName ]; - return this; + if ( value !== undefined ) { - } + times.push( key.time ); + values.push.apply( values, value ); // push all elements - toJSON() { + } - const data = super.toJSON(); + key = jsonKeys[ i ++ ]; - data.autoClose = this.autoClose; - data.curves = []; + } while ( key !== undefined ); - for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + } else if ( value.toArray !== undefined ) { - const curve = this.curves[ i ]; - data.curves.push( curve.toJSON() ); + // ...assume THREE.Math-ish - } + do { - return data; + value = key[ valuePropertyName ]; - } + if ( value !== undefined ) { - fromJSON( json ) { + times.push( key.time ); + value.toArray( values, values.length ); - super.fromJSON( json ); + } - this.autoClose = json.autoClose; - this.curves = []; + key = jsonKeys[ i ++ ]; - for ( let i = 0, l = json.curves.length; i < l; i ++ ) { + } while ( key !== undefined ); - const curve = json.curves[ i ]; - this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + } else { - } + // otherwise push as-is - return this; + do { - } + value = key[ valuePropertyName ]; -} + if ( value !== undefined ) { -class Path extends CurvePath { + times.push( key.time ); + values.push( value ); - constructor( points ) { + } - super(); - this.type = 'Path'; + key = jsonKeys[ i ++ ]; - this.currentPoint = new Vector2(); + } while ( key !== undefined ); - if ( points ) { + } - this.setFromPoints( points ); +} - } +function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) { - } + const clip = sourceClip.clone(); - setFromPoints( points ) { + clip.name = name; - this.moveTo( points[ 0 ].x, points[ 0 ].y ); + const tracks = []; - for ( let i = 1, l = points.length; i < l; i ++ ) { + for ( let i = 0; i < clip.tracks.length; ++ i ) { - this.lineTo( points[ i ].x, points[ i ].y ); + const track = clip.tracks[ i ]; + const valueSize = track.getValueSize(); - } + const times = []; + const values = []; - return this; + for ( let j = 0; j < track.times.length; ++ j ) { - } + const frame = track.times[ j ] * fps; - moveTo( x, y ) { + if ( frame < startFrame || frame >= endFrame ) continue; - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + times.push( track.times[ j ] ); - return this; + for ( let k = 0; k < valueSize; ++ k ) { - } + values.push( track.values[ j * valueSize + k ] ); - lineTo( x, y ) { + } - const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); - this.curves.push( curve ); + } - this.currentPoint.set( x, y ); + if ( times.length === 0 ) continue; - return this; + track.times = convertArray( times, track.times.constructor ); + track.values = convertArray( values, track.values.constructor ); + + tracks.push( track ); } - quadraticCurveTo( aCPx, aCPy, aX, aY ) { + clip.tracks = tracks; - const curve = new QuadraticBezierCurve( - this.currentPoint.clone(), - new Vector2( aCPx, aCPy ), - new Vector2( aX, aY ) - ); + // find minimum .times value across all tracks in the trimmed clip - this.curves.push( curve ); + let minStartTime = Infinity; - this.currentPoint.set( aX, aY ); + for ( let i = 0; i < clip.tracks.length; ++ i ) { - return this; + if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { - } + minStartTime = clip.tracks[ i ].times[ 0 ]; - bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + } - const curve = new CubicBezierCurve( - this.currentPoint.clone(), - new Vector2( aCP1x, aCP1y ), - new Vector2( aCP2x, aCP2y ), - new Vector2( aX, aY ) - ); + } - this.curves.push( curve ); + // shift all tracks such that clip begins at t=0 - this.currentPoint.set( aX, aY ); + for ( let i = 0; i < clip.tracks.length; ++ i ) { - return this; + clip.tracks[ i ].shift( - 1 * minStartTime ); } - splineThru( pts /*Array of Vector*/ ) { + clip.resetDuration(); - const npts = [ this.currentPoint.clone() ].concat( pts ); + return clip; - const curve = new SplineCurve( npts ); - this.curves.push( curve ); +} - this.currentPoint.copy( pts[ pts.length - 1 ] ); +function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { - return this; + if ( fps <= 0 ) fps = 30; - } + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; - arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + // Make each track's values relative to the values at the reference frame + for ( let i = 0; i < numTracks; ++ i ) { - const x0 = this.currentPoint.x; - const y0 = this.currentPoint.y; + const referenceTrack = referenceClip.tracks[ i ]; + const referenceTrackType = referenceTrack.ValueTypeName; - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + // Skip this track if it's non-numeric + if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; - return this; + // Find the track in the target clip whose name and type matches the reference track + const targetTrack = targetClip.tracks.find( function ( track ) { - } + return track.name === referenceTrack.name + && track.ValueTypeName === referenceTrackType; - absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + } ); - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + if ( targetTrack === undefined ) continue; - return this; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); - } + if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { - ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + referenceOffset = referenceValueSize / 3; - const x0 = this.currentPoint.x; - const y0 = this.currentPoint.y; + } - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); - return this; + if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { - } + targetOffset = targetValueSize / 3; - absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + } - const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; - if ( this.curves.length > 0 ) { + // Find the value to subtract out of the track + if ( referenceTime <= referenceTrack.times[ 0 ] ) { - // if a previous curve is present, attempt to join - const firstPoint = curve.getPoint( 0 ); + // Reference frame is earlier than the first keyframe, so just use the first keyframe + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); - if ( ! firstPoint.equals( this.currentPoint ) ) { + } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { - this.lineTo( firstPoint.x, firstPoint.y ); + // Reference frame is after the last keyframe, so just use the last keyframe + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); - } + } else { - } + // Interpolate to the reference value + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate( referenceTime ); + referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex ); - this.curves.push( curve ); + } - const lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + // Conjugate the quaternion + if ( referenceTrackType === 'quaternion' ) { - return this; + const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); + referenceQuat.toArray( referenceValue ); - } + } - copy( source ) { + // Subtract the reference value from all of the track values - super.copy( source ); + const numTimes = targetTrack.times.length; + for ( let j = 0; j < numTimes; ++ j ) { - this.currentPoint.copy( source.currentPoint ); + const valueStart = j * targetValueSize + targetOffset; - return this; + if ( referenceTrackType === 'quaternion' ) { - } + // Multiply the conjugate for quaternion track types + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); - toJSON() { + } else { - const data = super.toJSON(); + const valueEnd = targetValueSize - targetOffset * 2; - data.currentPoint = this.currentPoint.toArray(); + // Subtract each value for all other numeric track types + for ( let k = 0; k < valueEnd; ++ k ) { - return data; + targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; - } + } - fromJSON( json ) { + } - super.fromJSON( json ); + } - this.currentPoint.fromArray( json.currentPoint ); + } - return this; + targetClip.blendMode = AdditiveAnimationBlendMode; - } + return targetClip; } -class Shape extends Path { +var AnimationUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + arraySlice: arraySlice, + convertArray: convertArray, + isTypedArray: isTypedArray, + getKeyframeOrder: getKeyframeOrder, + sortedArray: sortedArray, + flattenJSON: flattenJSON, + subclip: subclip, + makeClipAdditive: makeClipAdditive +}); + +/** + * 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 + * + */ - constructor( points ) { +class Interpolant { - super( points ); + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - this.uuid = MathUtils.generateUUID(); + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; - this.type = 'Shape'; + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; - this.holes = []; + this.settings = null; + this.DefaultSettings_ = {}; } - getPointsHoles( divisions ) { + evaluate( t ) { - const holesPts = []; + const pp = this.parameterPositions; + let i1 = this._cachedIndex, + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + validate_interval: { - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + seek: { - } + let right; - return holesPts; + linear_scan: { - } + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - // get points of shape and holes (keypoints based on segments parameter) + for ( let giveUpAt = i1 + 2; ; ) { - extractPoints( divisions ) { + if ( t1 === undefined ) { - return { + if ( t < t0 ) break forward_scan; - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + // after end - }; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); - } + } - copy( source ) { + if ( i1 === giveUpAt ) break; // this loop - super.copy( source ); + t0 = t1; + t1 = pp[ ++ i1 ]; - this.holes = []; + if ( t < t1 ) { - for ( let i = 0, l = source.holes.length; i < l; i ++ ) { + // we have arrived at the sought interval + break seek; - const hole = source.holes[ i ]; + } - this.holes.push( hole.clone() ); + } - } + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - return this; + } - } + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - toJSON() { + // looping? - const data = super.toJSON(); + const t1global = pp[ 1 ]; - data.uuid = this.uuid; - data.holes = []; + if ( t < t1global ) { - for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - const hole = this.holes[ i ]; - data.holes.push( hole.toJSON() ); + } - } + // linear reverse scan - return data; + for ( let giveUpAt = i1 - 2; ; ) { - } + if ( t0 === undefined ) { - fromJSON( json ) { + // before start - super.fromJSON( json ); + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); - this.uuid = json.uuid; - this.holes = []; + } - for ( let i = 0, l = json.holes.length; i < l; i ++ ) { + if ( i1 === giveUpAt ) break; // this loop - const hole = json.holes[ i ]; - this.holes.push( new Path().fromJSON( hole ) ); + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - } + if ( t >= t0 ) { - return this; + // we have arrived at the sought interval + break seek; - } + } -} + } -class Light extends Object3D { + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - constructor( color, intensity = 1 ) { + } - super(); + // the interval is valid - this.type = 'Light'; + break validate_interval; - this.color = new Color( color ); - this.intensity = intensity; + } // linear scan - } + // binary search - copy( source ) { + while ( i1 < right ) { - super.copy( source ); + const mid = ( i1 + right ) >>> 1; - this.color.copy( source.color ); - this.intensity = source.intensity; + if ( t < pp[ mid ] ) { - return this; + right = mid; - } + } else { - toJSON( meta ) { + i1 = mid + 1; - const data = super.toJSON( meta ); + } - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + } - if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - 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; + // check boundary cases, again - if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); + if ( t0 === undefined ) { - return data; + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); - } + } -} + if ( t1 === undefined ) { -Light.prototype.isLight = true; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); -class HemisphereLight extends Light { + } - constructor( skyColor, groundColor, intensity ) { + } // seek - super( skyColor, intensity ); + this._cachedIndex = i1; - this.type = 'HemisphereLight'; + this.intervalChanged_( i1, t0, t1 ); - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + } // validate_interval - this.groundColor = new Color( groundColor ); + return this.interpolate_( i1, t0, t, t1 ); } - copy( source ) { + getSettings_() { - Light.prototype.copy.call( this, source ); + return this.settings || this.DefaultSettings_; - this.groundColor.copy( source.groundColor ); + } - return this; + copySampleValue_( index ) { - } + // copies a sample value to the result buffer -} + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; -HemisphereLight.prototype.isHemisphereLight = true; + for ( let i = 0; i !== stride; ++ i ) { -const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); -const _lightPositionWorld = /*@__PURE__*/ new Vector3(); -const _lookTarget = /*@__PURE__*/ new Vector3(); + result[ i ] = values[ offset + i ]; -class LightShadow { + } - constructor( camera ) { + return result; - this.camera = camera; + } - this.bias = 0; - this.normalBias = 0; - this.radius = 1; + // Template methods for derived classes: - this.mapSize = new Vector2( 512, 512 ); + interpolate_( /* i1, t0, t, t1 */ ) { - this.map = null; - this.mapPass = null; - this.matrix = new Matrix4(); + throw new Error( 'call to abstract method' ); + // implementations shall return this.resultBuffer - this.autoUpdate = true; - this.needsUpdate = false; + } - this._frustum = new Frustum(); - this._frameExtents = new Vector2( 1, 1 ); + intervalChanged_( /* i1, t0, t1 */ ) { - this._viewportCount = 1; + // empty - this._viewports = [ + } - new Vector4( 0, 0, 1, 1 ) +} - ]; +/** + * 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. + */ - } +class CubicInterpolant extends Interpolant { - getViewportCount() { + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - return this._viewportCount; + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - } + this._weightPrev = - 0; + this._offsetPrev = - 0; + this._weightNext = - 0; + this._offsetNext = - 0; - getFrustum() { + this.DefaultSettings_ = { - return this._frustum; + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - } + }; - updateMatrices( light ) { + } - const shadowCamera = this.camera; - const shadowMatrix = this.matrix; + intervalChanged_( i1, t0, t1 ) { - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( _lightPositionWorld ); + const pp = this.parameterPositions; + let iPrev = i1 - 2, + iNext = i1 + 1, - _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _lookTarget ); - shadowCamera.updateMatrixWorld(); + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - this._frustum.setFromProjectionMatrix( _projScreenMatrix ); + if ( tPrev === undefined ) { - 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 - ); + switch ( this.getSettings_().endingStart ) { - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + case ZeroSlopeEnding: - } + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; - getViewport( viewportIndex ) { + break; - return this._viewports[ viewportIndex ]; + case WrapAroundEnding: - } + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - getFrameExtents() { + break; - return this._frameExtents; + default: // ZeroCurvatureEnding - } + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; - copy( source ) { + } - this.camera = source.camera.clone(); + } - this.bias = source.bias; - this.radius = source.radius; + if ( tNext === undefined ) { - this.mapSize.copy( source.mapSize ); + switch ( this.getSettings_().endingEnd ) { - return this; + case ZeroSlopeEnding: - } + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - clone() { + break; - return new this.constructor().copy( this ); + case WrapAroundEnding: - } + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - toJSON() { + break; - const object = {}; + default: // ZeroCurvatureEnding - if ( this.bias !== 0 ) object.bias = this.bias; - if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; - if ( this.radius !== 1 ) object.radius = this.radius; - if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; - object.camera = this.camera.toJSON( false ).object; - delete object.camera.matrix; + } - return object; + } - } + const halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; -} + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; -class SpotLightShadow extends LightShadow { + } - constructor() { + interpolate_( i1, t0, t, t1 ) { - super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - this.focus = 1; + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - } + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - updateMatrices( light ) { + // evaluate polynomials - const camera = this.camera; + const sP = - wP * ppp + 2 * wP * pp - wP * p; + const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; + const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; - const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus; - const aspect = this.mapSize.width / this.mapSize.height; - const far = light.distance || camera.far; + // combine data linearly - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + for ( let i = 0; i !== stride; ++ i ) { - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; } - super.updateMatrices( light ); + return result; } } -SpotLightShadow.prototype.isSpotLightShadow = true; +class LinearInterpolant extends Interpolant { -class SpotLight extends Light { + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) { + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - super( color, intensity ); + } - this.type = 'SpotLight'; + interpolate_( i1, t0, t, t1 ) { - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - this.target = new Object3D(); + offset1 = i1 * stride, + offset0 = offset1 - stride, - this.distance = distance; - this.angle = angle; - this.penumbra = penumbra; - this.decay = decay; // for physically correct lights, should be 2. + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - this.shadow = new SpotLightShadow(); + for ( let i = 0; i !== stride; ++ i ) { - } + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - get power() { + } - // intensity = power per solid angle. - // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - return this.intensity * Math.PI; + return result; } - set power( power ) { - - // intensity = power per solid angle. - // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - this.intensity = power / Math.PI; +} - } +/** + * + * Interpolant that evaluates to the sample value at the position preceding + * the parameter. + */ - copy( source ) { +class DiscreteInterpolant extends Interpolant { - super.copy( source ); + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - this.target = source.target.clone(); + } - this.shadow = source.shadow.clone(); + interpolate_( i1 /*, t0, t, t1 */ ) { - return this; + return this.copySampleValue_( i1 - 1 ); } } -SpotLight.prototype.isSpotLight = true; +class KeyframeTrack { -const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); -const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); -const _lookTarget$1 = /*@__PURE__*/ new Vector3(); + constructor( name, times, values, interpolation ) { -class PointLightShadow extends LightShadow { + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); - constructor() { + this.name = name; - super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + this.times = convertArray( times, this.TimeBufferType ); + this.values = convertArray( values, this.ValueBufferType ); - this._frameExtents = new Vector2( 4, 2 ); + this.setInterpolation( interpolation || this.DefaultInterpolation ); - this._viewportCount = 6; + } - this._viewports = [ - // 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 + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - // positive X - new Vector4( 2, 1, 1, 1 ), - // negative X - new Vector4( 0, 1, 1, 1 ), - // positive Z - new Vector4( 3, 1, 1, 1 ), - // negative Z - new Vector4( 1, 1, 1, 1 ), - // positive Y - new Vector4( 3, 0, 1, 1 ), - // negative Y - new Vector4( 1, 0, 1, 1 ) - ]; + static toJSON( track ) { - this._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 ) - ]; + const trackType = track.constructor; - this._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 ) - ]; + let json; - } + // derived classes can define a static toJSON method + if ( trackType.toJSON !== this.toJSON ) { - updateMatrices( light, viewportIndex = 0 ) { + json = trackType.toJSON( track ); - const camera = this.camera; - const shadowMatrix = this.matrix; + } else { - _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); - camera.position.copy( _lightPositionWorld$1 ); + // by default, we assume the data can be serialized as-is + json = { - _lookTarget$1.copy( camera.position ); - _lookTarget$1.add( this._cubeDirections[ viewportIndex ] ); - camera.up.copy( this._cubeUps[ viewportIndex ] ); - camera.lookAt( _lookTarget$1 ); - camera.updateMatrixWorld(); + 'name': track.name, + 'times': convertArray( track.times, Array ), + 'values': convertArray( track.values, Array ) - shadowMatrix.makeTranslation( - _lightPositionWorld$1.x, - _lightPositionWorld$1.y, - _lightPositionWorld$1.z ); + }; - _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); + const interpolation = track.getInterpolation(); - } + if ( interpolation !== track.DefaultInterpolation ) { -} + json.interpolation = interpolation; -PointLightShadow.prototype.isPointLightShadow = true; + } -class PointLight extends Light { + } - constructor( color, intensity, distance = 0, decay = 1 ) { + json.type = track.ValueTypeName; // mandatory - super( color, intensity ); + return json; - this.type = 'PointLight'; + } - this.distance = distance; - this.decay = decay; // for physically correct lights, should be 2. + InterpolantFactoryMethodDiscrete( result ) { - this.shadow = new PointLightShadow(); + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); } - get power() { + InterpolantFactoryMethodLinear( result ) { - // intensity = power per solid angle. - // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - return this.intensity * 4 * Math.PI; + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); } - set power( power ) { + InterpolantFactoryMethodSmooth( result ) { + + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + setInterpolation( interpolation ) { + + let factoryMethod; - // intensity = power per solid angle. - // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - this.intensity = power / ( 4 * Math.PI ); + switch ( interpolation ) { - } + case InterpolateDiscrete: - copy( source ) { + factoryMethod = this.InterpolantFactoryMethodDiscrete; - super.copy( source ); + break; - this.distance = source.distance; - this.decay = source.decay; + case InterpolateLinear: - this.shadow = source.shadow.clone(); + factoryMethod = this.InterpolantFactoryMethodLinear; - return this; + break; - } + case InterpolateSmooth: -} + factoryMethod = this.InterpolantFactoryMethodSmooth; -PointLight.prototype.isPointLight = true; + break; -class OrthographicCamera extends Camera { + } - constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { + if ( factoryMethod === undefined ) { - super(); + const message = 'unsupported interpolation for ' + + this.ValueTypeName + ' keyframe track named ' + this.name; - this.type = 'OrthographicCamera'; + if ( this.createInterpolant === undefined ) { - this.zoom = 1; - this.view = null; + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + this.setInterpolation( this.DefaultInterpolation ); - this.near = near; - this.far = far; + } else { - this.updateProjectionMatrix(); + throw new Error( message ); // fatal, in this case - } + } - copy( source, recursive ) { + } - super.copy( source, recursive ); + console.warn( 'THREE.KeyframeTrack:', message ); + return this; - 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 ); + this.createInterpolant = factoryMethod; return this; } - setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + getInterpolation() { - if ( this.view === null ) { + switch ( this.createInterpolant ) { - this.view = { - enabled: true, - fullWidth: 1, - fullHeight: 1, - offsetX: 0, - offsetY: 0, - width: 1, - height: 1 - }; + case this.InterpolantFactoryMethodDiscrete: - } + return InterpolateDiscrete; - this.view.enabled = true; - this.view.fullWidth = fullWidth; - this.view.fullHeight = fullHeight; - this.view.offsetX = x; - this.view.offsetY = y; - this.view.width = width; - this.view.height = height; + case this.InterpolantFactoryMethodLinear: - this.updateProjectionMatrix(); + return InterpolateLinear; - } + case this.InterpolantFactoryMethodSmooth: - clearViewOffset() { + return InterpolateSmooth; - if ( this.view !== null ) { + } - this.view.enabled = false; + } - } + getValueSize() { - this.updateProjectionMatrix(); + return this.values.length / this.times.length; } - updateProjectionMatrix() { + // move all keyframes either forwards or backwards in time + shift( timeOffset ) { - const dx = ( this.right - this.left ) / ( 2 * this.zoom ); - const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - const cx = ( this.right + this.left ) / 2; - const cy = ( this.top + this.bottom ) / 2; + if ( timeOffset !== 0.0 ) { - let left = cx - dx; - let right = cx + dx; - let top = cy + dy; - let bottom = cy - dy; + const times = this.times; - if ( this.view !== null && this.view.enabled ) { + for ( let i = 0, n = times.length; i !== n; ++ i ) { - const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; - const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + times[ i ] += timeOffset; - left += scaleW * this.view.offsetX; - right = left + scaleW * this.view.width; - top -= scaleH * this.view.offsetY; - bottom = top - scaleH * this.view.height; + } } - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - - this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + return this; } - toJSON( meta ) { + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale( timeScale ) { - const data = Object3D.prototype.toJSON.call( this, meta ); + if ( timeScale !== 1.0 ) { - 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; + const times = this.times; - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + for ( let i = 0, n = times.length; i !== n; ++ i ) { - return data; + times[ i ] *= timeScale; - } + } -} + } -OrthographicCamera.prototype.isOrthographicCamera = true; + return this; -class DirectionalLightShadow extends LightShadow { + } - constructor() { + // 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( startTime, endTime ) { - super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + const times = this.times, + nKeys = times.length; - } + let from = 0, + to = nKeys - 1; -} + while ( from !== nKeys && times[ from ] < startTime ) { -DirectionalLightShadow.prototype.isDirectionalLightShadow = true; + ++ from; -class DirectionalLight extends Light { + } - constructor( color, intensity ) { + while ( to !== - 1 && times[ to ] > endTime ) { - super( color, intensity ); + -- to; - this.type = 'DirectionalLight'; + } - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + ++ to; // inclusive -> exclusive bound - this.target = new Object3D(); + if ( from !== 0 || to !== nKeys ) { - this.shadow = new DirectionalLightShadow(); + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) { - } + to = Math.max( to, 1 ); + from = to - 1; - copy( source ) { + } - super.copy( source ); + const stride = this.getValueSize(); + this.times = arraySlice( times, from, to ); + this.values = arraySlice( this.values, from * stride, to * stride ); - this.target = source.target.clone(); - this.shadow = source.shadow.clone(); + } return this; } -} + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate() { -DirectionalLight.prototype.isDirectionalLight = true; + let valid = true; -class AmbientLight extends Light { + const valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - constructor( color, intensity ) { + console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); + valid = false; - super( color, intensity ); + } - this.type = 'AmbientLight'; + const times = this.times, + values = this.values, - } + nKeys = times.length; -} + if ( nKeys === 0 ) { -AmbientLight.prototype.isAmbientLight = true; + console.error( 'THREE.KeyframeTrack: Track is empty.', this ); + valid = false; -class RectAreaLight extends Light { + } - constructor( color, intensity, width = 10, height = 10 ) { + let prevTime = null; - super( color, intensity ); + for ( let i = 0; i !== nKeys; i ++ ) { - this.type = 'RectAreaLight'; + const currTime = times[ i ]; - this.width = width; - this.height = height; + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - } + console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; - copy( source ) { + } - super.copy( source ); + if ( prevTime !== null && prevTime > currTime ) { - this.width = source.width; - this.height = source.height; + console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; - return this; + } - } + prevTime = currTime; - toJSON( meta ) { + } - const data = super.toJSON( meta ); + if ( values !== undefined ) { - data.object.width = this.width; - data.object.height = this.height; + if ( isTypedArray( values ) ) { - return data; + for ( let i = 0, n = values.length; i !== n; ++ i ) { - } + const value = values[ i ]; -} + if ( isNaN( value ) ) { -RectAreaLight.prototype.isRectAreaLight = true; + console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); + valid = false; + break; -/** - * Primary reference: - * https://graphics.stanford.edu/papers/envmap/envmap.pdf - * - * Secondary reference: - * https://www.ppsloan.org/publications/StupidSH36.pdf - */ + } -// 3-band SH defined by 9 coefficients + } -class SphericalHarmonics3 { + } - constructor() { + } - this.coefficients = []; + return valid; - for ( let i = 0; i < 9; i ++ ) { + } - this.coefficients.push( new Vector3() ); + // 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() { - } + // times or values may be shared with other tracks, so overwriting is unsafe + const times = arraySlice( this.times ), + values = arraySlice( this.values ), + stride = this.getValueSize(), - } + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, - set( coefficients ) { + lastIndex = times.length - 1; - for ( let i = 0; i < 9; i ++ ) { + let writeIndex = 1; - this.coefficients[ i ].copy( coefficients[ i ] ); + for ( let i = 1; i < lastIndex; ++ i ) { - } + let keep = false; - return this; + const time = times[ i ]; + const timeNext = times[ i + 1 ]; - } + // remove adjacent keyframes scheduled at the same time - zero() { + if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { - for ( let i = 0; i < 9; i ++ ) { + if ( ! smoothInterpolation ) { - this.coefficients[ i ].set( 0, 0, 0 ); + // remove unnecessary keyframes same as their neighbors - } + const offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - return this; + for ( let j = 0; j !== stride; ++ j ) { - } + const value = values[ offset + j ]; - // get the radiance in the direction of the normal - // target is a Vector3 - getAt( normal, target ) { + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - // normal is assumed to be unit length + keep = true; + break; - const x = normal.x, y = normal.y, z = normal.z; + } - const coeff = this.coefficients; + } - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); + } else { - // band 1 - target.addScaledVector( coeff[ 1 ], 0.488603 * y ); - target.addScaledVector( coeff[ 2 ], 0.488603 * z ); - target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + keep = true; - // band 2 - target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); - target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); - target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); - target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); - target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + } - return target; + } - } + // in-place compaction - // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal - // target is a Vector3 - // https://graphics.stanford.edu/papers/envmap/envmap.pdf - getIrradianceAt( normal, target ) { + if ( keep ) { - // normal is assumed to be unit length + if ( i !== writeIndex ) { - const x = normal.x, y = normal.y, z = normal.z; + times[ writeIndex ] = times[ i ]; - const coeff = this.coefficients; + const readOffset = i * stride, + writeOffset = writeIndex * stride; - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 + for ( let j = 0; j !== stride; ++ j ) { - // band 1 - target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 - target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); - target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); + values[ writeOffset + j ] = values[ readOffset + j ]; - // band 2 - target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 - target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); - target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 - target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); - target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 + } - return target; + } - } + ++ writeIndex; - add( sh ) { + } - for ( let i = 0; i < 9; i ++ ) { + } - this.coefficients[ i ].add( sh.coefficients[ i ] ); + // flush last keyframe (compaction looks ahead) - } + if ( lastIndex > 0 ) { - return this; + times[ writeIndex ] = times[ lastIndex ]; - } + for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { - addScaledSH( sh, s ) { + values[ writeOffset + j ] = values[ readOffset + j ]; - for ( let i = 0; i < 9; i ++ ) { + } - this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); + ++ writeIndex; } - return this; - - } + if ( writeIndex !== times.length ) { - scale( s ) { + this.times = arraySlice( times, 0, writeIndex ); + this.values = arraySlice( values, 0, writeIndex * stride ); - for ( let i = 0; i < 9; i ++ ) { + } else { - this.coefficients[ i ].multiplyScalar( s ); + this.times = times; + this.values = values; } @@ -37761,2486 +38904,2453 @@ class SphericalHarmonics3 { } - lerp( sh, alpha ) { + clone() { - for ( let i = 0; i < 9; i ++ ) { + const times = arraySlice( this.times, 0 ); + const values = arraySlice( this.values, 0 ); - this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack( this.name, times, values ); - } + // Interpolant argument to constructor is not saved, so copy the factory method directly. + track.createInterpolant = this.createInterpolant; - return this; + return track; } - equals( sh ) { - - for ( let i = 0; i < 9; i ++ ) { +} - if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; - return false; +/** + * A Track of Boolean keyframe values. + */ +class BooleanKeyframeTrack extends KeyframeTrack {} - } +BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - } +/** + * A Track of keyframe values that represent color. + */ +class ColorKeyframeTrack extends KeyframeTrack {} - return true; +ColorKeyframeTrack.prototype.ValueTypeName = 'color'; - } +/** + * A Track of numeric keyframe values. + */ +class NumberKeyframeTrack extends KeyframeTrack {} - copy( sh ) { +NumberKeyframeTrack.prototype.ValueTypeName = 'number'; - return this.set( sh.coefficients ); +/** + * Spherical linear unit quaternion interpolant. + */ - } +class QuaternionLinearInterpolant extends Interpolant { - clone() { + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - return new this.constructor().copy( this ); + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); } - fromArray( array, offset = 0 ) { + interpolate_( i1, t0, t, t1 ) { - const coefficients = this.coefficients; + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - for ( let i = 0; i < 9; i ++ ) { + alpha = ( t - t0 ) / ( t1 - t0 ); - coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); + let offset = i1 * stride; - } + for ( let end = offset + stride; offset !== end; offset += 4 ) { - return this; + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); - } + } - toArray( array = [], offset = 0 ) { + return result; - const coefficients = this.coefficients; + } - for ( let i = 0; i < 9; i ++ ) { +} - coefficients[ i ].toArray( array, offset + ( i * 3 ) ); +/** + * A Track of quaternion keyframe values. + */ +class QuaternionKeyframeTrack extends KeyframeTrack { - } + InterpolantFactoryMethodLinear( result ) { - return array; + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); } - // evaluate the basis functions - // shBasis is an Array[ 9 ] - static getBasisAt( normal, shBasis ) { +} - // normal is assumed to be unit length +QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; +// ValueBufferType is inherited +QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - const x = normal.x, y = normal.y, z = normal.z; +/** + * A Track that interpolates Strings + */ +class StringKeyframeTrack extends KeyframeTrack {} - // band 0 - shBasis[ 0 ] = 0.282095; +StringKeyframeTrack.prototype.ValueTypeName = 'string'; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; - // band 1 - shBasis[ 1 ] = 0.488603 * y; - shBasis[ 2 ] = 0.488603 * z; - shBasis[ 3 ] = 0.488603 * x; +/** + * A Track of vectored keyframe values. + */ +class VectorKeyframeTrack extends KeyframeTrack {} - // band 2 - shBasis[ 4 ] = 1.092548 * x * y; - shBasis[ 5 ] = 1.092548 * y * z; - shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); - shBasis[ 7 ] = 1.092548 * x * z; - shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); +VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; - } +class AnimationClip { -} + constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) { -SphericalHarmonics3.prototype.isSphericalHarmonics3 = true; + this.name = name; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; -class LightProbe extends Light { + this.uuid = generateUUID(); - constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - super( undefined, intensity ); + this.resetDuration(); - this.sh = sh; + } } - copy( source ) { - super.copy( source ); + static parse( json ) { - this.sh.copy( source.sh ); + const tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); - return this; + for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { - } + tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); - fromJSON( json ) { + } - this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); - this.sh.fromArray( json.sh ); + const clip = new this( json.name, json.duration, tracks, json.blendMode ); + clip.uuid = json.uuid; - return this; + return clip; } - toJSON( meta ) { - - const data = super.toJSON( meta ); + static toJSON( clip ) { - data.object.sh = this.sh.toArray(); + const tracks = [], + clipTracks = clip.tracks; - return data; + const json = { - } + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks, + 'uuid': clip.uuid, + 'blendMode': clip.blendMode -} + }; -LightProbe.prototype.isLightProbe = true; + for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { -class MaterialLoader extends Loader { + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - constructor( manager ) { + } - super( manager ); - this.textures = {}; + return json; } - load( url, onLoad, onProgress, onError ) { - - const scope = this; + static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { - const loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.setRequestHeader( scope.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; - try { + for ( let i = 0; i < numMorphTargets; i ++ ) { - onLoad( scope.parse( JSON.parse( text ) ) ); + let times = []; + let values = []; - } catch ( e ) { + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); - if ( onError ) { + values.push( 0, 1, 0 ); - onError( e ); + const order = getKeyframeOrder( times ); + times = sortedArray( times, 1, order ); + values = sortedArray( values, 1, order ); - } else { + // 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 ) { - console.error( e ); + times.push( numMorphTargets ); + values.push( values[ 0 ] ); - } + } - scope.manager.itemError( url ); + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); - } + } - }, onProgress, onError ); + return new this( name, - 1, tracks ); } - parse( json ) { - - const textures = this.textures; + static findByName( objectOrClipArray, name ) { - function getTexture( name ) { + let clipArray = objectOrClipArray; - if ( textures[ name ] === undefined ) { + if ( ! Array.isArray( objectOrClipArray ) ) { - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; - } + } - return textures[ name ]; + for ( let i = 0; i < clipArray.length; i ++ ) { - } + if ( clipArray[ i ].name === name ) { - const material = new Materials[ json.type ](); + return clipArray[ i ]; - if ( json.uuid !== undefined ) material.uuid = json.uuid; - if ( json.name !== undefined ) material.name = json.name; - if ( json.color !== undefined && material.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.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen ); - if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; - if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; - if ( json.fog !== undefined ) material.fog = json.fog; - if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.combine !== undefined ) material.combine = json.combine; - 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.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; - if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; - if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; - if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; - if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; - if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; - if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; - if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; + } - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; - if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; - if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; + return null; - if ( json.rotation !== undefined ) material.rotation = json.rotation; + } - if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; - if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; - if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; - if ( json.scale !== undefined ) material.scale = json.scale; + static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { - if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; - if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; - if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; + const animationToMorphTargets = {}; - if ( json.skinning !== undefined ) material.skinning = json.skinning; - if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets; - if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals; - if ( json.dithering !== undefined ) material.dithering = json.dithering; + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + const pattern = /^([\w-]*?)([\d]+)$/; - if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents; + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { - if ( json.visible !== undefined ) material.visible = json.visible; + const morphTarget = morphTargets[ i ]; + const parts = morphTarget.name.match( pattern ); - if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; + if ( parts && parts.length > 1 ) { - if ( json.userData !== undefined ) material.userData = json.userData; + const name = parts[ 1 ]; - if ( json.vertexColors !== undefined ) { + let animationMorphTargets = animationToMorphTargets[ name ]; - if ( typeof json.vertexColors === 'number' ) { + if ( ! animationMorphTargets ) { - material.vertexColors = ( json.vertexColors > 0 ) ? true : false; + animationToMorphTargets[ name ] = animationMorphTargets = []; - } else { + } - material.vertexColors = json.vertexColors; + animationMorphTargets.push( morphTarget ); } } - // Shader Material - - if ( json.uniforms !== undefined ) { - - for ( const name in json.uniforms ) { - - const uniform = json.uniforms[ name ]; - - material.uniforms[ name ] = {}; + const clips = []; - switch ( uniform.type ) { + for ( const name in animationToMorphTargets ) { - case 't': - material.uniforms[ name ].value = getTexture( uniform.value ); - break; + clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); - case 'c': - material.uniforms[ name ].value = new Color().setHex( uniform.value ); - break; + } - case 'v2': - material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); - break; + return clips; - case 'v3': - material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); - break; + } - case 'v4': - material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); - break; + // parse the animation.hierarchy format + static parseAnimation( animation, bones ) { - case 'm3': - material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); - break; + if ( ! animation ) { - case 'm4': - material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); - break; + console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); + return null; - default: - material.uniforms[ name ].value = uniform.value; + } - } + const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { - } + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { - } + const times = []; + const values = []; - if ( json.defines !== undefined ) material.defines = json.defines; - if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; - if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + flattenJSON( animationKeys, times, values, propertyName ); - if ( json.extensions !== undefined ) { + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - for ( const key in json.extensions ) { + destTracks.push( new trackType( trackName, times, values ) ); - material.extensions[ key ] = json.extensions[ key ]; + } } - } - - // Deprecated + }; - if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading + const tracks = []; - // for PointsMaterial + const clipName = animation.name || 'default'; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + // automatic length determination in AnimationClip. + let duration = animation.length || - 1; - // maps + const hierarchyTracks = animation.hierarchy || []; - if ( json.map !== undefined ) material.map = getTexture( json.map ); - if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); + for ( let h = 0; h < hierarchyTracks.length; h ++ ) { - if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); + const animationKeys = hierarchyTracks[ h ].keys; - if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); - if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); - if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; - if ( json.normalScale !== undefined ) { + // process morph targets + if ( animationKeys[ 0 ].morphTargets ) { - let normalScale = json.normalScale; + // figure out all morph targets used in this track + const morphTargetNames = {}; - if ( Array.isArray( normalScale ) === false ) { + let k; - // Blender exporter used to export a scalar. See #7459 + for ( k = 0; k < animationKeys.length; k ++ ) { - normalScale = [ normalScale, normalScale ]; + if ( animationKeys[ k ].morphTargets ) { - } + for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { - material.normalScale = new Vector2().fromArray( normalScale ); + morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; - } + } - if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); - if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; - if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; + } - if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); - if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); + } - if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); - if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( const morphTargetName in morphTargetNames ) { - if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + const times = []; + const values = []; - if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); - if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; + for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { - if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; - if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; + const animationKey = animationKeys[ k ]; - if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + } - if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); - if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); - if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); - if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + } - if ( json.transmission !== undefined ) material.transmission = json.transmission; - if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); + duration = morphTargetNames.length * fps; - return material; + } else { - } + // ...assume skeletal animation - setTextures( value ) { + const boneName = '.bones[' + bones[ h ].name + ']'; - this.textures = value; - return this; + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - } + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); -} + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); -const LoaderUtils = { + } - decodeText: function ( array ) { + } - if ( typeof TextDecoder !== 'undefined' ) { + if ( tracks.length === 0 ) { - return new TextDecoder().decode( array ); + return null; } - // Avoid the String.fromCharCode.apply(null, array) shortcut, which - // throws a "maximum call stack size exceeded" error for large arrays. + const clip = new this( clipName, duration, tracks, blendMode ); - let s = ''; + return clip; - for ( let i = 0, il = array.length; i < il; i ++ ) { + } - // Implicitly assumes little-endian. - s += String.fromCharCode( array[ i ] ); + resetDuration() { - } + const tracks = this.tracks; + let duration = 0; - try { + for ( let i = 0, n = tracks.length; i !== n; ++ i ) { - // merges multi-byte utf-8 characters. + const track = this.tracks[ i ]; - return decodeURIComponent( escape( s ) ); + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); - } catch ( e ) { // see #16358 + } - return s; + this.duration = duration; - } + return this; - }, + } - extractUrlBase: function ( url ) { + trim() { - const index = url.lastIndexOf( '/' ); + for ( let i = 0; i < this.tracks.length; i ++ ) { - if ( index === - 1 ) return './'; + this.tracks[ i ].trim( 0, this.duration ); + + } - return url.substr( 0, index + 1 ); + return this; } -}; + validate() { -function InstancedBufferGeometry() { + let valid = true; - BufferGeometry.call( this ); + for ( let i = 0; i < this.tracks.length; i ++ ) { - this.type = 'InstancedBufferGeometry'; - this.instanceCount = Infinity; + valid = valid && this.tracks[ i ].validate(); -} + } -InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), { + return valid; - constructor: InstancedBufferGeometry, + } - isInstancedBufferGeometry: true, + optimize() { - copy: function ( source ) { + for ( let i = 0; i < this.tracks.length; i ++ ) { - BufferGeometry.prototype.copy.call( this, source ); + this.tracks[ i ].optimize(); - this.instanceCount = source.instanceCount; + } return this; - }, - - clone: function () { - - return new this.constructor().copy( this ); + } - }, + clone() { - toJSON: function () { + const tracks = []; - const data = BufferGeometry.prototype.toJSON.call( this ); + for ( let i = 0; i < this.tracks.length; i ++ ) { - data.instanceCount = this.instanceCount; + tracks.push( this.tracks[ i ].clone() ); - data.isInstancedBufferGeometry = true; + } - return data; + return new this.constructor( this.name, this.duration, tracks, this.blendMode ); } -} ); + toJSON() { + + return this.constructor.toJSON( this ); -function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) { + } - if ( typeof ( normalized ) === 'number' ) { +} - meshPerAttribute = normalized; +function getTrackTypeForValueTypeName( typeName ) { - normalized = false; + switch ( typeName.toLowerCase() ) { - console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' ); + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': - } + return NumberKeyframeTrack; - BufferAttribute.call( this, array, itemSize, normalized ); + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': - this.meshPerAttribute = meshPerAttribute || 1; + return VectorKeyframeTrack; -} + case 'color': -InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), { + return ColorKeyframeTrack; - constructor: InstancedBufferAttribute, + case 'quaternion': - isInstancedBufferAttribute: true, + return QuaternionKeyframeTrack; - copy: function ( source ) { + case 'bool': + case 'boolean': - BufferAttribute.prototype.copy.call( this, source ); + return BooleanKeyframeTrack; - this.meshPerAttribute = source.meshPerAttribute; + case 'string': - return this; + return StringKeyframeTrack; - }, + } - toJSON: function () { + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); - const data = BufferAttribute.prototype.toJSON.call( this ); +} - data.meshPerAttribute = this.meshPerAttribute; +function parseKeyframeTrack( json ) { - data.isInstancedBufferAttribute = true; + if ( json.type === undefined ) { - return data; + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); } -} ); + const trackType = getTrackTypeForValueTypeName( json.type ); -class BufferGeometryLoader extends Loader { + if ( json.times === undefined ) { - constructor( manager ) { + const times = [], values = []; - super( manager ); + flattenJSON( json.keys, times, values, 'value' ); + + json.times = times; + json.values = values; } - load( url, onLoad, onProgress, onError ) { + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - const scope = this; + return trackType.parse( json ); - const loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.setRequestHeader( scope.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { + } else { - try { + // by default, we assume a constructor compatible with the base + return new trackType( json.name, json.times, json.values, json.interpolation ); - onLoad( scope.parse( JSON.parse( text ) ) ); + } - } catch ( e ) { +} - if ( onError ) { +const Cache = { - onError( e ); + enabled: false, - } else { + files: {}, - console.error( e ); + add: function ( key, file ) { - } + if ( this.enabled === false ) return; - scope.manager.itemError( url ); + // console.log( 'THREE.Cache', 'Adding key:', key ); - } + this.files[ key ] = file; - }, onProgress, onError ); + }, + + get: function ( key ) { - } + if ( this.enabled === false ) return; - parse( json ) { + // console.log( 'THREE.Cache', 'Checking key:', key ); - const interleavedBufferMap = {}; - const arrayBufferMap = {}; + return this.files[ key ]; - function getInterleavedBuffer( json, uuid ) { + }, - if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; + remove: function ( key ) { - const interleavedBuffers = json.interleavedBuffers; - const interleavedBuffer = interleavedBuffers[ uuid ]; + delete this.files[ key ]; - const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); + }, - const array = getTypedArray( interleavedBuffer.type, buffer ); - const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); - ib.uuid = interleavedBuffer.uuid; + clear: function () { - interleavedBufferMap[ uuid ] = ib; + this.files = {}; - return ib; + } - } +}; - function getArrayBuffer( json, uuid ) { +class LoadingManager { - if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; + constructor( onLoad, onProgress, onError ) { - const arrayBuffers = json.arrayBuffers; - const arrayBuffer = arrayBuffers[ uuid ]; + const scope = this; - const ab = new Uint32Array( arrayBuffer ).buffer; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; - arrayBufferMap[ uuid ] = ab; + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor - return ab; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - } + this.itemStart = function ( url ) { - const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + itemsTotal ++; - const index = json.data.index; + if ( isLoading === false ) { - if ( index !== undefined ) { + if ( scope.onStart !== undefined ) { - const typedArray = getTypedArray( index.type, index.array ); - geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + scope.onStart( url, itemsLoaded, itemsTotal ); - } + } - const attributes = json.data.attributes; + } - for ( const key in attributes ) { + isLoading = true; - const attribute = attributes[ key ]; - let bufferAttribute; + }; - if ( attribute.isInterleavedBufferAttribute ) { + this.itemEnd = function ( url ) { - const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); - bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + itemsLoaded ++; - } else { + if ( scope.onProgress !== undefined ) { - const typedArray = getTypedArray( attribute.type, attribute.array ); - const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; - bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); + scope.onProgress( url, itemsLoaded, itemsTotal ); } - if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; - geometry.setAttribute( key, bufferAttribute ); + if ( itemsLoaded === itemsTotal ) { - } + isLoading = false; - const morphAttributes = json.data.morphAttributes; + if ( scope.onLoad !== undefined ) { - if ( morphAttributes ) { + scope.onLoad(); - for ( const key in morphAttributes ) { + } - const attributeArray = morphAttributes[ key ]; + } - const array = []; + }; - for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + this.itemError = function ( url ) { - const attribute = attributeArray[ i ]; - let bufferAttribute; + if ( scope.onError !== undefined ) { - if ( attribute.isInterleavedBufferAttribute ) { + scope.onError( url ); - const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); - bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + } - } else { + }; - const typedArray = getTypedArray( attribute.type, attribute.array ); - bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + this.resolveURL = function ( url ) { - } + if ( urlModifier ) { - if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; - array.push( bufferAttribute ); + return urlModifier( url ); - } + } - geometry.morphAttributes[ key ] = array; + return url; - } + }; - } + this.setURLModifier = function ( transform ) { - const morphTargetsRelative = json.data.morphTargetsRelative; + urlModifier = transform; - if ( morphTargetsRelative ) { + return this; - geometry.morphTargetsRelative = true; + }; - } + this.addHandler = function ( regex, loader ) { - const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + handlers.push( regex, loader ); - if ( groups !== undefined ) { + return this; - for ( let i = 0, n = groups.length; i !== n; ++ i ) { + }; - const group = groups[ i ]; + this.removeHandler = function ( regex ) { - geometry.addGroup( group.start, group.count, group.materialIndex ); + const index = handlers.indexOf( regex ); + + if ( index !== - 1 ) { + + handlers.splice( index, 2 ); } - } + return this; - const boundingSphere = json.data.boundingSphere; + }; - if ( boundingSphere !== undefined ) { + this.getHandler = function ( file ) { - const center = new Vector3(); + for ( let i = 0, l = handlers.length; i < l; i += 2 ) { - if ( boundingSphere.center !== undefined ) { + const regex = handlers[ i ]; + const loader = handlers[ i + 1 ]; - center.fromArray( boundingSphere.center ); + if ( regex.global ) regex.lastIndex = 0; // see #17920 - } + if ( regex.test( file ) ) { - geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + return loader; - } + } - if ( json.name ) geometry.name = json.name; - if ( json.userData ) geometry.userData = json.userData; + } - return geometry; + return null; + + }; } } -class ObjectLoader extends Loader { +const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); + +class Loader { constructor( manager ) { - super( manager ); + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + this.crossOrigin = 'anonymous'; + this.withCredentials = false; + this.path = ''; + this.resourcePath = ''; + this.requestHeader = {}; } - load( url, onLoad, onProgress, onError ) { + load( /* url, onLoad, onProgress, onError */ ) {} + + loadAsync( url, onProgress ) { const scope = this; - const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; - this.resourcePath = this.resourcePath || path; + return new Promise( function ( resolve, reject ) { - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + scope.load( url, resolve, onProgress, reject ); - let json = null; + } ); - try { + } - json = JSON.parse( text ); + parse( /* data */ ) {} - } catch ( error ) { + setCrossOrigin( crossOrigin ) { - if ( onError !== undefined ) onError( error ); + this.crossOrigin = crossOrigin; + return this; - console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); + } - return; + setWithCredentials( value ) { - } + this.withCredentials = value; + return this; - const metadata = json.metadata; + } - if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + setPath( path ) { - console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); - return; + this.path = path; + return this; - } + } - scope.parse( json, onLoad ); + setResourcePath( resourcePath ) { - }, onProgress, onError ); + this.resourcePath = resourcePath; + return this; } - parse( json, onLoad ) { - - const animations = this.parseAnimations( json.animations ); - const shapes = this.parseShapes( json.shapes ); - const geometries = this.parseGeometries( json.geometries, shapes ); + setRequestHeader( requestHeader ) { - const images = this.parseImages( json.images, function () { + this.requestHeader = requestHeader; + return this; - if ( onLoad !== undefined ) onLoad( object ); + } - } ); +} - const textures = this.parseTextures( json.textures, images ); - const materials = this.parseMaterials( json.materials, textures ); +const loading = {}; - const object = this.parseObject( json.object, geometries, materials, animations ); - const skeletons = this.parseSkeletons( json.skeletons, object ); +class HttpError extends Error { - this.bindSkeletons( object, skeletons ); + constructor( message, response ) { - // + super( message ); + this.response = response; - if ( onLoad !== undefined ) { + } - let hasImages = false; +} - for ( const uuid in images ) { +class FileLoader extends Loader { - if ( images[ uuid ] instanceof HTMLImageElement ) { + constructor( manager ) { - hasImages = true; - break; + super( manager ); - } + } - } + load( url, onLoad, onProgress, onError ) { - if ( hasImages === false ) onLoad( object ); + if ( url === undefined ) url = ''; - } + if ( this.path !== undefined ) url = this.path + url; - return object; + url = this.manager.resolveURL( url ); - } + const cached = Cache.get( url ); - parseShapes( json ) { + if ( cached !== undefined ) { - const shapes = {}; + this.manager.itemStart( url ); - if ( json !== undefined ) { + setTimeout( () => { - for ( let i = 0, l = json.length; i < l; i ++ ) { + if ( onLoad ) onLoad( cached ); - const shape = new Shape().fromJSON( json[ i ] ); + this.manager.itemEnd( url ); - shapes[ shape.uuid ] = shape; + }, 0 ); - } + return cached; } - return shapes; + // Check if request is duplicate - } + if ( loading[ url ] !== undefined ) { - parseSkeletons( json, object ) { + loading[ url ].push( { - const skeletons = {}; - const bones = {}; + onLoad: onLoad, + onProgress: onProgress, + onError: onError - // generate bone lookup table + } ); - object.traverse( function ( child ) { + return; - if ( child.isBone ) bones[ child.uuid ] = child; + } + // Initialise array for duplicate requests + loading[ url ] = []; + + loading[ url ].push( { + onLoad: onLoad, + onProgress: onProgress, + onError: onError, } ); - // create skeletons + // create request + const req = new Request( url, { + headers: new Headers( this.requestHeader ), + credentials: this.withCredentials ? 'include' : 'same-origin', + // An abort controller could be added within a future PR + } ); - if ( json !== undefined ) { + // record states ( avoid data race ) + const mimeType = this.mimeType; + const responseType = this.responseType; - for ( let i = 0, l = json.length; i < l; i ++ ) { + // start the fetch + fetch( req ) + .then( response => { - const skeleton = new Skeleton().fromJSON( json[ i ], bones ); + if ( response.status === 200 || response.status === 0 ) { - skeletons[ skeleton.uuid ] = skeleton; + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. - } + if ( response.status === 0 ) { - } + console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); - return skeletons; + } - } + // Workaround: Checking if response.body === undefined for Alipay browser #23548 - parseGeometries( json, shapes ) { + if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) { - const geometries = {}; - let geometryShapes; + return response; - if ( json !== undefined ) { + } - const bufferGeometryLoader = new BufferGeometryLoader(); + const callbacks = loading[ url ]; + const reader = response.body.getReader(); + const contentLength = response.headers.get( 'Content-Length' ); + const total = contentLength ? parseInt( contentLength ) : 0; + const lengthComputable = total !== 0; + let loaded = 0; - for ( let i = 0, l = json.length; i < l; i ++ ) { + // periodically read data into the new stream tracking while download progress + const stream = new ReadableStream( { + start( controller ) { - let geometry; - const data = json[ i ]; + readData(); - switch ( data.type ) { + function readData() { - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + reader.read().then( ( { done, value } ) => { - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + if ( done ) { - break; + controller.close(); - case 'BoxGeometry': - case 'BoxBufferGeometry': + } else { - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + loaded += value.byteLength; - break; + const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } ); + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { - case 'CircleGeometry': - case 'CircleBufferGeometry': + const callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); - geometry = new Geometries[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + } - break; + controller.enqueue( value ); + readData(); - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + } ); - break; + } - case 'ConeGeometry': - case 'ConeBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + } ); - break; + return new Response( stream ); - case 'SphereGeometry': - case 'SphereBufferGeometry': + } else { - geometry = new Geometries[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response ); - break; + } - case 'DodecahedronGeometry': - case 'DodecahedronBufferGeometry': - case 'IcosahedronGeometry': - case 'IcosahedronBufferGeometry': - case 'OctahedronGeometry': - case 'OctahedronBufferGeometry': - case 'TetrahedronGeometry': - case 'TetrahedronBufferGeometry': + } ) + .then( response => { - geometry = new Geometries[ data.type ]( - data.radius, - data.detail - ); + switch ( responseType ) { - break; + case 'arraybuffer': - case 'RingGeometry': - case 'RingBufferGeometry': + return response.arrayBuffer(); - geometry = new Geometries[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + case 'blob': - break; + return response.blob(); - case 'TorusGeometry': - case 'TorusBufferGeometry': + case 'document': - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + return response.text() + .then( text => { - break; + const parser = new DOMParser(); + return parser.parseFromString( text, mimeType ); - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + } ); - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + case 'json': - break; + return response.json(); - case 'TubeGeometry': - case 'TubeBufferGeometry': + default: - // This only works for built-in curves (e.g. CatmullRomCurve3). - // User defined curves or instances of CurvePath will not be deserialized. - geometry = new Geometries[ data.type ]( - new Curves[ data.path.type ]().fromJSON( data.path ), - data.tubularSegments, - data.radius, - data.radialSegments, - data.closed - ); + if ( mimeType === undefined ) { - break; + return response.text(); - case 'LatheGeometry': - case 'LatheBufferGeometry': + } else { - geometry = new Geometries[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + // sniff encoding + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec( mimeType ); + const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined; + const decoder = new TextDecoder( label ); + return response.arrayBuffer().then( ab => decoder.decode( ab ) ); - break; + } - case 'PolyhedronGeometry': - case 'PolyhedronBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.vertices, - data.indices, - data.radius, - data.details - ); + } ) + .then( data => { - break; + // Add to cache only on HTTP success, so that we do not cache + // error response bodies as proper responses to requests. + Cache.add( url, data ); - case 'ShapeGeometry': - case 'ShapeBufferGeometry': + const callbacks = loading[ url ]; + delete loading[ url ]; - geometryShapes = []; + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { - for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + const callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( data ); - const shape = shapes[ data.shapes[ j ] ]; + } - geometryShapes.push( shape ); + } ) + .catch( err => { - } + // Abort errors and other errors are handled the same - geometry = new Geometries[ data.type ]( - geometryShapes, - data.curveSegments - ); + const callbacks = loading[ url ]; - break; + if ( callbacks === undefined ) { + // When onLoad was called and url was deleted in `loading` + this.manager.itemError( url ); + throw err; - case 'ExtrudeGeometry': - case 'ExtrudeBufferGeometry': + } - geometryShapes = []; + delete loading[ url ]; - for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { - const shape = shapes[ data.shapes[ j ] ]; + const callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( err ); - geometryShapes.push( shape ); + } - } + this.manager.itemError( url ); - const extrudePath = data.options.extrudePath; + } ) + .finally( () => { - if ( extrudePath !== undefined ) { + this.manager.itemEnd( url ); - data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + } ); - } + this.manager.itemStart( url ); - geometry = new Geometries[ data.type ]( - geometryShapes, - data.options - ); + } - break; + setResponseType( value ) { - case 'BufferGeometry': - case 'InstancedBufferGeometry': + this.responseType = value; + return this; - geometry = bufferGeometryLoader.parse( data ); + } - break; + setMimeType( value ) { - case 'Geometry': + this.mimeType = value; + return this; - console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' ); + } - break; +} - default: +class AnimationLoader extends Loader { - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + constructor( manager ) { - continue; + super( manager ); - } + } - geometry.uuid = data.uuid; + load( url, onLoad, onProgress, onError ) { - if ( data.name !== undefined ) geometry.name = data.name; - if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; + const scope = this; - geometries[ data.uuid ] = geometry; + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - } + try { - } + onLoad( scope.parse( JSON.parse( text ) ) ); - return geometries; + } catch ( e ) { - } + if ( onError ) { - parseMaterials( json, textures ) { + onError( e ); - const cache = {}; // MultiMaterial - const materials = {}; + } else { - if ( json !== undefined ) { + console.error( e ); - const loader = new MaterialLoader(); - loader.setTextures( textures ); + } - for ( let i = 0, l = json.length; i < l; i ++ ) { + scope.manager.itemError( url ); - const data = json[ i ]; + } - if ( data.type === 'MultiMaterial' ) { + }, onProgress, onError ); - // Deprecated + } - const array = []; + parse( json ) { - for ( let j = 0; j < data.materials.length; j ++ ) { + const animations = []; - const material = data.materials[ j ]; + for ( let i = 0; i < json.length; i ++ ) { - if ( cache[ material.uuid ] === undefined ) { + const clip = AnimationClip.parse( json[ i ] ); - cache[ material.uuid ] = loader.parse( material ); + animations.push( clip ); - } + } - array.push( cache[ material.uuid ] ); + return animations; - } + } - materials[ data.uuid ] = array; +} - } else { +/** + * Abstract Base class to block based textures loader (dds, pvr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ - if ( cache[ data.uuid ] === undefined ) { +class CompressedTextureLoader extends Loader { - cache[ data.uuid ] = loader.parse( data ); + constructor( manager ) { - } + super( manager ); - materials[ data.uuid ] = cache[ data.uuid ]; + } - } + load( url, onLoad, onProgress, onError ) { - } + const scope = this; - } + const images = []; - return materials; + const texture = new CompressedTexture(); - } + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); - parseAnimations( json ) { + let loaded = 0; - const animations = {}; + function loadTexture( i ) { - if ( json !== undefined ) { + loader.load( url[ i ], function ( buffer ) { - for ( let i = 0; i < json.length; i ++ ) { + const texDatas = scope.parse( buffer, true ); - const data = json[ i ]; + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; - const clip = AnimationClip.parse( data ); + loaded += 1; - animations[ clip.uuid ] = clip; + if ( loaded === 6 ) { - } + if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; - } + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; - return animations; + if ( onLoad ) onLoad( texture ); - } + } - parseImages( json, onLoad ) { + }, onProgress, onError ); - const scope = this; - const images = {}; + } - let loader; + if ( Array.isArray( url ) ) { - function loadImage( url ) { + for ( let i = 0, il = url.length; i < il; ++ i ) { - scope.manager.itemStart( url ); + loadTexture( i ); - return loader.load( url, function () { + } - scope.manager.itemEnd( url ); + } else { - }, undefined, function () { + // compressed cubemap texture stored in a single DDS file - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + loader.load( url, function ( buffer ) { - } ); + const texDatas = scope.parse( buffer, true ); - } + if ( texDatas.isCubemap ) { - function deserializeImage( image ) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; - if ( typeof image === 'string' ) { + for ( let f = 0; f < faces; f ++ ) { - const url = image; + images[ f ] = { mipmaps: [] }; - const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + for ( let i = 0; i < texDatas.mipmapCount; i ++ ) { - return loadImage( path ); + 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; - } else { + } - if ( image.data ) { + } - return { - data: getTypedArray( image.type, image.data ), - width: image.width, - height: image.height - }; + texture.image = images; } else { - return null; + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; } - } - - } - - if ( json !== undefined && json.length > 0 ) { - - const manager = new LoadingManager( onLoad ); - - loader = new ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + if ( texDatas.mipmapCount === 1 ) { - for ( let i = 0, il = json.length; i < il; i ++ ) { + texture.minFilter = LinearFilter; - const image = json[ i ]; - const url = image.url; + } - if ( Array.isArray( url ) ) { + texture.format = texDatas.format; + texture.needsUpdate = true; - // load array of images e.g CubeTexture + if ( onLoad ) onLoad( texture ); - images[ image.uuid ] = []; + }, onProgress, onError ); - for ( let j = 0, jl = url.length; j < jl; j ++ ) { + } - const currentUrl = url[ j ]; + return texture; - const deserializedImage = deserializeImage( currentUrl ); + } - if ( deserializedImage !== null ) { +} - if ( deserializedImage instanceof HTMLImageElement ) { +class ImageLoader extends Loader { - images[ image.uuid ].push( deserializedImage ); + constructor( manager ) { - } else { + super( manager ); - // special case: handle array of data textures for cube textures + } - images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + load( url, onLoad, onProgress, onError ) { - } + if ( this.path !== undefined ) url = this.path + url; - } + url = this.manager.resolveURL( url ); - } + const scope = this; - } else { + const cached = Cache.get( url ); - // load single image + if ( cached !== undefined ) { - const deserializedImage = deserializeImage( image.url ); + scope.manager.itemStart( url ); - if ( deserializedImage !== null ) { + setTimeout( function () { - images[ image.uuid ] = deserializedImage; + if ( onLoad ) onLoad( cached ); - } + scope.manager.itemEnd( url ); - } + }, 0 ); - } + return cached; } - return images; - - } + const image = createElementNS( 'img' ); - parseTextures( json, images ) { + function onImageLoad() { - function parseConstant( value, type ) { + removeEventListeners(); - if ( typeof value === 'number' ) return value; + Cache.add( url, this ); - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + if ( onLoad ) onLoad( this ); - return type[ value ]; + scope.manager.itemEnd( url ); } - const textures = {}; - - if ( json !== undefined ) { + function onImageError( event ) { - for ( let i = 0, l = json.length; i < l; i ++ ) { + removeEventListeners(); - const data = json[ i ]; + if ( onError ) onError( event ); - if ( data.image === undefined ) { + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + } - } + function removeEventListeners() { - if ( images[ data.image ] === undefined ) { + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + } - } + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); - let texture; - const image = images[ data.image ]; + if ( url.slice( 0, 5 ) !== 'data:' ) { - if ( Array.isArray( image ) ) { + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; - texture = new CubeTexture( image ); + } - if ( image.length === 6 ) texture.needsUpdate = true; + scope.manager.itemStart( url ); - } else { + image.src = url; - if ( image && image.data ) { + return image; - texture = new DataTexture( image.data, image.width, image.height ); + } - } else { +} - texture = new Texture( image ); +class CubeTextureLoader extends Loader { - } + constructor( manager ) { - if ( image ) texture.needsUpdate = true; // textures can have undefined image data + super( manager ); - } + } - texture.uuid = data.uuid; + load( urls, onLoad, onProgress, onError ) { - if ( data.name !== undefined ) texture.name = data.name; + const texture = new CubeTexture(); - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); - if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); - if ( data.center !== undefined ) texture.center.fromArray( data.center ); - if ( data.rotation !== undefined ) texture.rotation = data.rotation; + let loaded = 0; - if ( data.wrap !== undefined ) { + function loadTexture( i ) { - texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); - texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + loader.load( urls[ i ], function ( image ) { - } + texture.images[ i ] = image; - if ( data.format !== undefined ) texture.format = data.format; - if ( data.type !== undefined ) texture.type = data.type; - if ( data.encoding !== undefined ) texture.encoding = data.encoding; + loaded ++; - if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); - if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); - if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + if ( loaded === 6 ) { - if ( data.flipY !== undefined ) texture.flipY = data.flipY; + texture.needsUpdate = true; - if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; - if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; + if ( onLoad ) onLoad( texture ); - textures[ data.uuid ] = texture; + } - } + }, undefined, onError ); } - return textures; - - } + for ( let i = 0; i < urls.length; ++ i ) { - parseObject( data, geometries, materials, animations ) { + loadTexture( i ); - let object; + } - function getGeometry( name ) { + return texture; - if ( geometries[ name ] === undefined ) { + } - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); +} - } +/** + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ - return geometries[ name ]; +class DataTextureLoader extends Loader { - } + constructor( manager ) { - function getMaterial( name ) { + super( manager ); - if ( name === undefined ) return undefined; + } - if ( Array.isArray( name ) ) { + load( url, onLoad, onProgress, onError ) { - const array = []; + const scope = this; - for ( let i = 0, l = name.length; i < l; i ++ ) { + const texture = new DataTexture(); - const uuid = name[ i ]; + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setPath( this.path ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( buffer ) { - if ( materials[ uuid ] === undefined ) { + const texData = scope.parse( buffer ); - console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); + if ( ! texData ) return; - } + if ( texData.image !== undefined ) { - array.push( materials[ uuid ] ); + texture.image = texData.image; - } + } else if ( texData.data !== undefined ) { - return array; + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; } - if ( materials[ name ] === undefined ) { - - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; - } + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; - return materials[ name ]; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; - } + if ( texData.encoding !== undefined ) { - let geometry, material; + texture.encoding = texData.encoding; - switch ( data.type ) { + } - case 'Scene': + if ( texData.flipY !== undefined ) { - object = new Scene(); + texture.flipY = texData.flipY; - if ( data.background !== undefined ) { + } - if ( Number.isInteger( data.background ) ) { + if ( texData.format !== undefined ) { - object.background = new Color( data.background ); + texture.format = texData.format; - } + } - } + if ( texData.type !== undefined ) { - if ( data.fog !== undefined ) { + texture.type = texData.type; - if ( data.fog.type === 'Fog' ) { + } - object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + if ( texData.mipmaps !== undefined ) { - } else if ( data.fog.type === 'FogExp2' ) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; // presumably... - object.fog = new FogExp2( data.fog.color, data.fog.density ); + } - } + if ( texData.mipmapCount === 1 ) { - } + texture.minFilter = LinearFilter; - break; + } - case 'PerspectiveCamera': + if ( texData.generateMipmaps !== undefined ) { - object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + texture.generateMipmaps = texData.generateMipmaps; - 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 ); + } - break; + texture.needsUpdate = true; - case 'OrthographicCamera': + if ( onLoad ) onLoad( texture, texData ); - object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + }, onProgress, onError ); - if ( data.zoom !== undefined ) object.zoom = data.zoom; - if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - break; + return texture; - case 'AmbientLight': + } - object = new AmbientLight( data.color, data.intensity ); +} - break; +class TextureLoader extends Loader { - case 'DirectionalLight': + constructor( manager ) { - object = new DirectionalLight( data.color, data.intensity ); + super( manager ); - break; + } - case 'PointLight': + load( url, onLoad, onProgress, onError ) { - object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + const texture = new Texture(); - break; + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - case 'RectAreaLight': + loader.load( url, function ( image ) { - object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + texture.image = image; + texture.needsUpdate = true; - break; + if ( onLoad !== undefined ) { - case 'SpotLight': + onLoad( texture ); - object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + } - break; + }, onProgress, onError ); - case 'HemisphereLight': + return texture; - object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + } - break; +} - case 'LightProbe': +class Light extends Object3D { - object = new LightProbe().fromJSON( data ); + constructor( color, intensity = 1 ) { - break; + super(); - case 'SkinnedMesh': + this.isLight = true; - geometry = getGeometry( data.geometry ); - material = getMaterial( data.material ); + this.type = 'Light'; - object = new SkinnedMesh( geometry, material ); + this.color = new Color( color ); + this.intensity = intensity; - if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; - if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); - if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; + } - break; + dispose() { - case 'Mesh': + // Empty here in base class; some subclasses override. - geometry = getGeometry( data.geometry ); - material = getMaterial( data.material ); + } - object = new Mesh( geometry, material ); + copy( source, recursive ) { - break; + super.copy( source, recursive ); - case 'InstancedMesh': + this.color.copy( source.color ); + this.intensity = source.intensity; - geometry = getGeometry( data.geometry ); - material = getMaterial( data.material ); - const count = data.count; - const instanceMatrix = data.instanceMatrix; + return this; - object = new InstancedMesh( geometry, material, count ); - object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + } - break; + toJSON( meta ) { - case 'LOD': + const data = super.toJSON( meta ); - object = new LOD(); + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; - break; + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); - case 'Line': + 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; - object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); - break; + return data; - case 'LineLoop': + } - object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); +} - break; +class HemisphereLight extends Light { - case 'LineSegments': + constructor( skyColor, groundColor, intensity ) { - object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + super( skyColor, intensity ); - break; + this.isHemisphereLight = true; - case 'PointCloud': - case 'Points': + this.type = 'HemisphereLight'; - object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - break; + this.groundColor = new Color( groundColor ); - case 'Sprite': + } - object = new Sprite( getMaterial( data.material ) ); + copy( source, recursive ) { - break; + super.copy( source, recursive ); - case 'Group': + this.groundColor.copy( source.groundColor ); - object = new Group(); + return this; - break; + } - case 'Bone': +} - object = new Bone(); +const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); +const _lookTarget$1 = /*@__PURE__*/ new Vector3(); - break; +class LightShadow { - default: + constructor( camera ) { - object = new Object3D(); + this.camera = camera; - } + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; - object.uuid = data.uuid; + this.mapSize = new Vector2( 512, 512 ); - if ( data.name !== undefined ) object.name = data.name; + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); - if ( data.matrix !== undefined ) { + this.autoUpdate = true; + this.needsUpdate = false; - object.matrix.fromArray( data.matrix ); + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); - if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; - if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale ); + this._viewportCount = 1; - } else { + this._viewports = [ - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + new Vector4( 0, 0, 1, 1 ) - } + ]; - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + } - if ( data.shadow ) { + getViewportCount() { - if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; - if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; - if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; - if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); - if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); + return this._viewportCount; - } + } - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; - if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; - if ( data.userData !== undefined ) object.userData = data.userData; - if ( data.layers !== undefined ) object.layers.mask = data.layers; + getFrustum() { - if ( data.children !== undefined ) { + return this._frustum; - const children = data.children; + } - for ( let i = 0; i < children.length; i ++ ) { + updateMatrices( light ) { - object.add( this.parseObject( children[ i ], geometries, materials, animations ) ); + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; - } + _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld$1 ); - } + _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget$1 ); + shadowCamera.updateMatrixWorld(); - if ( data.animations !== undefined ) { + _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); - const objectAnimations = data.animations; + 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 + ); - for ( let i = 0; i < objectAnimations.length; i ++ ) { + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - const uuid = objectAnimations[ i ]; + } - object.animations.push( animations[ uuid ] ); + getViewport( viewportIndex ) { - } + return this._viewports[ viewportIndex ]; - } + } - if ( data.type === 'LOD' ) { + getFrameExtents() { - if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; + return this._frameExtents; - const levels = data.levels; + } - for ( let l = 0; l < levels.length; l ++ ) { + dispose() { - const level = levels[ l ]; - const child = object.getObjectByProperty( 'uuid', level.object ); + if ( this.map ) { - if ( child !== undefined ) { + this.map.dispose(); - object.addLevel( child, level.distance ); + } - } + if ( this.mapPass ) { - } + this.mapPass.dispose(); } - return object; - } - bindSkeletons( object, skeletons ) { - - if ( Object.keys( skeletons ).length === 0 ) return; - - object.traverse( function ( child ) { + copy( source ) { - if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { + this.camera = source.camera.clone(); - const skeleton = skeletons[ child.skeleton ]; + this.bias = source.bias; + this.radius = source.radius; - if ( skeleton === undefined ) { + this.mapSize.copy( source.mapSize ); - console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton ); + return this; - } else { + } - child.bind( skeleton, child.bindMatrix ); + clone() { - } + return new this.constructor().copy( this ); - } + } - } ); + toJSON() { - } + const object = {}; - /* DEPRECATED */ + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); - setTexturePath( value ) { + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; - console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' ); - return this.setResourcePath( value ); + return object; } } -const TEXTURE_MAPPING = { - UVMapping: UVMapping, - CubeReflectionMapping: CubeReflectionMapping, - CubeRefractionMapping: CubeRefractionMapping, - EquirectangularReflectionMapping: EquirectangularReflectionMapping, - EquirectangularRefractionMapping: EquirectangularRefractionMapping, - CubeUVReflectionMapping: CubeUVReflectionMapping, - CubeUVRefractionMapping: CubeUVRefractionMapping -}; - -const TEXTURE_WRAPPING = { - RepeatWrapping: RepeatWrapping, - ClampToEdgeWrapping: ClampToEdgeWrapping, - MirroredRepeatWrapping: MirroredRepeatWrapping -}; - -const TEXTURE_FILTER = { - NearestFilter: NearestFilter, - NearestMipmapNearestFilter: NearestMipmapNearestFilter, - NearestMipmapLinearFilter: NearestMipmapLinearFilter, - LinearFilter: LinearFilter, - LinearMipmapNearestFilter: LinearMipmapNearestFilter, - LinearMipmapLinearFilter: LinearMipmapLinearFilter -}; - -function ImageBitmapLoader( manager ) { +class SpotLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - if ( typeof createImageBitmap === 'undefined' ) { + this.isSpotLightShadow = true; - console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); + this.focus = 1; } - if ( typeof fetch === 'undefined' ) { + updateMatrices( light ) { - console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); + const camera = this.camera; - } + const fov = RAD2DEG * 2 * light.angle * this.focus; + const aspect = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; - Loader.call( this, manager ); + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { - this.options = { premultiplyAlpha: 'none' }; + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); -} + } -ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + super.updateMatrices( light ); - constructor: ImageBitmapLoader, + } - isImageBitmapLoader: true, + copy( source ) { - setOptions: function setOptions( options ) { + super.copy( source ); - this.options = options; + this.focus = source.focus; return this; - }, - - load: function ( url, onLoad, onProgress, onError ) { + } - if ( url === undefined ) url = ''; +} - if ( this.path !== undefined ) url = this.path + url; +class SpotLight extends Light { - url = this.manager.resolveURL( url ); + constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) { - const scope = this; + super( color, intensity ); - const cached = Cache.get( url ); + this.isSpotLight = true; - if ( cached !== undefined ) { + this.type = 'SpotLight'; - scope.manager.itemStart( url ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - setTimeout( function () { + this.target = new Object3D(); - if ( onLoad ) onLoad( cached ); + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; // for physically correct lights, should be 2. - scope.manager.itemEnd( url ); + this.map = null; - }, 0 ); + this.shadow = new SpotLightShadow(); - return cached; + } - } + get power() { - const fetchOptions = {}; - fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; - fetchOptions.headers = this.requestHeader; + // compute the light's luminous power (in lumens) from its intensity (in candela) + // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd) + return this.intensity * Math.PI; - fetch( url, fetchOptions ).then( function ( res ) { + } - return res.blob(); + set power( power ) { - } ).then( function ( blob ) { + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / Math.PI; - return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) ); + } - } ).then( function ( imageBitmap ) { + dispose() { - Cache.add( url, imageBitmap ); + this.shadow.dispose(); - if ( onLoad ) onLoad( imageBitmap ); + } - scope.manager.itemEnd( url ); + copy( source, recursive ) { - } ).catch( function ( e ) { + super.copy( source, recursive ); - if ( onError ) onError( e ); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + this.target = source.target.clone(); - } ); + this.shadow = source.shadow.clone(); - scope.manager.itemStart( url ); + return this; } -} ); +} -class ShapePath { +const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld = /*@__PURE__*/ new Vector3(); +const _lookTarget = /*@__PURE__*/ new Vector3(); + +class PointLightShadow extends LightShadow { constructor() { - this.type = 'ShapePath'; + super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); - this.color = new Color(); + this.isPointLightShadow = true; - this.subPaths = []; - this.currentPath = null; + this._frameExtents = new Vector2( 4, 2 ); - } + this._viewportCount = 6; - moveTo( x, y ) { + this._viewports = [ + // 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.currentPath = new Path(); - this.subPaths.push( this.currentPath ); - this.currentPath.moveTo( x, y ); + // positive X + new Vector4( 2, 1, 1, 1 ), + // negative X + new Vector4( 0, 1, 1, 1 ), + // positive Z + new Vector4( 3, 1, 1, 1 ), + // negative Z + new Vector4( 1, 1, 1, 1 ), + // positive Y + new Vector4( 3, 0, 1, 1 ), + // negative Y + new Vector4( 1, 0, 1, 1 ) + ]; - return this; + this._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 ) + ]; - } + this._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 ) + ]; - lineTo( x, y ) { + } - this.currentPath.lineTo( x, y ); + updateMatrices( light, viewportIndex = 0 ) { - return this; + const camera = this.camera; + const shadowMatrix = this.matrix; - } + const far = light.distance || camera.far; - quadraticCurveTo( aCPx, aCPy, aX, aY ) { + if ( far !== camera.far ) { - this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + camera.far = far; + camera.updateProjectionMatrix(); - return this; + } - } + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + camera.position.copy( _lightPositionWorld ); - bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + _lookTarget.copy( camera.position ); + _lookTarget.add( this._cubeDirections[ viewportIndex ] ); + camera.up.copy( this._cubeUps[ viewportIndex ] ); + camera.lookAt( _lookTarget ); + camera.updateMatrixWorld(); - this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); - return this; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix ); } - splineThru( pts ) { - - this.currentPath.splineThru( pts ); +} - return this; +class PointLight extends Light { - } + constructor( color, intensity, distance = 0, decay = 1 ) { - toShapes( isCCW, noHoles ) { + super( color, intensity ); - function toShapesNoHoles( inSubpaths ) { + this.isPointLight = true; - const shapes = []; + this.type = 'PointLight'; - for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { + this.distance = distance; + this.decay = decay; // for physically correct lights, should be 2. - const tmpPath = inSubpaths[ i ]; + this.shadow = new PointLightShadow(); - const tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; + } - shapes.push( tmpShape ); + get power() { - } + // compute the light's luminous power (in lumens) from its intensity (in candela) + // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd) + return this.intensity * 4 * Math.PI; - return shapes; + } - } + set power( power ) { - function isPointInsidePolygon( inPt, inPolygon ) { + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / ( 4 * Math.PI ); - const 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 - let inside = false; - for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + dispose() { - let edgeLowPt = inPolygon[ p ]; - let edgeHighPt = inPolygon[ q ]; + this.shadow.dispose(); - let edgeDx = edgeHighPt.x - edgeLowPt.x; - let edgeDy = edgeHighPt.y - edgeLowPt.y; + } - if ( Math.abs( edgeDy ) > Number.EPSILON ) { + copy( source, recursive ) { - // not parallel - if ( edgeDy < 0 ) { + super.copy( source, recursive ); - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + this.distance = source.distance; + this.decay = source.decay; - } + this.shadow = source.shadow.clone(); - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + return this; - if ( inPt.y === edgeLowPt.y ) { + } - if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! +} - } else { +class DirectionalLightShadow extends LightShadow { - const 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 + constructor() { - } + super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); - } else { + this.isDirectionalLightShadow = true; - // 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; + } - } +} - } +class DirectionalLight extends Light { - return inside; + constructor( color, intensity ) { - } + super( color, intensity ); - const isClockWise = ShapeUtils.isClockWise; + this.isDirectionalLight = true; - const subPaths = this.subPaths; - if ( subPaths.length === 0 ) return []; + this.type = 'DirectionalLight'; - if ( noHoles === true ) return toShapesNoHoles( subPaths ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); + this.target = new Object3D(); - let solid, tmpPath, tmpShape; - const shapes = []; + this.shadow = new DirectionalLightShadow(); - if ( subPaths.length === 1 ) { + } - tmpPath = subPaths[ 0 ]; - tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + dispose() { - } + this.shadow.dispose(); - let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + } - // console.log("Holes first", holesFirst); + copy( source ) { - const betterShapeHoles = []; - const newShapes = []; - let newShapeHoles = []; - let mainIdx = 0; - let tmpPoints; + super.copy( source ); - newShapes[ mainIdx ] = undefined; - newShapeHoles[ mainIdx ] = []; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); - for ( let i = 0, l = subPaths.length; i < l; i ++ ) { + return this; - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + } - if ( solid ) { +} - if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; +class AmbientLight extends Light { - newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; - newShapes[ mainIdx ].s.curves = tmpPath.curves; + constructor( color, intensity ) { - if ( holesFirst ) mainIdx ++; - newShapeHoles[ mainIdx ] = []; + super( color, intensity ); - //console.log('cw', i); + this.isAmbientLight = true; - } else { + this.type = 'AmbientLight'; - newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + } - //console.log('ccw', i); +} - } +class RectAreaLight extends Light { - } + constructor( color, intensity, width = 10, height = 10 ) { - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + super( color, intensity ); + this.isRectAreaLight = true; - if ( newShapes.length > 1 ) { + this.type = 'RectAreaLight'; - let ambiguous = false; - const toChange = []; + this.width = width; + this.height = height; - for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + } - betterShapeHoles[ sIdx ] = []; + get power() { - } + // compute the light's luminous power (in lumens) from its intensity (in nits) + return this.intensity * this.width * this.height * Math.PI; - for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + } - const sho = newShapeHoles[ sIdx ]; + set power( power ) { - for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { + // set the light's intensity (in nits) from the desired luminous power (in lumens) + this.intensity = power / ( this.width * this.height * Math.PI ); - const ho = sho[ hIdx ]; - let hole_unassigned = true; + } - for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + copy( source ) { - if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + super.copy( source ); - if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { + this.width = source.width; + this.height = source.height; - hole_unassigned = false; - betterShapeHoles[ s2Idx ].push( ho ); + return this; - } else { + } - ambiguous = true; + toJSON( meta ) { - } + const data = super.toJSON( meta ); - } + data.object.width = this.width; + data.object.height = this.height; - } + return data; - if ( hole_unassigned ) { + } - betterShapeHoles[ sIdx ].push( ho ); +} - } +/** + * Primary reference: + * https://graphics.stanford.edu/papers/envmap/envmap.pdf + * + * Secondary reference: + * https://www.ppsloan.org/publications/StupidSH36.pdf + */ - } +// 3-band SH defined by 9 coefficients - } - // console.log("ambiguous: ", ambiguous); +class SphericalHarmonics3 { - if ( toChange.length > 0 ) { + constructor() { - // console.log("to change: ", toChange); - if ( ! ambiguous ) newShapeHoles = betterShapeHoles; + this.isSphericalHarmonics3 = true; - } + this.coefficients = []; - } + for ( let i = 0; i < 9; i ++ ) { - let tmpHoles; + this.coefficients.push( new Vector3() ); - for ( let i = 0, il = newShapes.length; i < il; i ++ ) { + } - tmpShape = newShapes[ i ].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[ i ]; + } - for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + set( coefficients ) { - tmpShape.holes.push( tmpHoles[ j ].h ); + for ( let i = 0; i < 9; i ++ ) { - } + this.coefficients[ i ].copy( coefficients[ i ] ); } - //console.log("shape", shapes); - - return shapes; + return this; } -} + zero() { -class Font { + for ( let i = 0; i < 9; i ++ ) { - constructor( data ) { + this.coefficients[ i ].set( 0, 0, 0 ); - this.type = 'Font'; + } - this.data = data; + return this; } - generateShapes( text, size = 100 ) { + // get the radiance in the direction of the normal + // target is a Vector3 + getAt( normal, target ) { - const shapes = []; - const paths = createPaths( text, size, this.data ); + // normal is assumed to be unit length - for ( let p = 0, pl = paths.length; p < pl; p ++ ) { + const x = normal.x, y = normal.y, z = normal.z; - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + const coeff = this.coefficients; - } + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); - return shapes; + // band 1 + target.addScaledVector( coeff[ 1 ], 0.488603 * y ); + target.addScaledVector( coeff[ 2 ], 0.488603 * z ); + target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); + target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); + target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); + target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); + target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + + return target; } -} + // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal + // target is a Vector3 + // https://graphics.stanford.edu/papers/envmap/envmap.pdf + getIrradianceAt( normal, target ) { + + // normal is assumed to be unit length -function createPaths( text, size, data ) { + const x = normal.x, y = normal.y, z = normal.z; - const chars = Array.from( text ); - const scale = size / data.resolution; - const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; + const coeff = this.coefficients; - const paths = []; + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 - let offsetX = 0, offsetY = 0; + // band 1 + target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 + target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); + target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); - for ( let i = 0; i < chars.length; i ++ ) { + // band 2 + target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 + target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); + target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 + target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); + target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 - const char = chars[ i ]; + return target; - if ( char === '\n' ) { + } - offsetX = 0; - offsetY -= line_height; + add( sh ) { - } else { + for ( let i = 0; i < 9; i ++ ) { - const ret = createPath( char, scale, offsetX, offsetY, data ); - offsetX += ret.offsetX; - paths.push( ret.path ); + this.coefficients[ i ].add( sh.coefficients[ i ] ); } + return this; + } - return paths; + addScaledSH( sh, s ) { + + for ( let i = 0; i < 9; i ++ ) { -} + this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); -function createPath( char, scale, offsetX, offsetY, data ) { + } + + return this; - const glyph = data.glyphs[ char ] || data.glyphs[ '?' ]; + } - if ( ! glyph ) { + scale( s ) { - console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' ); + for ( let i = 0; i < 9; i ++ ) { - return; + this.coefficients[ i ].multiplyScalar( s ); + + } + + return this; } - const path = new ShapePath(); + lerp( sh, alpha ) { - let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; + for ( let i = 0; i < 9; i ++ ) { - if ( glyph.o ) { + this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); - const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + } - for ( let i = 0, l = outline.length; i < l; ) { + return this; - const action = outline[ i ++ ]; + } - switch ( action ) { + equals( sh ) { - case 'm': // moveTo + for ( let i = 0; i < 9; i ++ ) { - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { - path.moveTo( x, y ); + return false; - break; + } - case 'l': // lineTo + } - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + return true; - path.lineTo( x, y ); + } - break; + copy( sh ) { - case 'q': // quadraticCurveTo + return this.set( sh.coefficients ); - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; + } - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + clone() { - break; + return new this.constructor().copy( this ); - case 'b': // bezierCurveTo + } - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; - cpx2 = outline[ i ++ ] * scale + offsetX; - cpy2 = outline[ i ++ ] * scale + offsetY; + fromArray( array, offset = 0 ) { - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + const coefficients = this.coefficients; - break; + for ( let i = 0; i < 9; i ++ ) { - } + coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); } + return this; + } - return { offsetX: glyph.ha * scale, path: path }; + toArray( array = [], offset = 0 ) { -} + const coefficients = this.coefficients; -Font.prototype.isFont = true; + for ( let i = 0; i < 9; i ++ ) { -class FontLoader extends Loader { + coefficients[ i ].toArray( array, offset + ( i * 3 ) ); - constructor( manager ) { + } - super( manager ); + return array; } - load( url, onLoad, onProgress, onError ) { + // evaluate the basis functions + // shBasis is an Array[ 9 ] + static getBasisAt( normal, shBasis ) { - const scope = this; + // normal is assumed to be unit length - const loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( scope.withCredentials ); - loader.load( url, function ( text ) { + const x = normal.x, y = normal.y, z = normal.z; - let json; + // band 0 + shBasis[ 0 ] = 0.282095; - try { + // band 1 + shBasis[ 1 ] = 0.488603 * y; + shBasis[ 2 ] = 0.488603 * z; + shBasis[ 3 ] = 0.488603 * x; - json = JSON.parse( text ); + // band 2 + shBasis[ 4 ] = 1.092548 * x * y; + shBasis[ 5 ] = 1.092548 * y * z; + shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); + shBasis[ 7 ] = 1.092548 * x * z; + shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); - } catch ( e ) { + } - console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); - json = JSON.parse( text.substring( 65, text.length - 2 ) ); +} - } +class LightProbe extends Light { - const font = scope.parse( json ); + constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { - if ( onLoad ) onLoad( font ); + super( undefined, intensity ); - }, onProgress, onError ); + this.isLightProbe = true; - } + this.sh = sh; - parse( json ) { + } - return new Font( json ); + copy( source ) { - } + super.copy( source ); -} + this.sh.copy( source.sh ); -let _context; + return this; -const AudioContext = { + } - getContext: function () { + fromJSON( json ) { - if ( _context === undefined ) { + this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); + this.sh.fromArray( json.sh ); - _context = new ( window.AudioContext || window.webkitAudioContext )(); + return this; - } + } - return _context; + toJSON( meta ) { - }, + const data = super.toJSON( meta ); - setContext: function ( value ) { + data.object.sh = this.sh.toArray(); - _context = value; + return data; } -}; +} -class AudioLoader extends Loader { +class MaterialLoader extends Loader { constructor( manager ) { super( manager ); + this.textures = {}; } @@ -40248,25 +41358,15 @@ class AudioLoader extends Loader { const scope = this; - const loader = new FileLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.setPath( this.path ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( buffer ) { + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { try { - // Create a copy of the buffer. The `decodeAudioData` method - // detaches the buffer when complete, preventing reuse. - const bufferCopy = buffer.slice( 0 ); - - const context = AudioContext.getContext(); - context.decodeAudioData( bufferCopy, function ( audioBuffer ) { - - onLoad( audioBuffer ); - - } ); + onLoad( scope.parse( JSON.parse( text ) ) ); } catch ( e ) { @@ -40288,2352 +41388,2300 @@ class AudioLoader extends Loader { } -} + parse( json ) { -class HemisphereLightProbe extends LightProbe { + const textures = this.textures; - constructor( skyColor, groundColor, intensity = 1 ) { + function getTexture( name ) { - super( undefined, intensity ); + if ( textures[ name ] === undefined ) { - const color1 = new Color().set( skyColor ); - const color2 = new Color().set( groundColor ); + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - const sky = new Vector3( color1.r, color1.g, color1.b ); - const ground = new Vector3( color2.r, color2.g, color2.b ); + } - // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); - const c0 = Math.sqrt( Math.PI ); - const c1 = c0 * Math.sqrt( 0.75 ); + return textures[ name ]; - this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); - this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); + } - } + const material = MaterialLoader.createMaterialFromType( json.type ); -} + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined && material.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.sheen !== undefined ) material.sheen = json.sheen; + if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor ); + if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness; + if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity; + if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; + if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.iridescence !== undefined ) material.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if ( json.transmission !== undefined ) material.transmission = json.transmission; + if ( json.thickness !== undefined ) material.thickness = json.thickness; + if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance; + if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor ); + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.combine !== undefined ) material.combine = json.combine; + if ( json.side !== undefined ) material.side = json.side; + if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide; + 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; -HemisphereLightProbe.prototype.isHemisphereLightProbe = true; + if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; + if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; + if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; + if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; + if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; + if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; + if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; + if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; -class AmbientLightProbe extends LightProbe { + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; - constructor( color, intensity = 1 ) { + if ( json.rotation !== undefined ) material.rotation = json.rotation; - super( undefined, intensity ); + if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; + if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; + if ( json.scale !== undefined ) material.scale = json.scale; - const color1 = new Color().set( color ); + if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; - // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); - this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); + if ( json.dithering !== undefined ) material.dithering = json.dithering; - } + if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage; + if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha; -} + if ( json.visible !== undefined ) material.visible = json.visible; -AmbientLightProbe.prototype.isAmbientLightProbe = true; + if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; -const _eyeRight = new Matrix4(); -const _eyeLeft = new Matrix4(); + if ( json.userData !== undefined ) material.userData = json.userData; -class StereoCamera { + if ( json.vertexColors !== undefined ) { - constructor() { + if ( typeof json.vertexColors === 'number' ) { - this.type = 'StereoCamera'; + material.vertexColors = ( json.vertexColors > 0 ) ? true : false; - this.aspect = 1; + } else { - this.eyeSep = 0.064; + material.vertexColors = json.vertexColors; - this.cameraL = new PerspectiveCamera(); - this.cameraL.layers.enable( 1 ); - this.cameraL.matrixAutoUpdate = false; + } - this.cameraR = new PerspectiveCamera(); - this.cameraR.layers.enable( 2 ); - this.cameraR.matrixAutoUpdate = false; + } - this._cache = { - focus: null, - fov: null, - aspect: null, - near: null, - far: null, - zoom: null, - eyeSep: null - }; + // Shader Material - } + if ( json.uniforms !== undefined ) { - update( camera ) { + for ( const name in json.uniforms ) { - const cache = this._cache; + const uniform = json.uniforms[ name ]; - const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || - cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || - cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + material.uniforms[ name ] = {}; - if ( needsUpdate ) { + switch ( uniform.type ) { - cache.focus = camera.focus; - cache.fov = camera.fov; - cache.aspect = camera.aspect * this.aspect; - cache.near = camera.near; - cache.far = camera.far; - cache.zoom = camera.zoom; - cache.eyeSep = this.eyeSep; + case 't': + material.uniforms[ name ].value = getTexture( uniform.value ); + break; - // Off-axis stereoscopic effect based on - // http://paulbourke.net/stereographics/stereorender/ + case 'c': + material.uniforms[ name ].value = new Color().setHex( uniform.value ); + break; - const projectionMatrix = camera.projectionMatrix.clone(); - const eyeSepHalf = cache.eyeSep / 2; - const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; - const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; - let xmin, xmax; + case 'v2': + material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); + break; - // translate xOffset + case 'v3': + material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); + break; - _eyeLeft.elements[ 12 ] = - eyeSepHalf; - _eyeRight.elements[ 12 ] = eyeSepHalf; + case 'v4': + material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); + break; - // for left eye + case 'm3': + material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); + break; - xmin = - ymax * cache.aspect + eyeSepOnProjection; - xmax = ymax * cache.aspect + eyeSepOnProjection; + case 'm4': + material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); + break; - projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + default: + material.uniforms[ name ].value = uniform.value; - this.cameraL.projectionMatrix.copy( projectionMatrix ); + } - // for right eye + } - xmin = - ymax * cache.aspect - eyeSepOnProjection; - xmax = ymax * cache.aspect - eyeSepOnProjection; + } - projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + if ( json.defines !== undefined ) material.defines = json.defines; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion; - this.cameraR.projectionMatrix.copy( projectionMatrix ); + if ( json.extensions !== undefined ) { - } + for ( const key in json.extensions ) { - this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); - this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); + material.extensions[ key ] = json.extensions[ key ]; - } + } -} + } -class Clock { + // for PointsMaterial - constructor( autoStart ) { + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + // maps - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + if ( json.map !== undefined ) material.map = getTexture( json.map ); + if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); - this.running = false; + if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); - } + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - start() { + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; + if ( json.normalScale !== undefined ) { - this.startTime = now(); + let normalScale = json.normalScale; - this.oldTime = this.startTime; - this.elapsedTime = 0; - this.running = true; + if ( Array.isArray( normalScale ) === false ) { - } + // Blender exporter used to export a scalar. See #7459 - stop() { + normalScale = [ normalScale, normalScale ]; - this.getElapsedTime(); - this.running = false; - this.autoStart = false; + } - } + material.normalScale = new Vector2().fromArray( normalScale ); - getElapsedTime() { + } - this.getDelta(); - return this.elapsedTime; + if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); + if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; - } + if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); - getDelta() { + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - let diff = 0; + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap ); + if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); - if ( this.autoStart && ! this.running ) { + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; - this.start(); - return 0; + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; - } + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; - if ( this.running ) { + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - const newTime = now(); + if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; + if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); + if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); + if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); + if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); - this.elapsedTime += diff; + if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap ); + if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap ); - } + if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); + if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap ); - return diff; + if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap ); + if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap ); + + return material; } -} + setTextures( value ) { -function now() { + this.textures = value; + return this; - return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 + } -} + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; -const _position$2 = /*@__PURE__*/ new Vector3(); -const _quaternion$3 = /*@__PURE__*/ new Quaternion(); -const _scale$1 = /*@__PURE__*/ new Vector3(); -const _orientation = /*@__PURE__*/ new Vector3(); + return new materialLib[ type ](); -class AudioListener extends Object3D { + } - constructor() { +} - super(); +class LoaderUtils { - this.type = 'AudioListener'; + static decodeText( array ) { - this.context = AudioContext.getContext(); + if ( typeof TextDecoder !== 'undefined' ) { - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + return new TextDecoder().decode( array ); - this.filter = null; + } - this.timeDelta = 0; + // Avoid the String.fromCharCode.apply(null, array) shortcut, which + // throws a "maximum call stack size exceeded" error for large arrays. - // private + let s = ''; - this._clock = new Clock(); + for ( let i = 0, il = array.length; i < il; i ++ ) { - } + // Implicitly assumes little-endian. + s += String.fromCharCode( array[ i ] ); - getInput() { + } - return this.gain; + try { - } + // merges multi-byte utf-8 characters. - removeFilter() { + return decodeURIComponent( escape( s ) ); - if ( this.filter !== null ) { + } catch ( e ) { // see #16358 - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); - this.gain.connect( this.context.destination ); - this.filter = null; + return s; } - return this; - } - getFilter() { + static extractUrlBase( url ) { - return this.filter; + const index = url.lastIndexOf( '/' ); - } + if ( index === - 1 ) return './'; - setFilter( value ) { + return url.slice( 0, index + 1 ); - if ( this.filter !== null ) { + } - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); + static resolveURL( url, path ) { - } else { + // Invalid URL + if ( typeof url !== 'string' || url === '' ) return ''; - this.gain.disconnect( this.context.destination ); + // Host Relative URL + if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { + + path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); } - this.filter = value; - this.gain.connect( this.filter ); - this.filter.connect( this.context.destination ); + // Absolute URL http://,https://,// + if ( /^(https?:)?\/\//i.test( url ) ) return url; - return this; + // Data URI + if ( /^data:.*,.*$/i.test( url ) ) return url; + + // Blob URL + if ( /^blob:.*$/i.test( url ) ) return url; + + // Relative URL + return path + url; } - getMasterVolume() { +} - return this.gain.gain.value; +class InstancedBufferGeometry extends BufferGeometry { - } + constructor() { - setMasterVolume( value ) { + super(); - this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + this.isInstancedBufferGeometry = true; - return this; + this.type = 'InstancedBufferGeometry'; + this.instanceCount = Infinity; } - updateMatrixWorld( force ) { + copy( source ) { - super.updateMatrixWorld( force ); + super.copy( source ); - const listener = this.context.listener; - const up = this.up; + this.instanceCount = source.instanceCount; - this.timeDelta = this._clock.getDelta(); + return this; - this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 ); + } - _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 ); + clone() { - if ( listener.positionX ) { + return new this.constructor().copy( this ); - // code path for Chrome (see #14393) + } - const endTime = this.context.currentTime + this.timeDelta; + toJSON() { - listener.positionX.linearRampToValueAtTime( _position$2.x, endTime ); - listener.positionY.linearRampToValueAtTime( _position$2.y, endTime ); - listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime ); - listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime ); - listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime ); - listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime ); - listener.upX.linearRampToValueAtTime( up.x, endTime ); - listener.upY.linearRampToValueAtTime( up.y, endTime ); - listener.upZ.linearRampToValueAtTime( up.z, endTime ); + const data = super.toJSON( this ); - } else { + data.instanceCount = this.instanceCount; - listener.setPosition( _position$2.x, _position$2.y, _position$2.z ); - listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z ); + data.isInstancedBufferGeometry = true; - } + return data; } } -class Audio extends Object3D { - - constructor( listener ) { - - super(); - - this.type = 'Audio'; +class BufferGeometryLoader extends Loader { - this.listener = listener; - this.context = listener.context; + constructor( manager ) { - this.gain = this.context.createGain(); - this.gain.connect( listener.getInput() ); + super( manager ); - this.autoplay = false; + } - this.buffer = null; - this.detune = 0; - this.loop = false; - this.loopStart = 0; - this.loopEnd = 0; - this.offset = 0; - this.duration = undefined; - this.playbackRate = 1; - this.isPlaying = false; - this.hasPlaybackControl = true; - this.source = null; - this.sourceType = 'empty'; + load( url, onLoad, onProgress, onError ) { - this._startedAt = 0; - this._progress = 0; - this._connected = false; + const scope = this; - this.filters = []; + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { - } + try { - getOutput() { + onLoad( scope.parse( JSON.parse( text ) ) ); - return this.gain; + } catch ( e ) { - } + if ( onError ) { - setNodeSource( audioNode ) { + onError( e ); - this.hasPlaybackControl = false; - this.sourceType = 'audioNode'; - this.source = audioNode; - this.connect(); + } else { - return this; + console.error( e ); - } + } - setMediaElementSource( mediaElement ) { + scope.manager.itemError( url ); - this.hasPlaybackControl = false; - this.sourceType = 'mediaNode'; - this.source = this.context.createMediaElementSource( mediaElement ); - this.connect(); + } - return this; + }, onProgress, onError ); } - setMediaStreamSource( mediaStream ) { + parse( json ) { - this.hasPlaybackControl = false; - this.sourceType = 'mediaStreamNode'; - this.source = this.context.createMediaStreamSource( mediaStream ); - this.connect(); + const interleavedBufferMap = {}; + const arrayBufferMap = {}; - return this; + function getInterleavedBuffer( json, uuid ) { - } + if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; - setBuffer( audioBuffer ) { + const interleavedBuffers = json.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[ uuid ]; - this.buffer = audioBuffer; - this.sourceType = 'buffer'; + const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); - if ( this.autoplay ) this.play(); + const array = getTypedArray( interleavedBuffer.type, buffer ); + const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); + ib.uuid = interleavedBuffer.uuid; - return this; + interleavedBufferMap[ uuid ] = ib; - } + return ib; - play( delay = 0 ) { + } - if ( this.isPlaying === true ) { + function getArrayBuffer( json, uuid ) { - console.warn( 'THREE.Audio: Audio is already playing.' ); - return; + if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; - } + const arrayBuffers = json.arrayBuffers; + const arrayBuffer = arrayBuffers[ uuid ]; - if ( this.hasPlaybackControl === false ) { + const ab = new Uint32Array( arrayBuffer ).buffer; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + arrayBufferMap[ uuid ] = ab; - } + return ab; - this._startedAt = this.context.currentTime + delay; + } - const source = this.context.createBufferSource(); - source.buffer = this.buffer; - source.loop = this.loop; - source.loopStart = this.loopStart; - source.loopEnd = this.loopEnd; - source.onended = this.onEnded.bind( this ); - source.start( this._startedAt, this._progress + this.offset, this.duration ); + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); - this.isPlaying = true; + const index = json.data.index; - this.source = source; + if ( index !== undefined ) { - this.setDetune( this.detune ); - this.setPlaybackRate( this.playbackRate ); + const typedArray = getTypedArray( index.type, index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); - return this.connect(); + } - } + const attributes = json.data.attributes; - pause() { + for ( const key in attributes ) { - if ( this.hasPlaybackControl === false ) { + const attribute = attributes[ key ]; + let bufferAttribute; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + if ( attribute.isInterleavedBufferAttribute ) { - } + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); - if ( this.isPlaying === true ) { + } else { - // update current progress + const typedArray = getTypedArray( attribute.type, attribute.array ); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); - this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; + } - if ( this.loop === true ) { + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage ); - // ensure _progress does not exceed duration with looped audios + if ( attribute.updateRange !== undefined ) { - this._progress = this._progress % ( this.duration || this.buffer.duration ); + bufferAttribute.updateRange.offset = attribute.updateRange.offset; + bufferAttribute.updateRange.count = attribute.updateRange.count; } - this.source.stop(); - this.source.onended = null; - - this.isPlaying = false; + geometry.setAttribute( key, bufferAttribute ); } - return this; + const morphAttributes = json.data.morphAttributes; - } + if ( morphAttributes ) { - stop() { + for ( const key in morphAttributes ) { - if ( this.hasPlaybackControl === false ) { + const attributeArray = morphAttributes[ key ]; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + const array = []; - } + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { - this._progress = 0; + const attribute = attributeArray[ i ]; + let bufferAttribute; - this.source.stop(); - this.source.onended = null; - this.isPlaying = false; + if ( attribute.isInterleavedBufferAttribute ) { - return this; + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); - } + } else { - connect() { + const typedArray = getTypedArray( attribute.type, attribute.array ); + bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); - if ( this.filters.length > 0 ) { + } - this.source.connect( this.filters[ 0 ] ); + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + array.push( bufferAttribute ); - for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + } - this.filters[ i - 1 ].connect( this.filters[ i ] ); + geometry.morphAttributes[ key ] = array; } - this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + } - } else { + const morphTargetsRelative = json.data.morphTargetsRelative; - this.source.connect( this.getOutput() ); + if ( morphTargetsRelative ) { - } + geometry.morphTargetsRelative = true; - this._connected = true; + } - return this; + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; - } + if ( groups !== undefined ) { - disconnect() { + for ( let i = 0, n = groups.length; i !== n; ++ i ) { - if ( this.filters.length > 0 ) { + const group = groups[ i ]; - this.source.disconnect( this.filters[ 0 ] ); + geometry.addGroup( group.start, group.count, group.materialIndex ); - for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + } - this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + } - } + const boundingSphere = json.data.boundingSphere; - this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + if ( boundingSphere !== undefined ) { - } else { + const center = new Vector3(); - this.source.disconnect( this.getOutput() ); + if ( boundingSphere.center !== undefined ) { - } + center.fromArray( boundingSphere.center ); - this._connected = false; + } - return this; + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - } + } - getFilters() { + if ( json.name ) geometry.name = json.name; + if ( json.userData ) geometry.userData = json.userData; - return this.filters; + return geometry; } - setFilters( value ) { +} - if ( ! value ) value = []; +class ObjectLoader extends Loader { - if ( this._connected === true ) { + constructor( manager ) { - this.disconnect(); - this.filters = value.slice(); - this.connect(); + super( manager ); - } else { + } - this.filters = value.slice(); + load( url, onLoad, onProgress, onError ) { - } + const scope = this; - return this; + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; - } + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - setDetune( value ) { + let json = null; - this.detune = value; + try { - if ( this.source.detune === undefined ) return; // only set detune when available + json = JSON.parse( text ); - if ( this.isPlaying === true ) { + } catch ( error ) { - this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); + if ( onError !== undefined ) onError( error ); - } + console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); - return this; + return; - } + } - getDetune() { + const metadata = json.metadata; - return this.detune; + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { - } + console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); + return; - getFilter() { + } - return this.getFilters()[ 0 ]; + scope.parse( json, onLoad ); - } + }, onProgress, onError ); - setFilter( filter ) { + } - return this.setFilters( filter ? [ filter ] : [] ); + async loadAsync( url, onProgress ) { - } + const scope = this; - setPlaybackRate( value ) { + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; - if ( this.hasPlaybackControl === false ) { + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + const text = await loader.loadAsync( url, onProgress ); - } + const json = JSON.parse( text ); - this.playbackRate = value; + const metadata = json.metadata; - if ( this.isPlaying === true ) { + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { - this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url ); } - return this; + return await scope.parseAsync( json ); } - getPlaybackRate() { - - return this.playbackRate; - - } + parse( json, onLoad ) { - onEnded() { + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); - this.isPlaying = false; + const images = this.parseImages( json.images, function () { - } + if ( onLoad !== undefined ) onLoad( object ); - getLoop() { + } ); - if ( this.hasPlaybackControl === false ) { + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return false; + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); - } + this.bindSkeletons( object, skeletons ); - return this.loop; + // - } + if ( onLoad !== undefined ) { - setLoop( value ) { + let hasImages = false; - if ( this.hasPlaybackControl === false ) { + for ( const uuid in images ) { - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + if ( images[ uuid ].data instanceof HTMLImageElement ) { - } + hasImages = true; + break; - this.loop = value; + } - if ( this.isPlaying === true ) { + } - this.source.loop = this.loop; + if ( hasImages === false ) onLoad( object ); } - return this; + return object; } - setLoopStart( value ) { + async parseAsync( json ) { - this.loopStart = value; + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); - return this; + const images = await this.parseImagesAsync( json.images ); - } + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); - setLoopEnd( value ) { + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); - this.loopEnd = value; + this.bindSkeletons( object, skeletons ); - return this; + return object; } - getVolume() { - - return this.gain.gain.value; - - } + parseShapes( json ) { - setVolume( value ) { + const shapes = {}; - this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + if ( json !== undefined ) { - return this; + for ( let i = 0, l = json.length; i < l; i ++ ) { - } + const shape = new Shape().fromJSON( json[ i ] ); -} + shapes[ shape.uuid ] = shape; -const _position$3 = /*@__PURE__*/ new Vector3(); -const _quaternion$4 = /*@__PURE__*/ new Quaternion(); -const _scale$2 = /*@__PURE__*/ new Vector3(); -const _orientation$1 = /*@__PURE__*/ new Vector3(); + } -class PositionalAudio extends Audio { + } - constructor( listener ) { + return shapes; - super( listener ); + } - this.panner = this.context.createPanner(); - this.panner.panningModel = 'HRTF'; - this.panner.connect( this.gain ); + parseSkeletons( json, object ) { - } + const skeletons = {}; + const bones = {}; - getOutput() { + // generate bone lookup table - return this.panner; + object.traverse( function ( child ) { - } + if ( child.isBone ) bones[ child.uuid ] = child; - getRefDistance() { + } ); - return this.panner.refDistance; + // create skeletons - } + if ( json !== undefined ) { - setRefDistance( value ) { + for ( let i = 0, l = json.length; i < l; i ++ ) { - this.panner.refDistance = value; + const skeleton = new Skeleton().fromJSON( json[ i ], bones ); - return this; + skeletons[ skeleton.uuid ] = skeleton; - } + } - getRolloffFactor() { + } - return this.panner.rolloffFactor; + return skeletons; } - setRolloffFactor( value ) { + parseGeometries( json, shapes ) { - this.panner.rolloffFactor = value; + const geometries = {}; - return this; + if ( json !== undefined ) { - } + const bufferGeometryLoader = new BufferGeometryLoader(); - getDistanceModel() { + for ( let i = 0, l = json.length; i < l; i ++ ) { - return this.panner.distanceModel; + let geometry; + const data = json[ i ]; - } + switch ( data.type ) { - setDistanceModel( value ) { + case 'BufferGeometry': + case 'InstancedBufferGeometry': - this.panner.distanceModel = value; + geometry = bufferGeometryLoader.parse( data ); + break; - return this; + default: - } + if ( data.type in Geometries ) { - getMaxDistance() { + geometry = Geometries[ data.type ].fromJSON( data, shapes ); - return this.panner.maxDistance; + } else { - } + console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` ); - setMaxDistance( value ) { + } - this.panner.maxDistance = value; + } - return this; + geometry.uuid = data.uuid; - } + if ( data.name !== undefined ) geometry.name = data.name; + if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; - setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { + geometries[ data.uuid ] = geometry; - this.panner.coneInnerAngle = coneInnerAngle; - this.panner.coneOuterAngle = coneOuterAngle; - this.panner.coneOuterGain = coneOuterGain; + } - return this; + } - } + return geometries; - updateMatrixWorld( force ) { + } - super.updateMatrixWorld( force ); + parseMaterials( json, textures ) { - if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; + const cache = {}; // MultiMaterial + const materials = {}; - this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 ); + if ( json !== undefined ) { - _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 ); + const loader = new MaterialLoader(); + loader.setTextures( textures ); - const panner = this.panner; + for ( let i = 0, l = json.length; i < l; i ++ ) { - if ( panner.positionX ) { + const data = json[ i ]; - // code path for Chrome and Firefox (see #14393) + if ( cache[ data.uuid ] === undefined ) { - const endTime = this.context.currentTime + this.listener.timeDelta; + cache[ data.uuid ] = loader.parse( data ); - panner.positionX.linearRampToValueAtTime( _position$3.x, endTime ); - panner.positionY.linearRampToValueAtTime( _position$3.y, endTime ); - panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime ); - panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime ); - panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime ); - panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + } - } else { + materials[ data.uuid ] = cache[ data.uuid ]; - panner.setPosition( _position$3.x, _position$3.y, _position$3.z ); - panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z ); + } } - } + return materials; -} + } -class AudioAnalyser { + parseAnimations( json ) { - constructor( audio, fftSize = 2048 ) { + const animations = {}; - this.analyser = audio.context.createAnalyser(); - this.analyser.fftSize = fftSize; + if ( json !== undefined ) { - this.data = new Uint8Array( this.analyser.frequencyBinCount ); + for ( let i = 0; i < json.length; i ++ ) { - audio.getOutput().connect( this.analyser ); + const data = json[ i ]; - } + const clip = AnimationClip.parse( data ); + animations[ clip.uuid ] = clip; - getFrequencyData() { + } - this.analyser.getByteFrequencyData( this.data ); + } - return this.data; + return animations; } - getAverageFrequency() { + parseImages( json, onLoad ) { - let value = 0; - const data = this.getFrequencyData(); + const scope = this; + const images = {}; - for ( let i = 0; i < data.length; i ++ ) { + let loader; - value += data[ i ]; + function loadImage( url ) { - } + scope.manager.itemStart( url ); - return value / data.length; + return loader.load( url, function () { - } + scope.manager.itemEnd( url ); -} + }, undefined, function () { -class PropertyMixer { + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - constructor( binding, typeName, valueSize ) { + } ); - this.binding = binding; - this.valueSize = valueSize; + } - let mixFunction, - mixFunctionAdditive, - setIdentity; + function deserializeImage( image ) { + + if ( typeof image === 'string' ) { - // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] - // - // 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 - // - // 'add' is used for additive cumulative results - // - // 'work' is optional and is only present for quaternion types. It is used - // to store intermediate quaternion multiplication results + const url = image; - switch ( typeName ) { + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; - case 'quaternion': - mixFunction = this._slerp; - mixFunctionAdditive = this._slerpAdditive; - setIdentity = this._setAdditiveIdentityQuaternion; + return loadImage( path ); - this.buffer = new Float64Array( valueSize * 6 ); - this._workIndex = 5; - break; + } else { - case 'string': - case 'bool': - mixFunction = this._select; + if ( image.data ) { - // Use the regular mix function and for additive on these types, - // additive is not relevant for non-numeric types - mixFunctionAdditive = this._select; + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; - setIdentity = this._setAdditiveIdentityOther; + } else { - this.buffer = new Array( valueSize * 5 ); - break; + return null; - default: - mixFunction = this._lerp; - mixFunctionAdditive = this._lerpAdditive; - setIdentity = this._setAdditiveIdentityNumeric; + } - this.buffer = new Float64Array( valueSize * 5 ); + } } - this._mixBufferRegion = mixFunction; - this._mixBufferRegionAdditive = mixFunctionAdditive; - this._setIdentity = setIdentity; - this._origIndex = 3; - this._addIndex = 4; + if ( json !== undefined && json.length > 0 ) { - this.cumulativeWeight = 0; - this.cumulativeWeightAdditive = 0; + const manager = new LoadingManager( onLoad ); - this.useCount = 0; - this.referenceCount = 0; + loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - } + for ( let i = 0, il = json.length; i < il; i ++ ) { - // accumulate data in the 'incoming' region into 'accu' - accumulate( accuIndex, weight ) { + const image = json[ i ]; + const url = image.url; - // note: happily accumulating nothing when weight = 0, the caller knows - // the weight and shouldn't have made the call in the first place + if ( Array.isArray( url ) ) { - const buffer = this.buffer, - stride = this.valueSize, - offset = accuIndex * stride + stride; + // load array of images e.g CubeTexture - let currentWeight = this.cumulativeWeight; + const imageArray = []; - if ( currentWeight === 0 ) { + for ( let j = 0, jl = url.length; j < jl; j ++ ) { - // accuN := incoming * weight + const currentUrl = url[ j ]; - for ( let i = 0; i !== stride; ++ i ) { + const deserializedImage = deserializeImage( currentUrl ); - buffer[ offset + i ] = buffer[ i ]; + if ( deserializedImage !== null ) { - } + if ( deserializedImage instanceof HTMLImageElement ) { - currentWeight = weight; + imageArray.push( deserializedImage ); - } else { + } else { - // accuN := accuN + incoming * weight + // special case: handle array of data textures for cube textures - currentWeight += weight; - const mix = weight / currentWeight; - this._mixBufferRegion( buffer, offset, 0, mix, stride ); + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); - } + } - this.cumulativeWeight = currentWeight; + } - } + } - // accumulate data in the 'incoming' region into 'add' - accumulateAdditive( weight ) { + images[ image.uuid ] = new Source( imageArray ); - const buffer = this.buffer, - stride = this.valueSize, - offset = stride * this._addIndex; + } else { - if ( this.cumulativeWeightAdditive === 0 ) { + // load single image - // add = identity + const deserializedImage = deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); - this._setIdentity(); - } + } - // add := add + incoming * weight + } - this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); - this.cumulativeWeightAdditive += weight; + } + + return images; } - // apply the state of 'accu' to the binding when accus differ - apply( accuIndex ) { + async parseImagesAsync( json ) { - const stride = this.valueSize, - buffer = this.buffer, - offset = accuIndex * stride + stride, + const scope = this; + const images = {}; - weight = this.cumulativeWeight, - weightAdditive = this.cumulativeWeightAdditive, + let loader; - binding = this.binding; + async function deserializeImage( image ) { - this.cumulativeWeight = 0; - this.cumulativeWeightAdditive = 0; + if ( typeof image === 'string' ) { - if ( weight < 1 ) { + const url = image; - // accuN := accuN + original * ( 1 - cumulativeWeight ) + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; - const originalValueOffset = stride * this._origIndex; + return await loader.loadAsync( path ); - this._mixBufferRegion( - buffer, offset, originalValueOffset, 1 - weight, stride ); + } else { - } + if ( image.data ) { - if ( weightAdditive > 0 ) { + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; - // accuN := accuN + additive accuN + } else { - this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); + return null; - } + } - for ( let i = stride, e = stride + stride; i !== e; ++ i ) { + } - if ( buffer[ i ] !== buffer[ i + stride ] ) { + } - // value has changed -> update scene graph + if ( json !== undefined && json.length > 0 ) { - binding.setValue( buffer, offset ); - break; + loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); - } + for ( let i = 0, il = json.length; i < il; i ++ ) { - } + const image = json[ i ]; + const url = image.url; - } + if ( Array.isArray( url ) ) { - // remember the state of the bound property and copy it to both accus - saveOriginalState() { + // load array of images e.g CubeTexture - const binding = this.binding; + const imageArray = []; - const buffer = this.buffer, - stride = this.valueSize, + for ( let j = 0, jl = url.length; j < jl; j ++ ) { - originalValueOffset = stride * this._origIndex; + const currentUrl = url[ j ]; - binding.getValue( buffer, originalValueOffset ); + const deserializedImage = await deserializeImage( currentUrl ); - // accu[0..1] := orig -- initially detect changes against the original - for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { + if ( deserializedImage !== null ) { - buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + if ( deserializedImage instanceof HTMLImageElement ) { - } + imageArray.push( deserializedImage ); - // Add to identity for additive - this._setIdentity(); + } else { - this.cumulativeWeight = 0; - this.cumulativeWeightAdditive = 0; + // special case: handle array of data textures for cube textures - } + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); - // apply the state previously taken via 'saveOriginalState' to the binding - restoreOriginalState() { + } - const originalValueOffset = this.valueSize * 3; - this.binding.setValue( this.buffer, originalValueOffset ); + } - } + } - _setAdditiveIdentityNumeric() { + images[ image.uuid ] = new Source( imageArray ); - const startIndex = this._addIndex * this.valueSize; - const endIndex = startIndex + this.valueSize; + } else { - for ( let i = startIndex; i < endIndex; i ++ ) { + // load single image - this.buffer[ i ] = 0; + const deserializedImage = await deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); - } + } - } + } - _setAdditiveIdentityQuaternion() { + } - this._setAdditiveIdentityNumeric(); - this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; + return images; } - _setAdditiveIdentityOther() { + parseTextures( json, images ) { - const startIndex = this._origIndex * this.valueSize; - const targetIndex = this._addIndex * this.valueSize; + function parseConstant( value, type ) { - for ( let i = 0; i < this.valueSize; i ++ ) { + if ( typeof value === 'number' ) return value; - this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + + return type[ value ]; } - } + const textures = {}; + if ( json !== undefined ) { - // mix functions + for ( let i = 0, l = json.length; i < l; i ++ ) { - _select( buffer, dstOffset, srcOffset, t, stride ) { + const data = json[ i ]; - if ( t >= 0.5 ) { + if ( data.image === undefined ) { - for ( let i = 0; i !== stride; ++ i ) { + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); - buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + } - } + if ( images[ data.image ] === undefined ) { - } + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); - } + } - _slerp( buffer, dstOffset, srcOffset, t ) { + const source = images[ data.image ]; + const image = source.data; - Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); + let texture; - } + if ( Array.isArray( image ) ) { - _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + texture = new CubeTexture(); - const workOffset = this._workIndex * stride; + if ( image.length === 6 ) texture.needsUpdate = true; - // Store result in intermediate buffer offset - Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); + } else { - // Slerp to the intermediate result - Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); + if ( image && image.data ) { - } + texture = new DataTexture(); - _lerp( buffer, dstOffset, srcOffset, t, stride ) { + } else { - const s = 1 - t; + texture = new Texture(); - for ( let i = 0; i !== stride; ++ i ) { + } - const j = dstOffset + i; + if ( image ) texture.needsUpdate = true; // textures can have undefined image data - buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + } - } + texture.source = source; - } + texture.uuid = data.uuid; - _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + if ( data.name !== undefined ) texture.name = data.name; - for ( let i = 0; i !== stride; ++ i ) { + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); - const j = dstOffset + i; + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.center !== undefined ) texture.center.fromArray( data.center ); + if ( data.rotation !== undefined ) texture.rotation = data.rotation; - buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; + if ( data.wrap !== undefined ) { - } + texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); + texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); - } + } -} + if ( data.format !== undefined ) texture.format = data.format; + if ( data.type !== undefined ) texture.type = data.type; + if ( data.encoding !== undefined ) texture.encoding = data.encoding; -// Characters [].:/ are reserved for track binding syntax. -const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; -const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; -// Attempts to allow node names from any language. ES5's `\w` regexp matches -// only latin characters, and the unicode \p{L} is not yet supported. So -// instead, we exclude reserved characters and match everything else. -const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; -const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; + if ( data.flipY !== undefined ) texture.flipY = data.flipY; -// Parent directories, delimited by '/' or ':'. Currently unused, but must -// be matched to parse the rest of the track name. -const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); + if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; + if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; -// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. -const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); + if ( data.userData !== undefined ) texture.userData = data.userData; -// Object on target node, and accessor. May not contain reserved -// characters. Accessor may contain any character except closing bracket. -const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); + textures[ data.uuid ] = texture; -// Property and accessor. May not contain reserved characters. Accessor may -// contain any non-bracket characters. -const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); + } -const _trackRe = new RegExp( '' - + '^' - + _directoryRe - + _nodeRe - + _objectRe - + _propertyRe - + '$' -); + } -const _supportedObjectNames = [ 'material', 'materials', 'bones' ]; + return textures; -function Composite( targetGroup, path, optionalParsedPath ) { + } - const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); + parseObject( data, geometries, materials, textures, animations ) { - this._targetGroup = targetGroup; - this._bindings = targetGroup.subscribe_( path, parsedPath ); + let object; -} + function getGeometry( name ) { -Object.assign( Composite.prototype, { + if ( geometries[ name ] === undefined ) { - getValue: function ( array, offset ) { + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); - this.bind(); // bind all binding + } - const firstValidIndex = this._targetGroup.nCachedObjects_, - binding = this._bindings[ firstValidIndex ]; + return geometries[ name ]; - // and only call .getValue on the first - if ( binding !== undefined ) binding.getValue( array, offset ); + } - }, + function getMaterial( name ) { - setValue: function ( array, offset ) { + if ( name === undefined ) return undefined; - const bindings = this._bindings; + if ( Array.isArray( name ) ) { - for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + const array = []; - bindings[ i ].setValue( array, offset ); + for ( let i = 0, l = name.length; i < l; i ++ ) { - } + const uuid = name[ i ]; - }, + if ( materials[ uuid ] === undefined ) { - bind: function () { + console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); - const bindings = this._bindings; + } - for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + array.push( materials[ uuid ] ); - bindings[ i ].bind(); + } - } + return array; - }, + } - unbind: function () { + if ( materials[ name ] === undefined ) { - const bindings = this._bindings; + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + } - bindings[ i ].unbind(); + return materials[ name ]; } - } + function getTexture( uuid ) { + + if ( textures[ uuid ] === undefined ) { -} ); + console.warn( 'THREE.ObjectLoader: Undefined texture', uuid ); + } -function PropertyBinding( rootNode, path, parsedPath ) { + return textures[ uuid ]; - this.path = path; - this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); + } - this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; + let geometry, material; - this.rootNode = rootNode; + switch ( data.type ) { -} + case 'Scene': -Object.assign( PropertyBinding, { + object = new Scene(); - Composite: Composite, + if ( data.background !== undefined ) { - create: function ( root, path, parsedPath ) { + if ( Number.isInteger( data.background ) ) { - if ( ! ( root && root.isAnimationObjectGroup ) ) { + object.background = new Color( data.background ); - return new PropertyBinding( root, path, parsedPath ); + } else { - } else { + object.background = getTexture( data.background ); - return new PropertyBinding.Composite( root, path, parsedPath ); + } - } + } - }, + if ( data.environment !== undefined ) { - /** - * Replaces spaces with underscores and removes unsupported characters from - * node names, to ensure compatibility with parseTrackName(). - * - * @param {string} name Node name to be sanitized. - * @return {string} - */ - sanitizeNodeName: function ( name ) { + object.environment = getTexture( data.environment ); - return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); + } - }, + if ( data.fog !== undefined ) { - parseTrackName: function ( trackName ) { + if ( data.fog.type === 'Fog' ) { - const matches = _trackRe.exec( trackName ); + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); - if ( ! matches ) { + } else if ( data.fog.type === 'FogExp2' ) { - throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); + object.fog = new FogExp2( data.fog.color, data.fog.density ); - } + } - const results = { - // directoryName: matches[ 1 ], // (tschw) currently unused - nodeName: matches[ 2 ], - objectName: matches[ 3 ], - objectIndex: matches[ 4 ], - propertyName: matches[ 5 ], // required - propertyIndex: matches[ 6 ] - }; + } - const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + break; - if ( lastDot !== undefined && lastDot !== - 1 ) { + case 'PerspectiveCamera': - const objectName = results.nodeName.substring( lastDot + 1 ); + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - // Object names must be checked against an allowlist. Otherwise, there - // is no way to parse 'foo.bar.baz': 'baz' must be a property, but - // 'bar' could be the objectName, or part of a nodeName (which can - // include '.' characters). - if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { + 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 ); - results.nodeName = results.nodeName.substring( 0, lastDot ); - results.objectName = objectName; + break; - } + case 'OrthographicCamera': - } + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - if ( results.propertyName === null || results.propertyName.length === 0 ) { + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + break; - } + case 'AmbientLight': - return results; + object = new AmbientLight( data.color, data.intensity ); - }, + break; - findNode: function ( root, nodeName ) { + case 'DirectionalLight': - if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { + object = new DirectionalLight( data.color, data.intensity ); - return root; + break; - } + case 'PointLight': - // search into skeleton bones. - if ( root.skeleton ) { + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - const bone = root.skeleton.getBoneByName( nodeName ); + break; - if ( bone !== undefined ) { + case 'RectAreaLight': - return bone; + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); - } + break; - } + case 'SpotLight': - // search into node subtree. - if ( root.children ) { + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - const searchNodeSubtree = function ( children ) { + break; - for ( let i = 0; i < children.length; i ++ ) { + case 'HemisphereLight': - const childNode = children[ i ]; + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + break; - return childNode; + case 'LightProbe': - } + object = new LightProbe().fromJSON( data ); - const result = searchNodeSubtree( childNode.children ); + break; - if ( result ) return result; + case 'SkinnedMesh': - } + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); - return null; + object = new SkinnedMesh( geometry, material ); - }; + if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; + if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); + if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; - const subTreeNode = searchNodeSubtree( root.children ); + break; - if ( subTreeNode ) { + case 'Mesh': - return subTreeNode; + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); - } + object = new Mesh( geometry, material ); - } + break; - return null; + case 'InstancedMesh': - } + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; -} ); + object = new InstancedMesh( geometry, material, count ); + object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize ); -Object.assign( PropertyBinding.prototype, { // prototype, continued + break; - // these are used to "bind" a nonexistent property - _getValue_unavailable: function () {}, - _setValue_unavailable: function () {}, - - BindingType: { - Direct: 0, - EntireArray: 1, - ArrayElement: 2, - HasFromToArray: 3 - }, + case 'LOD': - Versioning: { - None: 0, - NeedsUpdate: 1, - MatrixWorldNeedsUpdate: 2 - }, + object = new LOD(); - GetterByBindingType: [ + break; - function getValue_direct( buffer, offset ) { + case 'Line': - buffer[ offset ] = this.node[ this.propertyName ]; + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); - }, + break; - function getValue_array( buffer, offset ) { + case 'LineLoop': - const source = this.resolvedProperty; + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); - for ( let i = 0, n = source.length; i !== n; ++ i ) { + break; - buffer[ offset ++ ] = source[ i ]; + case 'LineSegments': - } + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); - }, + break; - function getValue_arrayElement( buffer, offset ) { + case 'PointCloud': + case 'Points': - buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - }, + break; - function getValue_toArray( buffer, offset ) { + case 'Sprite': - this.resolvedProperty.toArray( buffer, offset ); + object = new Sprite( getMaterial( data.material ) ); - } + break; - ], + case 'Group': - SetterByBindingTypeAndVersioning: [ + object = new Group(); - [ - // Direct + break; - function setValue_direct( buffer, offset ) { + case 'Bone': - this.targetObject[ this.propertyName ] = buffer[ offset ]; + object = new Bone(); - }, + break; - function setValue_direct_setNeedsUpdate( buffer, offset ) { + default: - this.targetObject[ this.propertyName ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + object = new Object3D(); - }, + } - function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + object.uuid = data.uuid; - this.targetObject[ this.propertyName ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + if ( data.name !== undefined ) object.name = data.name; - } + if ( data.matrix !== undefined ) { - ], [ + object.matrix.fromArray( data.matrix ); - // EntireArray + if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; + if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale ); - function setValue_array( buffer, offset ) { + } else { - const dest = this.resolvedProperty; + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - for ( let i = 0, n = dest.length; i !== n; ++ i ) { + } - dest[ i ] = buffer[ offset ++ ]; + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - } + if ( data.shadow ) { - }, + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); - function setValue_array_setNeedsUpdate( buffer, offset ) { + } - const dest = this.resolvedProperty; + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.userData !== undefined ) object.userData = data.userData; + if ( data.layers !== undefined ) object.layers.mask = data.layers; - for ( let i = 0, n = dest.length; i !== n; ++ i ) { + if ( data.children !== undefined ) { - dest[ i ] = buffer[ offset ++ ]; + const children = data.children; - } + for ( let i = 0; i < children.length; i ++ ) { - this.targetObject.needsUpdate = true; + object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) ); - }, + } - function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + } - const dest = this.resolvedProperty; + if ( data.animations !== undefined ) { - for ( let i = 0, n = dest.length; i !== n; ++ i ) { + const objectAnimations = data.animations; - dest[ i ] = buffer[ offset ++ ]; + for ( let i = 0; i < objectAnimations.length; i ++ ) { - } + const uuid = objectAnimations[ i ]; - this.targetObject.matrixWorldNeedsUpdate = true; + object.animations.push( animations[ uuid ] ); } - ], [ - - // ArrayElement + } - function setValue_arrayElement( buffer, offset ) { + if ( data.type === 'LOD' ) { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; - }, + const levels = data.levels; - function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + for ( let l = 0; l < levels.length; l ++ ) { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + const level = levels[ l ]; + const child = object.getObjectByProperty( 'uuid', level.object ); - }, + if ( child !== undefined ) { - function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + object.addLevel( child, level.distance ); - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + } } - ], [ + } - // HasToFromArray + return object; - function setValue_fromArray( buffer, offset ) { + } - this.resolvedProperty.fromArray( buffer, offset ); + bindSkeletons( object, skeletons ) { - }, + if ( Object.keys( skeletons ).length === 0 ) return; - function setValue_fromArray_setNeedsUpdate( buffer, offset ) { + object.traverse( function ( child ) { - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.needsUpdate = true; + if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { - }, + const skeleton = skeletons[ child.skeleton ]; - function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + if ( skeleton === undefined ) { - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.matrixWorldNeedsUpdate = true; + console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton ); - } + } else { - ] + child.bind( skeleton, child.bindMatrix ); - ], + } - 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. + } - }, +} - setValue: function getValue_unbound( sourceArray, offset ) { +const TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping +}; - this.bind(); - this.setValue( sourceArray, offset ); +const TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping +}; - }, +const TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + LinearFilter: LinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter +}; - // create getter / setter pair for a property in the scene graph - bind: function () { +class ImageBitmapLoader extends Loader { - let targetObject = this.node; - const parsedPath = this.parsedPath; + constructor( manager ) { - const objectName = parsedPath.objectName; - const propertyName = parsedPath.propertyName; - let propertyIndex = parsedPath.propertyIndex; + super( manager ); - if ( ! targetObject ) { + this.isImageBitmapLoader = true; - targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; + if ( typeof createImageBitmap === 'undefined' ) { - this.node = targetObject; + console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); } - // 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 ) { + if ( typeof fetch === 'undefined' ) { - console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); - return; + console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); } - if ( objectName ) { - - let objectIndex = parsedPath.objectIndex; + this.options = { premultiplyAlpha: 'none' }; - // special cases were we need to reach deeper into the hierarchy to get the face materials.... - switch ( objectName ) { + } - case 'materials': + setOptions( options ) { - if ( ! targetObject.material ) { + this.options = options; - console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); - return; + return this; - } + } - if ( ! targetObject.material.materials ) { + load( url, onLoad, onProgress, onError ) { - console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); - return; + if ( url === undefined ) url = ''; - } + if ( this.path !== undefined ) url = this.path + url; - targetObject = targetObject.material.materials; + url = this.manager.resolveURL( url ); - break; + const scope = this; - case 'bones': + const cached = Cache.get( url ); - if ( ! targetObject.skeleton ) { + if ( cached !== undefined ) { - console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); - return; + scope.manager.itemStart( url ); - } + setTimeout( function () { - // potential future optimization: skip this if propertyIndex is already an integer - // and convert the integer string to a true integer. + if ( onLoad ) onLoad( cached ); - targetObject = targetObject.skeleton.bones; + scope.manager.itemEnd( url ); - // support resolving morphTarget names into indices. - for ( let i = 0; i < targetObject.length; i ++ ) { + }, 0 ); - if ( targetObject[ i ].name === objectIndex ) { + return cached; - objectIndex = i; - break; + } - } + const fetchOptions = {}; + fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; + fetchOptions.headers = this.requestHeader; - } + fetch( url, fetchOptions ).then( function ( res ) { - break; + return res.blob(); - default: + } ).then( function ( blob ) { - if ( targetObject[ objectName ] === undefined ) { + return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) ); - console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); - return; + } ).then( function ( imageBitmap ) { - } + Cache.add( url, imageBitmap ); - targetObject = targetObject[ objectName ]; + if ( onLoad ) onLoad( imageBitmap ); - } + scope.manager.itemEnd( url ); + } ).catch( function ( e ) { - if ( objectIndex !== undefined ) { + if ( onError ) onError( e ); - if ( targetObject[ objectIndex ] === undefined ) { + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); - return; + } ); - } + scope.manager.itemStart( url ); - targetObject = targetObject[ objectIndex ]; + } - } +} - } +let _context; - // resolve property - const nodeProperty = targetObject[ propertyName ]; +const AudioContext = { - if ( nodeProperty === undefined ) { + getContext: function () { - const nodeName = parsedPath.nodeName; + if ( _context === undefined ) { - console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + - '.' + propertyName + ' but it wasn\'t found.', targetObject ); - return; + _context = new ( window.AudioContext || window.webkitAudioContext )(); } - // determine versioning scheme - let versioning = this.Versioning.None; - - this.targetObject = targetObject; - - if ( targetObject.needsUpdate !== undefined ) { // material + return _context; - versioning = this.Versioning.NeedsUpdate; + }, - } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + setContext: function ( value ) { - versioning = this.Versioning.MatrixWorldNeedsUpdate; + _context = value; - } + } - // determine how the property gets bound - let bindingType = this.BindingType.Direct; +}; - if ( propertyIndex !== undefined ) { +class AudioLoader extends Loader { - // access a sub element of the property array (only primitives are supported right now) + constructor( manager ) { - if ( propertyName === 'morphTargetInfluences' ) { + super( manager ); - // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + } - // support resolving morphTarget names into indices. - if ( ! targetObject.geometry ) { + load( url, onLoad, onProgress, onError ) { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); - return; + const scope = this; - } + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( buffer ) { - if ( targetObject.geometry.isBufferGeometry ) { + try { - if ( ! targetObject.geometry.morphAttributes ) { + // Create a copy of the buffer. The `decodeAudioData` method + // detaches the buffer when complete, preventing reuse. + const bufferCopy = buffer.slice( 0 ); - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); - return; + const context = AudioContext.getContext(); + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { - } + onLoad( audioBuffer ); - if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { + } ); - propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; + } catch ( e ) { - } + if ( onError ) { + onError( e ); } else { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this ); - return; + console.error( e ); } + scope.manager.itemError( url ); + } - bindingType = this.BindingType.ArrayElement; + }, onProgress, onError ); - this.resolvedProperty = nodeProperty; - this.propertyIndex = propertyIndex; + } - } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { +} - // must use copy for Object3D.Euler/Quaternion +class HemisphereLightProbe extends LightProbe { - bindingType = this.BindingType.HasFromToArray; + constructor( skyColor, groundColor, intensity = 1 ) { - this.resolvedProperty = nodeProperty; + super( undefined, intensity ); - } else if ( Array.isArray( nodeProperty ) ) { + this.isHemisphereLightProbe = true; - bindingType = this.BindingType.EntireArray; + const color1 = new Color().set( skyColor ); + const color2 = new Color().set( groundColor ); - this.resolvedProperty = nodeProperty; + const sky = new Vector3( color1.r, color1.g, color1.b ); + const ground = new Vector3( color2.r, color2.g, color2.b ); - } else { + // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); + const c0 = Math.sqrt( Math.PI ); + const c1 = c0 * Math.sqrt( 0.75 ); - this.propertyName = propertyName; + this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); + this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); - } + } - // select getter / setter - this.getValue = this.GetterByBindingType[ bindingType ]; - this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; +} - }, +class AmbientLightProbe extends LightProbe { - unbind: function () { + constructor( color, intensity = 1 ) { - this.node = null; + super( undefined, intensity ); - // 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; + this.isAmbientLightProbe = true; + + const color1 = new Color().set( color ); + + // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); + this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); } -} ); +} -// DECLARE ALIAS AFTER assign prototype -Object.assign( PropertyBinding.prototype, { +const _eyeRight = /*@__PURE__*/ new Matrix4(); +const _eyeLeft = /*@__PURE__*/ new Matrix4(); +const _projectionMatrix = /*@__PURE__*/ new Matrix4(); - // initial state of these methods that calls 'bind' - _getValue_unbound: PropertyBinding.prototype.getValue, - _setValue_unbound: PropertyBinding.prototype.setValue, +class StereoCamera { -} ); + constructor() { -/** - * - * 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. - */ + this.type = 'StereoCamera'; -class AnimationObjectGroup { + this.aspect = 1; - constructor() { + this.eyeSep = 0.064; - this.uuid = MathUtils.generateUUID(); + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; - // cached objects followed by the active ones - this._objects = Array.prototype.slice.call( arguments ); + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; - this.nCachedObjects_ = 0; // threshold - // note: read by PropertyBinding.Composite + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; - const indices = {}; - this._indicesByUUID = indices; // for bookkeeping + } - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + update( camera ) { - indices[ arguments[ i ].uuid ] = i; + const cache = this._cache; - } + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || + cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || + cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; - this._paths = []; // inside: string - this._parsedPaths = []; // inside: { we don't care, here } - this._bindings = []; // inside: Array< PropertyBinding > - this._bindingsIndicesByPath = {}; // inside: indices in these arrays + if ( needsUpdate ) { - const scope = this; + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; - this.stats = { + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ - objects: { - get total() { + _projectionMatrix.copy( camera.projectionMatrix ); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; + let xmin, xmax; - return scope._objects.length; + // translate xOffset - }, - get inUse() { + _eyeLeft.elements[ 12 ] = - eyeSepHalf; + _eyeRight.elements[ 12 ] = eyeSepHalf; - return this.total - scope.nCachedObjects_; + // for left eye - } - }, - get bindingsPerObject() { + xmin = - ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; - return scope._bindings.length; + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - } + this.cameraL.projectionMatrix.copy( _projectionMatrix ); - }; + // for right eye + + xmin = - ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraR.projectionMatrix.copy( _projectionMatrix ); + + } + + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); } - add() { +} - const objects = this._objects, - indicesByUUID = this._indicesByUUID, - paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - nBindings = bindings.length; +class Clock { - let knownObject = undefined, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_; + constructor( autoStart = true ) { - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + this.autoStart = autoStart; - const object = arguments[ i ], - uuid = object.uuid; - let index = indicesByUUID[ uuid ]; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; - if ( index === undefined ) { + this.running = false; + + } + + start() { + + this.startTime = now(); - // unknown object -> add it to the ACTIVE region + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; - index = nObjects ++; - indicesByUUID[ uuid ] = index; - objects.push( object ); + } - // accounting is done, now do the same for all bindings + stop() { - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; - bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); + } - } + getElapsedTime() { - } else if ( index < nCachedObjects ) { + this.getDelta(); + return this.elapsedTime; - knownObject = objects[ index ]; + } - // move existing object to the ACTIVE region + getDelta() { - const firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ]; + let diff = 0; - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + if ( this.autoStart && ! this.running ) { - indicesByUUID[ uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = object; + this.start(); + return 0; - // accounting is done, now do the same for all bindings + } - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + if ( this.running ) { - const bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ]; + const newTime = now(); - let binding = bindingsForPath[ index ]; + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; - bindingsForPath[ index ] = lastCached; + this.elapsedTime += diff; - if ( binding === undefined ) { + } - // since we do not bother to create new bindings - // for objects that are cached, the binding may - // or may not exist + return diff; - binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); + } - } +} - bindingsForPath[ firstActiveIndex ] = binding; +function now() { - } + return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 - } else if ( objects[ index ] !== knownObject ) { +} - console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + - 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); +const _position$1 = /*@__PURE__*/ new Vector3(); +const _quaternion$1 = /*@__PURE__*/ new Quaternion(); +const _scale$1 = /*@__PURE__*/ new Vector3(); +const _orientation$1 = /*@__PURE__*/ new Vector3(); - } // else the object is already where we want it to be +class AudioListener extends Object3D { - } // for arguments + constructor() { - this.nCachedObjects_ = nCachedObjects; + super(); - } + this.type = 'AudioListener'; - remove() { + this.context = AudioContext.getContext(); - const objects = this._objects, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - let nCachedObjects = this.nCachedObjects_; + this.filter = null; - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + this.timeDelta = 0; - const object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + // private - if ( index !== undefined && index >= nCachedObjects ) { + this._clock = new Clock(); - // move existing object into the CACHED region + } - const lastCachedIndex = nCachedObjects ++, - firstActiveObject = objects[ lastCachedIndex ]; + getInput() { - indicesByUUID[ firstActiveObject.uuid ] = index; - objects[ index ] = firstActiveObject; + return this.gain; - indicesByUUID[ uuid ] = lastCachedIndex; - objects[ lastCachedIndex ] = object; + } - // accounting is done, now do the same for all bindings + removeFilter() { - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + if ( this.filter !== null ) { - const bindingsForPath = bindings[ j ], - firstActive = bindingsForPath[ lastCachedIndex ], - binding = bindingsForPath[ index ]; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; - bindingsForPath[ index ] = firstActive; - bindingsForPath[ lastCachedIndex ] = binding; + } - } + return this; - } + } - } // for arguments + getFilter() { - this.nCachedObjects_ = nCachedObjects; + return this.filter; } - // remove & forget - uncache() { + setFilter( value ) { - const objects = this._objects, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + if ( this.filter !== null ) { - let nCachedObjects = this.nCachedObjects_, - nObjects = objects.length; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); - for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + } else { - const object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + this.gain.disconnect( this.context.destination ); - if ( index !== undefined ) { + } - delete indicesByUUID[ uuid ]; + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); - if ( index < nCachedObjects ) { + return this; - // object is cached, shrink the CACHED region + } - const firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ], - lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + getMasterVolume() { - // last cached object takes this object's place - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + return this.gain.gain.value; - // 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 + setMasterVolume( value ) { - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); - const bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - last = bindingsForPath[ lastIndex ]; + return this; - bindingsForPath[ index ] = lastCached; - bindingsForPath[ firstActiveIndex ] = last; - bindingsForPath.pop(); + } - } + updateMatrixWorld( force ) { - } else { + super.updateMatrixWorld( force ); - // object is active, just swap with the last and pop + const listener = this.context.listener; + const up = this.up; - const lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + this.timeDelta = this._clock.getDelta(); - if ( lastIndex > 0 ) { + this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 ); - indicesByUUID[ lastObject.uuid ] = index; + _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 ); - } + if ( listener.positionX ) { - objects[ index ] = lastObject; - objects.pop(); + // code path for Chrome (see #14393) - // accounting is done, now do the same for all bindings + const endTime = this.context.currentTime + this.timeDelta; - for ( let j = 0, m = nBindings; j !== m; ++ j ) { + listener.positionX.linearRampToValueAtTime( _position$1.x, endTime ); + listener.positionY.linearRampToValueAtTime( _position$1.y, endTime ); + listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime ); + listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime ); + listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime ); + listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + listener.upX.linearRampToValueAtTime( up.x, endTime ); + listener.upY.linearRampToValueAtTime( up.y, endTime ); + listener.upZ.linearRampToValueAtTime( up.z, endTime ); - const bindingsForPath = bindings[ j ]; + } else { - bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; - bindingsForPath.pop(); + listener.setPosition( _position$1.x, _position$1.y, _position$1.z ); + listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z ); - } + } - } // cached or active + } - } // if object is known +} - } // for arguments +class Audio extends Object3D { - this.nCachedObjects_ = nCachedObjects; + constructor( listener ) { - } + super(); - // Internal interface used by befriended PropertyBinding.Composite: + this.type = 'Audio'; - subscribe_( path, parsedPath ) { + this.listener = listener; + this.context = listener.context; - // returns an array of bindings for the given path that is changed - // according to the contained objects in the group + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); - const indicesByPath = this._bindingsIndicesByPath; - let index = indicesByPath[ path ]; - const bindings = this._bindings; + this.autoplay = false; - if ( index !== undefined ) return bindings[ index ]; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = 'empty'; - const paths = this._paths, - parsedPaths = this._parsedPaths, - objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - bindingsForPath = new Array( nObjects ); + this._startedAt = 0; + this._progress = 0; + this._connected = false; - index = bindings.length; + this.filters = []; - indicesByPath[ path ] = index; + } - paths.push( path ); - parsedPaths.push( parsedPath ); - bindings.push( bindingsForPath ); + getOutput() { - for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { + return this.gain; - const object = objects[ i ]; - bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); + } - } + setNodeSource( audioNode ) { - return bindingsForPath; + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); + + return this; } - unsubscribe_( path ) { + setMediaElementSource( mediaElement ) { - // tells the group to forget about a property path and no longer - // update the array previously obtained with 'subscribe_' + this.hasPlaybackControl = false; + this.sourceType = 'mediaNode'; + this.source = this.context.createMediaElementSource( mediaElement ); + this.connect(); - const indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ]; + return this; - if ( index !== undefined ) { + } - const paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - lastBindingsIndex = bindings.length - 1, - lastBindings = bindings[ lastBindingsIndex ], - lastBindingsPath = path[ lastBindingsIndex ]; + setMediaStreamSource( mediaStream ) { - indicesByPath[ lastBindingsPath ] = index; + this.hasPlaybackControl = false; + this.sourceType = 'mediaStreamNode'; + this.source = this.context.createMediaStreamSource( mediaStream ); + this.connect(); - bindings[ index ] = lastBindings; - bindings.pop(); + return this; - parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; - parsedPaths.pop(); + } - paths[ index ] = paths[ lastBindingsIndex ]; - paths.pop(); + setBuffer( audioBuffer ) { - } + this.buffer = audioBuffer; + this.sourceType = 'buffer'; + + if ( this.autoplay ) this.play(); + + return this; } -} + play( delay = 0 ) { -AnimationObjectGroup.prototype.isAnimationObjectGroup = true; + if ( this.isPlaying === true ) { -class AnimationAction { + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; - constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { + } - this._mixer = mixer; - this._clip = clip; - this._localRoot = localRoot; - this.blendMode = blendMode; + if ( this.hasPlaybackControl === false ) { - const tracks = clip.tracks, - nTracks = tracks.length, - interpolants = new Array( nTracks ); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - const interpolantSettings = { - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding - }; + } - for ( let i = 0; i !== nTracks; ++ i ) { + this._startedAt = this.context.currentTime + delay; - const interpolant = tracks[ i ].createInterpolant( null ); - interpolants[ i ] = interpolant; - interpolant.settings = interpolantSettings; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind( this ); + source.start( this._startedAt, this._progress + this.offset, this.duration ); - } + this.isPlaying = true; - this._interpolantSettings = interpolantSettings; + this.source = source; - this._interpolants = interpolants; // bound by the mixer + this.setDetune( this.detune ); + this.setPlaybackRate( this.playbackRate ); - // inside: PropertyMixer (managed by the mixer) - this._propertyBindings = new Array( nTracks ); + return this.connect(); - this._cacheIndex = null; // for the memory manager - this._byClipCacheIndex = null; // for the memory manager + } - this._timeScaleInterpolant = null; - this._weightInterpolant = null; + pause() { - this.loop = LoopRepeat; - this._loopCount = - 1; + if ( this.hasPlaybackControl === false ) { - // global mixer time when the action is to be started - // it's set back to 'null' upon start of the action - this._startTime = null; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - // 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; + if ( this.isPlaying === true ) { - this.weight = 1; - this._effectiveWeight = 1; + // update current progress - this.repetitions = Infinity; // no. of repetitions when looping + this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; - this.paused = false; // true -> zero effective time scale - this.enabled = true; // false -> zero effective weight + if ( this.loop === true ) { - this.clampWhenFinished = false;// keep feeding the last frame? + // ensure _progress does not exceed duration with looped audios - this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate - this.zeroSlopeAtEnd = true;// clips for start, loop and end + this._progress = this._progress % ( this.duration || this.buffer.duration ); - } + } - // State & Scheduling + this.source.stop(); + this.source.onended = null; - play() { + this.isPlaying = false; - this._mixer._activateAction( this ); + } return this; @@ -42641,127 +43689,110 @@ class AnimationAction { stop() { - this._mixer._deactivateAction( this ); - - return this.reset(); + if ( this.hasPlaybackControl === false ) { - } + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - reset() { + } - this.paused = false; - this.enabled = true; + this._progress = 0; - this.time = 0; // restart clip - this._loopCount = - 1;// forget previous loops - this._startTime = null;// forget scheduling + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; - return this.stopFading().stopWarping(); + return this; } - isRunning() { - - return this.enabled && ! this.paused && this.timeScale !== 0 && - this._startTime === null && this._mixer._isActiveAction( this ); + connect() { - } + if ( this.filters.length > 0 ) { - // return true when play has been called - isScheduled() { + this.source.connect( this.filters[ 0 ] ); - return this._mixer._isActiveAction( this ); + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { - } + this.filters[ i - 1 ].connect( this.filters[ i ] ); - startAt( time ) { + } - this._startTime = time; + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); - return this; + } else { - } + this.source.connect( this.getOutput() ); - setLoop( mode, repetitions ) { + } - this.loop = mode; - this.repetitions = repetitions; + this._connected = true; return this; } - // Weight + disconnect() { - // 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( weight ) { + if ( this.filters.length > 0 ) { - this.weight = weight; + this.source.disconnect( this.filters[ 0 ] ); - // note: same logic as when updated at runtime - this._effectiveWeight = this.enabled ? weight : 0; + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { - return this.stopFading(); + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); - } + } - // return the weight considering fading and .enabled - getEffectiveWeight() { + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); - return this._effectiveWeight; + } else { - } + this.source.disconnect( this.getOutput() ); - fadeIn( duration ) { + } - return this._scheduleFading( duration, 0, 1 ); + this._connected = false; + + return this; } - fadeOut( duration ) { + getFilters() { - return this._scheduleFading( duration, 1, 0 ); + return this.filters; } - crossFadeFrom( fadeOutAction, duration, warp ) { + setFilters( value ) { - fadeOutAction.fadeOut( duration ); - this.fadeIn( duration ); + if ( ! value ) value = []; - if ( warp ) { + if ( this._connected === true ) { - const fadeInDuration = this._clip.duration, - fadeOutDuration = fadeOutAction._clip.duration, + this.disconnect(); + this.filters = value.slice(); + this.connect(); - startEndRatio = fadeOutDuration / fadeInDuration, - endStartRatio = fadeInDuration / fadeOutDuration; + } else { - fadeOutAction.warp( 1.0, startEndRatio, duration ); - this.warp( endStartRatio, 1.0, duration ); + this.filters = value.slice(); } - return this; - - } - - crossFadeTo( fadeInAction, duration, warp ) { - - return fadeInAction.crossFadeFrom( this, duration, warp ); + return this; } - stopFading() { + setDetune( value ) { - const weightInterpolant = this._weightInterpolant; + this.detune = value; - if ( weightInterpolant !== null ) { + if ( this.source.detune === undefined ) return; // only set detune when available - this._weightInterpolant = null; - this._mixer._takeBackControlInterpolant( weightInterpolant ); + if ( this.isPlaying === true ) { + + this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); } @@ -42769,86 +43800,84 @@ class AnimationAction { } - // Time Scale Control + getDetune() { - // set the time scale 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( timeScale ) { + return this.detune; - this.timeScale = timeScale; - this._effectiveTimeScale = this.paused ? 0 : timeScale; + } - return this.stopWarping(); + getFilter() { + + return this.getFilters()[ 0 ]; } - // return the time scale considering warping and .paused - getEffectiveTimeScale() { + setFilter( filter ) { - return this._effectiveTimeScale; + return this.setFilters( filter ? [ filter ] : [] ); } - setDuration( duration ) { + setPlaybackRate( value ) { - this.timeScale = this._clip.duration / duration; + if ( this.hasPlaybackControl === false ) { - return this.stopWarping(); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - } + } - syncWith( action ) { + this.playbackRate = value; - this.time = action.time; - this.timeScale = action.timeScale; + if ( this.isPlaying === true ) { - return this.stopWarping(); + this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + + } + + return this; } - halt( duration ) { + getPlaybackRate() { - return this.warp( this._effectiveTimeScale, 0, duration ); + return this.playbackRate; } - warp( startTimeScale, endTimeScale, duration ) { + onEnded() { - const mixer = this._mixer, - now = mixer.time, - timeScale = this.timeScale; + this.isPlaying = false; - let interpolant = this._timeScaleInterpolant; + } - if ( interpolant === null ) { + getLoop() { - interpolant = mixer._lendControlInterpolant(); - this._timeScaleInterpolant = interpolant; + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; } - const times = interpolant.parameterPositions, - values = interpolant.sampleValues; + return this.loop; - times[ 0 ] = now; - times[ 1 ] = now + duration; + } - values[ 0 ] = startTimeScale / timeScale; - values[ 1 ] = endTimeScale / timeScale; + setLoop( value ) { - return this; + if ( this.hasPlaybackControl === false ) { - } + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - stopWarping() { + } - const timeScaleInterpolant = this._timeScaleInterpolant; + this.loop = value; - if ( timeScaleInterpolant !== null ) { + if ( this.isPlaying === true ) { - this._timeScaleInterpolant = null; - this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + this.source.loop = this.loop; } @@ -42856,6060 +43885,5749 @@ class AnimationAction { } - // Object Accessors + setLoopStart( value ) { - getMixer() { + this.loopStart = value; - return this._mixer; + return this; } - getClip() { + setLoopEnd( value ) { - return this._clip; + this.loopEnd = value; + + return this; } - getRoot() { + getVolume() { - return this._localRoot || this._mixer._root; + return this.gain.gain.value; } - // Interna + setVolume( value ) { - _update( time, deltaTime, timeDirection, accuIndex ) { + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); - // called by the mixer + return this; - if ( ! this.enabled ) { + } - // call ._updateWeight() to update ._effectiveWeight +} - this._updateWeight( time ); - return; +const _position = /*@__PURE__*/ new Vector3(); +const _quaternion = /*@__PURE__*/ new Quaternion(); +const _scale = /*@__PURE__*/ new Vector3(); +const _orientation = /*@__PURE__*/ new Vector3(); - } +class PositionalAudio extends Audio { - const startTime = this._startTime; + constructor( listener ) { - if ( startTime !== null ) { + super( listener ); - // check for scheduled start of action + this.panner = this.context.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.connect( this.gain ); - const timeRunning = ( time - startTime ) * timeDirection; - if ( timeRunning < 0 || timeDirection === 0 ) { + } - return; // yet to come / don't decide when delta = 0 + disconnect() { - } + super.disconnect(); - // start + this.panner.disconnect( this.gain ); - this._startTime = null; // unschedule - deltaTime = timeDirection * timeRunning; + } - } + getOutput() { - // apply time scale and advance time + return this.panner; - deltaTime *= this._updateTimeScale( time ); - const clipTime = this._updateTime( deltaTime ); + } - // note: _updateTime may disable the action resulting in - // an effective weight of 0 + getRefDistance() { - const weight = this._updateWeight( time ); + return this.panner.refDistance; - if ( weight > 0 ) { + } - const interpolants = this._interpolants; - const propertyMixers = this._propertyBindings; + setRefDistance( value ) { - switch ( this.blendMode ) { + this.panner.refDistance = value; - case AdditiveAnimationBlendMode: + return this; - for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + } - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulateAdditive( weight ); + getRolloffFactor() { - } + return this.panner.rolloffFactor; - break; + } - case NormalAnimationBlendMode: - default: + setRolloffFactor( value ) { - for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + this.panner.rolloffFactor = value; - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulate( accuIndex, weight ); + return this; - } + } - } + getDistanceModel() { - } + return this.panner.distanceModel; } - _updateWeight( time ) { - - let weight = 0; - - if ( this.enabled ) { + setDistanceModel( value ) { - weight = this.weight; - const interpolant = this._weightInterpolant; + this.panner.distanceModel = value; - if ( interpolant !== null ) { + return this; - const interpolantValue = interpolant.evaluate( time )[ 0 ]; + } - weight *= interpolantValue; + getMaxDistance() { - if ( time > interpolant.parameterPositions[ 1 ] ) { + return this.panner.maxDistance; - this.stopFading(); + } - if ( interpolantValue === 0 ) { + setMaxDistance( value ) { - // faded out, disable - this.enabled = false; + this.panner.maxDistance = value; - } + return this; - } + } - } + setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { - } + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; - this._effectiveWeight = weight; - return weight; + return this; } - _updateTimeScale( time ) { + updateMatrixWorld( force ) { - let timeScale = 0; + super.updateMatrixWorld( force ); - if ( ! this.paused ) { + if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; - timeScale = this.timeScale; + this.matrixWorld.decompose( _position, _quaternion, _scale ); - const interpolant = this._timeScaleInterpolant; + _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); - if ( interpolant !== null ) { + const panner = this.panner; - const interpolantValue = interpolant.evaluate( time )[ 0 ]; + if ( panner.positionX ) { - timeScale *= interpolantValue; + // code path for Chrome and Firefox (see #14393) - if ( time > interpolant.parameterPositions[ 1 ] ) { + const endTime = this.context.currentTime + this.listener.timeDelta; - this.stopWarping(); + panner.positionX.linearRampToValueAtTime( _position.x, endTime ); + panner.positionY.linearRampToValueAtTime( _position.y, endTime ); + panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); + panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); + panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); + panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); - if ( timeScale === 0 ) { + } else { - // motion has halted, pause - this.paused = true; + panner.setPosition( _position.x, _position.y, _position.z ); + panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); - } else { + } - // warp done - apply final time scale - this.timeScale = timeScale; + } - } +} - } +class AudioAnalyser { - } + constructor( audio, fftSize = 2048 ) { - } + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; - this._effectiveTimeScale = timeScale; - return timeScale; + this.data = new Uint8Array( this.analyser.frequencyBinCount ); + + audio.getOutput().connect( this.analyser ); } - _updateTime( deltaTime ) { - const duration = this._clip.duration; - const loop = this.loop; + getFrequencyData() { - let time = this.time + deltaTime; - let loopCount = this._loopCount; + this.analyser.getByteFrequencyData( this.data ); - const pingPong = ( loop === LoopPingPong ); + return this.data; - if ( deltaTime === 0 ) { + } - if ( loopCount === - 1 ) return time; + getAverageFrequency() { - return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; + let value = 0; + const data = this.getFrequencyData(); + + for ( let i = 0; i < data.length; i ++ ) { + + value += data[ i ]; } - if ( loop === LoopOnce ) { + return value / data.length; - if ( loopCount === - 1 ) { + } - // just started +} - this._loopCount = 0; - this._setEndings( true, true, false ); +class PropertyMixer { - } + constructor( binding, typeName, valueSize ) { - handle_stop: { + this.binding = binding; + this.valueSize = valueSize; - if ( time >= duration ) { + let mixFunction, + mixFunctionAdditive, + setIdentity; - time = duration; + // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] + // + // 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 + // + // 'add' is used for additive cumulative results + // + // 'work' is optional and is only present for quaternion types. It is used + // to store intermediate quaternion multiplication results - } else if ( time < 0 ) { + switch ( typeName ) { - time = 0; + case 'quaternion': + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; - } else { + this.buffer = new Float64Array( valueSize * 6 ); + this._workIndex = 5; + break; - this.time = time; + case 'string': + case 'bool': + mixFunction = this._select; - break handle_stop; + // Use the regular mix function and for additive on these types, + // additive is not relevant for non-numeric types + mixFunctionAdditive = this._select; - } + setIdentity = this._setAdditiveIdentityOther; - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + this.buffer = new Array( valueSize * 5 ); + break; - this.time = time; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime < 0 ? - 1 : 1 - } ); + this.buffer = new Float64Array( valueSize * 5 ); - } + } - } else { // repetitive Repeat or PingPong + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; - if ( loopCount === - 1 ) { + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - // just started + this.useCount = 0; + this.referenceCount = 0; - if ( deltaTime >= 0 ) { + } - loopCount = 0; + // accumulate data in the 'incoming' region into 'accu' + accumulate( accuIndex, weight ) { - this._setEndings( true, this.repetitions === 0, pingPong ); + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place - } else { + const buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride; - // when looping in reverse direction, the initial - // transition through zero counts as a repetition, - // so leave loopCount at -1 + let currentWeight = this.cumulativeWeight; - this._setEndings( this.repetitions === 0, true, pingPong ); + if ( currentWeight === 0 ) { - } + // accuN := incoming * weight - } + for ( let i = 0; i !== stride; ++ i ) { - if ( time >= duration || time < 0 ) { + buffer[ offset + i ] = buffer[ i ]; - // wrap around + } - const loopDelta = Math.floor( time / duration ); // signed - time -= duration * loopDelta; + currentWeight = weight; - loopCount += Math.abs( loopDelta ); + } else { - const pending = this.repetitions - loopCount; + // accuN := accuN + incoming * weight - if ( pending <= 0 ) { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); - // have to stop (switch state, clamp time, fire event) + } - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + this.cumulativeWeight = currentWeight; - time = deltaTime > 0 ? duration : 0; + } - this.time = time; + // accumulate data in the 'incoming' region into 'add' + accumulateAdditive( weight ) { - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime > 0 ? 1 : - 1 - } ); + const buffer = this.buffer, + stride = this.valueSize, + offset = stride * this._addIndex; - } else { + if ( this.cumulativeWeightAdditive === 0 ) { - // keep running + // add = identity - if ( pending === 1 ) { + this._setIdentity(); - // entering the last round + } - const atStart = deltaTime < 0; - this._setEndings( atStart, ! atStart, pingPong ); + // add := add + incoming * weight - } else { + this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); + this.cumulativeWeightAdditive += weight; - this._setEndings( false, false, pingPong ); + } - } + // apply the state of 'accu' to the binding when accus differ + apply( accuIndex ) { - this._loopCount = loopCount; + const stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, - this.time = time; + weight = this.cumulativeWeight, + weightAdditive = this.cumulativeWeightAdditive, - this._mixer.dispatchEvent( { - type: 'loop', action: this, loopDelta: loopDelta - } ); + binding = this.binding; - } + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - } else { + if ( weight < 1 ) { - this.time = time; + // accuN := accuN + original * ( 1 - cumulativeWeight ) - } + const originalValueOffset = stride * this._origIndex; - if ( pingPong && ( loopCount & 1 ) === 1 ) { + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); - // invert time for the "pong round" + } - return duration - time; + if ( weightAdditive > 0 ) { - } + // accuN := accuN + additive accuN + + this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); } - return time; + for ( let i = stride, e = stride + stride; i !== e; ++ i ) { - } + if ( buffer[ i ] !== buffer[ i + stride ] ) { - _setEndings( atStart, atEnd, pingPong ) { + // value has changed -> update scene graph - const settings = this._interpolantSettings; + binding.setValue( buffer, offset ); + break; - if ( pingPong ) { + } - settings.endingStart = ZeroSlopeEnding; - settings.endingEnd = ZeroSlopeEnding; + } - } else { + } - // assuming for LoopOnce atStart == atEnd == true + // remember the state of the bound property and copy it to both accus + saveOriginalState() { - if ( atStart ) { + const binding = this.binding; - settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + const buffer = this.buffer, + stride = this.valueSize, - } else { + originalValueOffset = stride * this._origIndex; - settings.endingStart = WrapAroundEnding; + binding.getValue( buffer, originalValueOffset ); - } + // accu[0..1] := orig -- initially detect changes against the original + for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { - if ( atEnd ) { + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; - settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + } - } else { + // Add to identity for additive + this._setIdentity(); - settings.endingEnd = WrapAroundEnding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - } + } + + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState() { - } + const originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); } - _scheduleFading( duration, weightNow, weightThen ) { + _setAdditiveIdentityNumeric() { - const mixer = this._mixer, now = mixer.time; - let interpolant = this._weightInterpolant; + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; - if ( interpolant === null ) { + for ( let i = startIndex; i < endIndex; i ++ ) { - interpolant = mixer._lendControlInterpolant(); - this._weightInterpolant = interpolant; + this.buffer[ i ] = 0; } - const times = interpolant.parameterPositions, - values = interpolant.sampleValues; + } - times[ 0 ] = now; - values[ 0 ] = weightNow; - times[ 1 ] = now + duration; - values[ 1 ] = weightThen; + _setAdditiveIdentityQuaternion() { - return this; + this._setAdditiveIdentityNumeric(); + this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; } -} + _setAdditiveIdentityOther() { -class AnimationMixer extends EventDispatcher { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; - constructor( root ) { + for ( let i = 0; i < this.valueSize; i ++ ) { - super(); + this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; - this._root = root; - this._initMemoryManager(); - this._accuIndex = 0; - this.time = 0; - this.timeScale = 1.0; + } } - _bindAction( action, prototypeAction ) { - const root = action._localRoot || this._root, - tracks = action._clip.tracks, - nTracks = tracks.length, - bindings = action._propertyBindings, - interpolants = action._interpolants, - rootUuid = root.uuid, - bindingsByRoot = this._bindingsByRootAndName; + // mix functions - let bindingsByName = bindingsByRoot[ rootUuid ]; + _select( buffer, dstOffset, srcOffset, t, stride ) { - if ( bindingsByName === undefined ) { + if ( t >= 0.5 ) { - bindingsByName = {}; - bindingsByRoot[ rootUuid ] = bindingsByName; + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + + } } - for ( let i = 0; i !== nTracks; ++ i ) { + } - const track = tracks[ i ], - trackName = track.name; + _slerp( buffer, dstOffset, srcOffset, t ) { - let binding = bindingsByName[ trackName ]; + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); - if ( binding !== undefined ) { + } - bindings[ i ] = binding; + _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { - } else { + const workOffset = this._workIndex * stride; - binding = bindings[ i ]; + // Store result in intermediate buffer offset + Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); - if ( binding !== undefined ) { + // Slerp to the intermediate result + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); - // existing binding, make sure the cache knows + } - if ( binding._cacheIndex === null ) { + _lerp( buffer, dstOffset, srcOffset, t, stride ) { - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + const s = 1 - t; - } + for ( let i = 0; i !== stride; ++ i ) { - continue; + const j = dstOffset + i; - } + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; - const path = prototypeAction && prototypeAction. - _propertyBindings[ i ].binding.parsedPath; + } - binding = new PropertyMixer( - PropertyBinding.create( root, trackName, path ), - track.ValueTypeName, track.getValueSize() ); + } - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { - bindings[ i ] = binding; + for ( let i = 0; i !== stride; ++ i ) { - } + const j = dstOffset + i; - interpolants[ i ].resultBuffer = binding.buffer; + buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; } } - _activateAction( action ) { +} - if ( ! this._isActiveAction( action ) ) { +// Characters [].:/ are reserved for track binding syntax. +const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; +const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); - if ( action._cacheIndex === null ) { +// Attempts to allow node names from any language. ES5's `\w` regexp matches +// only latin characters, and the unicode \p{L} is not yet supported. So +// instead, we exclude reserved characters and match everything else. +const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; +const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; - // this action has been forgotten by the cache, but the user - // appears to be still using it -> rebind +// Parent directories, delimited by '/' or ':'. Currently unused, but must +// be matched to parse the rest of the track name. +const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); - const rootUuid = ( action._localRoot || this._root ).uuid, - clipUuid = action._clip.uuid, - actionsForClip = this._actionsByClip[ clipUuid ]; +// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. +const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); - this._bindAction( action, - actionsForClip && actionsForClip.knownActions[ 0 ] ); +// Object on target node, and accessor. May not contain reserved +// characters. Accessor may contain any character except closing bracket. +const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); - this._addInactiveAction( action, clipUuid, rootUuid ); +// Property and accessor. May not contain reserved characters. Accessor may +// contain any non-bracket characters. +const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); - } +const _trackRe = new RegExp( '' + + '^' + + _directoryRe + + _nodeRe + + _objectRe + + _propertyRe + + '$' +); - const bindings = action._propertyBindings; +const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ]; - // increment reference counts / sort out state - for ( let i = 0, n = bindings.length; i !== n; ++ i ) { +class Composite { - const binding = bindings[ i ]; + constructor( targetGroup, path, optionalParsedPath ) { - if ( binding.useCount ++ === 0 ) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); - this._lendBinding( binding ); - binding.saveOriginalState(); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); - } + } - } + getValue( array, offset ) { - this._lendAction( action ); + this.bind(); // bind all binding - } + const firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; + + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); } - _deactivateAction( action ) { + setValue( array, offset ) { - if ( this._isActiveAction( action ) ) { + const bindings = this._bindings; - const bindings = action._propertyBindings; + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { - // decrement reference counts / sort out state - for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + bindings[ i ].setValue( array, offset ); - const binding = bindings[ i ]; + } - if ( -- binding.useCount === 0 ) { + } - binding.restoreOriginalState(); - this._takeBackBinding( binding ); + bind() { - } + const bindings = this._bindings; - } + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { - this._takeBackAction( action ); + bindings[ i ].bind(); } } - // Memory manager - - _initMemoryManager() { + unbind() { - this._actions = []; // 'nActiveActions' followed by inactive ones - this._nActiveActions = 0; + const bindings = this._bindings; - this._actionsByClip = {}; - // inside: - // { - // knownActions: Array< AnimationAction > - used as prototypes - // actionByRoot: AnimationAction - lookup - // } + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + bindings[ i ].unbind(); - this._bindings = []; // 'nActiveBindings' followed by inactive ones - this._nActiveBindings = 0; + } - this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + } +} - this._controlInterpolants = []; // same game as above - this._nActiveControlInterpolants = 0; +// 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. +class PropertyBinding { - const scope = this; + constructor( rootNode, path, parsedPath ) { - this.stats = { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); - actions: { - get total() { + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; - return scope._actions.length; + this.rootNode = rootNode; - }, - get inUse() { + // initial state of these methods that calls 'bind' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; - return scope._nActiveActions; + } - } - }, - bindings: { - get total() { - return scope._bindings.length; + static create( root, path, parsedPath ) { - }, - get inUse() { + if ( ! ( root && root.isAnimationObjectGroup ) ) { - return scope._nActiveBindings; + return new PropertyBinding( root, path, parsedPath ); - } - }, - controlInterpolants: { - get total() { + } else { - return scope._controlInterpolants.length; + return new PropertyBinding.Composite( root, path, parsedPath ); - }, - get inUse() { + } - return scope._nActiveControlInterpolants; + } - } - } + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name Node name to be sanitized. + * @return {string} + */ + static sanitizeNodeName( name ) { - }; + return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); } - // Memory management for AnimationAction objects - - _isActiveAction( action ) { + static parseTrackName( trackName ) { - const index = action._cacheIndex; - return index !== null && index < this._nActiveActions; + const matches = _trackRe.exec( trackName ); - } + if ( matches === null ) { - _addInactiveAction( action, clipUuid, rootUuid ) { + throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); - const actions = this._actions, - actionsByClip = this._actionsByClip; + } - let actionsForClip = actionsByClip[ clipUuid ]; + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; - if ( actionsForClip === undefined ) { + const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); - actionsForClip = { + if ( lastDot !== undefined && lastDot !== - 1 ) { - knownActions: [ action ], - actionByRoot: {} + const objectName = results.nodeName.substring( lastDot + 1 ); - }; + // Object names must be checked against an allowlist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { - action._byClipCacheIndex = 0; + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; - actionsByClip[ clipUuid ] = actionsForClip; + } - } else { + } - const knownActions = actionsForClip.knownActions; + if ( results.propertyName === null || results.propertyName.length === 0 ) { - action._byClipCacheIndex = knownActions.length; - knownActions.push( action ); + throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); } - action._cacheIndex = actions.length; - actions.push( action ); - - actionsForClip.actionByRoot[ rootUuid ] = action; + return results; } - _removeInactiveAction( action ) { + static findNode( root, nodeName ) { - const actions = this._actions, - lastInactiveAction = actions[ actions.length - 1 ], - cacheIndex = action._cacheIndex; + if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + return root; - action._cacheIndex = null; + } + // search into skeleton bones. + if ( root.skeleton ) { - const clipUuid = action._clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ], - knownActionsForClip = actionsForClip.knownActions, + const bone = root.skeleton.getBoneByName( nodeName ); - lastKnownAction = - knownActionsForClip[ knownActionsForClip.length - 1 ], + if ( bone !== undefined ) { - byClipCacheIndex = action._byClipCacheIndex; + return bone; - lastKnownAction._byClipCacheIndex = byClipCacheIndex; - knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; - knownActionsForClip.pop(); + } - action._byClipCacheIndex = null; + } + // search into node subtree. + if ( root.children ) { - const actionByRoot = actionsForClip.actionByRoot, - rootUuid = ( action._localRoot || this._root ).uuid; + const searchNodeSubtree = function ( children ) { - delete actionByRoot[ rootUuid ]; + for ( let i = 0; i < children.length; i ++ ) { - if ( knownActionsForClip.length === 0 ) { + const childNode = children[ i ]; - delete actionsByClip[ clipUuid ]; + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { - } + return childNode; - this._removeInactiveBindingsForAction( action ); + } - } + const result = searchNodeSubtree( childNode.children ); - _removeInactiveBindingsForAction( action ) { + if ( result ) return result; - const bindings = action._propertyBindings; + } - for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + return null; - const binding = bindings[ i ]; + }; - if ( -- binding.referenceCount === 0 ) { + const subTreeNode = searchNodeSubtree( root.children ); - this._removeInactiveBinding( binding ); + if ( subTreeNode ) { + + return subTreeNode; } } - } - - _lendAction( action ) { - - // [ active actions | inactive actions ] - // [ active actions >| inactive actions ] - // s a - // <-swap-> - // a s + return null; - const actions = this._actions, - prevIndex = action._cacheIndex, + } - lastActiveIndex = this._nActiveActions ++, + // these are used to "bind" a nonexistent property + _getValue_unavailable() {} + _setValue_unavailable() {} - firstInactiveAction = actions[ lastActiveIndex ]; + // Getters - action._cacheIndex = lastActiveIndex; - actions[ lastActiveIndex ] = action; + _getValue_direct( buffer, offset ) { - firstInactiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = firstInactiveAction; + buffer[ offset ] = this.targetObject[ this.propertyName ]; } - _takeBackAction( action ) { + _getValue_array( buffer, offset ) { - // [ active actions | inactive actions ] - // [ active actions |< inactive actions ] - // a s - // <-swap-> - // s a + const source = this.resolvedProperty; - const actions = this._actions, - prevIndex = action._cacheIndex, + for ( let i = 0, n = source.length; i !== n; ++ i ) { - firstInactiveIndex = -- this._nActiveActions, + buffer[ offset ++ ] = source[ i ]; - lastActiveAction = actions[ firstInactiveIndex ]; + } - action._cacheIndex = firstInactiveIndex; - actions[ firstInactiveIndex ] = action; + } - lastActiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = lastActiveAction; + _getValue_arrayElement( buffer, offset ) { + + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; } - // Memory management for PropertyMixer objects + _getValue_toArray( buffer, offset ) { - _addInactiveBinding( binding, rootUuid, trackName ) { + this.resolvedProperty.toArray( buffer, offset ); - const bindingsByRoot = this._bindingsByRootAndName, - bindings = this._bindings; + } - let bindingByName = bindingsByRoot[ rootUuid ]; + // Direct - if ( bindingByName === undefined ) { + _setValue_direct( buffer, offset ) { - bindingByName = {}; - bindingsByRoot[ rootUuid ] = bindingByName; + this.targetObject[ this.propertyName ] = buffer[ offset ]; - } + } - bindingByName[ trackName ] = binding; + _setValue_direct_setNeedsUpdate( buffer, offset ) { - binding._cacheIndex = bindings.length; - bindings.push( binding ); + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; } - _removeInactiveBinding( binding ) { + _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - const bindings = this._bindings, - propBinding = binding.binding, - rootUuid = propBinding.rootNode.uuid, - trackName = propBinding.path, - bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - lastInactiveBinding = bindings[ bindings.length - 1 ], - cacheIndex = binding._cacheIndex; + } - lastInactiveBinding._cacheIndex = cacheIndex; - bindings[ cacheIndex ] = lastInactiveBinding; - bindings.pop(); + // EntireArray - delete bindingByName[ trackName ]; + _setValue_array( buffer, offset ) { - if ( Object.keys( bindingByName ).length === 0 ) { + const dest = this.resolvedProperty; - delete bindingsByRoot[ rootUuid ]; + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; } } - _lendBinding( binding ) { + _setValue_array_setNeedsUpdate( buffer, offset ) { - const bindings = this._bindings, - prevIndex = binding._cacheIndex, + const dest = this.resolvedProperty; - lastActiveIndex = this._nActiveBindings ++, + for ( let i = 0, n = dest.length; i !== n; ++ i ) { - firstInactiveBinding = bindings[ lastActiveIndex ]; + dest[ i ] = buffer[ offset ++ ]; - binding._cacheIndex = lastActiveIndex; - bindings[ lastActiveIndex ] = binding; + } - firstInactiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = firstInactiveBinding; + this.targetObject.needsUpdate = true; } - _takeBackBinding( binding ) { + _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { - const bindings = this._bindings, - prevIndex = binding._cacheIndex, + const dest = this.resolvedProperty; - firstInactiveIndex = -- this._nActiveBindings, + for ( let i = 0, n = dest.length; i !== n; ++ i ) { - lastActiveBinding = bindings[ firstInactiveIndex ]; + dest[ i ] = buffer[ offset ++ ]; - binding._cacheIndex = firstInactiveIndex; - bindings[ firstInactiveIndex ] = binding; + } - lastActiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = lastActiveBinding; + this.targetObject.matrixWorldNeedsUpdate = true; } + // ArrayElement - // Memory management of Interpolants for weight and time scale - - _lendControlInterpolant() { - - const interpolants = this._controlInterpolants, - lastActiveIndex = this._nActiveControlInterpolants ++; - - let interpolant = interpolants[ lastActiveIndex ]; - - if ( interpolant === undefined ) { + _setValue_arrayElement( buffer, offset ) { - interpolant = new LinearInterpolant( - new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - interpolant.__cacheIndex = lastActiveIndex; - interpolants[ lastActiveIndex ] = interpolant; + } - } + _setValue_arrayElement_setNeedsUpdate( buffer, offset ) { - return interpolant; + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; } - _takeBackControlInterpolant( interpolant ) { + _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { - const interpolants = this._controlInterpolants, - prevIndex = interpolant.__cacheIndex, + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - firstInactiveIndex = -- this._nActiveControlInterpolants, + } - lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + // HasToFromArray - interpolant.__cacheIndex = firstInactiveIndex; - interpolants[ firstInactiveIndex ] = interpolant; + _setValue_fromArray( buffer, offset ) { - lastActiveInterpolant.__cacheIndex = prevIndex; - interpolants[ prevIndex ] = lastActiveInterpolant; + this.resolvedProperty.fromArray( buffer, offset ); } - // 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( clip, optionalRoot, blendMode ) { - - const root = optionalRoot || this._root, - rootUuid = root.uuid; + _setValue_fromArray_setNeedsUpdate( buffer, offset ) { - let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; - const clipUuid = clipObject !== null ? clipObject.uuid : clip; + } - const actionsForClip = this._actionsByClip[ clipUuid ]; - let prototypeAction = null; + _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { - if ( blendMode === undefined ) { + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; - if ( clipObject !== null ) { + } - blendMode = clipObject.blendMode; + _getValue_unbound( targetArray, offset ) { - } else { + this.bind(); + this.getValue( targetArray, offset ); - blendMode = NormalAnimationBlendMode; + } - } + _setValue_unbound( sourceArray, offset ) { - } + this.bind(); + this.setValue( sourceArray, offset ); - if ( actionsForClip !== undefined ) { + } - const existingAction = actionsForClip.actionByRoot[ rootUuid ]; + // create getter / setter pair for a property in the scene graph + bind() { - if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { + let targetObject = this.node; + const parsedPath = this.parsedPath; - return existingAction; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; - } + if ( ! targetObject ) { - // we know the clip, so we don't have to parse all - // the bindings again but can just copy - prototypeAction = actionsForClip.knownActions[ 0 ]; + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; - // also, take the clip from the prototype action - if ( clipObject === null ) - clipObject = prototypeAction._clip; + this.node = targetObject; } - // clip must be known when specified via string - if ( clipObject === null ) return null; - - // allocate all resources required to run it - const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); - - this._bindAction( newAction, prototypeAction ); + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; - // and make the action known to the memory manager - this._addInactiveAction( newAction, clipUuid, rootUuid ); + // ensure there is a value node + if ( ! targetObject ) { - return newAction; + console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); + return; - } + } - // get an existing action - existingAction( clip, optionalRoot ) { + if ( objectName ) { - const root = optionalRoot || this._root, - rootUuid = root.uuid, + let objectIndex = parsedPath.objectIndex; - clipObject = typeof clip === 'string' ? - AnimationClip.findByName( root, clip ) : clip, + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { - clipUuid = clipObject ? clipObject.uuid : clip, + case 'materials': - actionsForClip = this._actionsByClip[ clipUuid ]; + if ( ! targetObject.material ) { - if ( actionsForClip !== undefined ) { + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; - return actionsForClip.actionByRoot[ rootUuid ] || null; + } - } + if ( ! targetObject.material.materials ) { - return null; + console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); + return; - } + } - // deactivates all previously scheduled actions - stopAllAction() { + targetObject = targetObject.material.materials; - const actions = this._actions, - nActions = this._nActiveActions; + break; - for ( let i = nActions - 1; i >= 0; -- i ) { + case 'bones': - actions[ i ].stop(); + if ( ! targetObject.skeleton ) { - } + console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); + return; - return this; + } - } + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. - // advance the time and update apply the animation - update( deltaTime ) { + targetObject = targetObject.skeleton.bones; - deltaTime *= this.timeScale; + // support resolving morphTarget names into indices. + for ( let i = 0; i < targetObject.length; i ++ ) { - const actions = this._actions, - nActions = this._nActiveActions, + if ( targetObject[ i ].name === objectIndex ) { - time = this.time += deltaTime, - timeDirection = Math.sign( deltaTime ), + objectIndex = i; + break; - accuIndex = this._accuIndex ^= 1; + } - // run active actions + } - for ( let i = 0; i !== nActions; ++ i ) { + break; - const action = actions[ i ]; + case 'map': - action._update( time, deltaTime, timeDirection, accuIndex ); + if ( ! targetObject.material ) { - } + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; - // update scene graph + } - const bindings = this._bindings, - nBindings = this._nActiveBindings; + if ( ! targetObject.material.map ) { - for ( let i = 0; i !== nBindings; ++ i ) { + console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this ); + return; - bindings[ i ].apply( accuIndex ); + } - } + targetObject = targetObject.material.map; + break; - return this; + default: - } + if ( targetObject[ objectName ] === undefined ) { - // Allows you to seek to a specific time in an animation. - setTime( timeInSeconds ) { + console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); + return; - this.time = 0; // Zero out time attribute for AnimationMixer object; - for ( let i = 0; i < this._actions.length; i ++ ) { + } - this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + targetObject = targetObject[ objectName ]; - } + } - return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. - } + if ( objectIndex !== undefined ) { - // return this mixer's root target object - getRoot() { + if ( targetObject[ objectIndex ] === undefined ) { - return this._root; + console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); + return; - } + } - // free all resources specific to a particular clip - uncacheClip( clip ) { + targetObject = targetObject[ objectIndex ]; - const actions = this._actions, - clipUuid = clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + } - if ( actionsForClip !== undefined ) { + } - // note: just calling _removeInactiveAction would mess up the - // iteration state and also require updating the state we can - // just throw away + // resolve property + const nodeProperty = targetObject[ propertyName ]; - const actionsToRemove = actionsForClip.knownActions; + if ( nodeProperty === undefined ) { - for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + const nodeName = parsedPath.nodeName; - const action = actionsToRemove[ i ]; + console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + + '.' + propertyName + ' but it wasn\'t found.', targetObject ); + return; - this._deactivateAction( action ); + } - const cacheIndex = action._cacheIndex, - lastInactiveAction = actions[ actions.length - 1 ]; + // determine versioning scheme + let versioning = this.Versioning.None; - action._cacheIndex = null; - action._byClipCacheIndex = null; + this.targetObject = targetObject; - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + if ( targetObject.needsUpdate !== undefined ) { // material - this._removeInactiveBindingsForAction( action ); + versioning = this.Versioning.NeedsUpdate; - } + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform - delete actionsByClip[ clipUuid ]; + versioning = this.Versioning.MatrixWorldNeedsUpdate; } - } - - // free all resources specific to a particular root target object - uncacheRoot( root ) { - - const rootUuid = root.uuid, - actionsByClip = this._actionsByClip; + // determine how the property gets bound + let bindingType = this.BindingType.Direct; - for ( const clipUuid in actionsByClip ) { + if ( propertyIndex !== undefined ) { - const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, - action = actionByRoot[ rootUuid ]; + // access a sub element of the property array (only primitives are supported right now) - if ( action !== undefined ) { + if ( propertyName === 'morphTargetInfluences' ) { - this._deactivateAction( action ); - this._removeInactiveAction( action ); + // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. - } + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { - } + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); + return; - const bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ]; + } - if ( bindingByName !== undefined ) { + if ( ! targetObject.geometry.morphAttributes ) { - for ( const trackName in bindingByName ) { + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; - const binding = bindingByName[ trackName ]; - binding.restoreOriginalState(); - this._removeInactiveBinding( binding ); + } - } + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { - } + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; - } + } - // remove a targeted clip from the cache - uncacheAction( clip, optionalRoot ) { + } - const action = this.existingAction( clip, optionalRoot ); + bindingType = this.BindingType.ArrayElement; - if ( action !== null ) { + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; - this._deactivateAction( action ); - this._removeInactiveAction( action ); + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { - } + // must use copy for Object3D.Euler/Quaternion - } + bindingType = this.BindingType.HasFromToArray; -} + this.resolvedProperty = nodeProperty; -AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 ); + } else if ( Array.isArray( nodeProperty ) ) { -class Uniform { + bindingType = this.BindingType.EntireArray; - constructor( value ) { + this.resolvedProperty = nodeProperty; - if ( typeof value === 'string' ) { + } else { - console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); - value = arguments[ 1 ]; + this.propertyName = propertyName; } - this.value = value; + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; } - clone() { + unbind() { - return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); + 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; } } -function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) { - - InterleavedBuffer.call( this, array, stride ); +PropertyBinding.Composite = Composite; - this.meshPerAttribute = meshPerAttribute || 1; - -} +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; -InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), { +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; - constructor: InstancedInterleavedBuffer, +PropertyBinding.prototype.GetterByBindingType = [ - isInstancedInterleavedBuffer: true, + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray, - copy: function ( source ) { +]; - InterleavedBuffer.prototype.copy.call( this, source ); +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ - this.meshPerAttribute = source.meshPerAttribute; + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate, - return this; + ], [ - }, + // EntireArray - clone: function ( data ) { + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate, - const ib = InterleavedBuffer.prototype.clone.call( this, data ); + ], [ - ib.meshPerAttribute = this.meshPerAttribute; + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate, - return ib; + ], [ - }, + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate, - toJSON: function ( data ) { + ] - const json = InterleavedBuffer.prototype.toJSON.call( this, data ); +]; - json.isInstancedInterleavedBuffer = true; - json.meshPerAttribute = this.meshPerAttribute; +/** + * + * 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. + */ - return json; +class AnimationObjectGroup { - } + constructor() { -} ); + this.isAnimationObjectGroup = true; -function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) { + this.uuid = generateUUID(); - this.buffer = buffer; - this.type = type; - this.itemSize = itemSize; - this.elementSize = elementSize; - this.count = count; + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); - this.version = 0; + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite -} + const indices = {}; + this._indicesByUUID = indices; // for bookkeeping -Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', { + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { - set: function ( value ) { + indices[ arguments[ i ].uuid ] = i; - if ( value === true ) this.version ++; + } - } + this._paths = []; // inside: string + this._parsedPaths = []; // inside: { we don't care, here } + this._bindings = []; // inside: Array< PropertyBinding > + this._bindingsIndicesByPath = {}; // inside: indices in these arrays -} ); + const scope = this; -Object.assign( GLBufferAttribute.prototype, { + this.stats = { - isGLBufferAttribute: true, + objects: { + get total() { - setBuffer: function ( buffer ) { + return scope._objects.length; - this.buffer = buffer; + }, + get inUse() { - return this; + return this.total - scope.nCachedObjects_; - }, + } + }, + get bindingsPerObject() { - setType: function ( type, elementSize ) { + return scope._bindings.length; - this.type = type; - this.elementSize = elementSize; + } - return this; + }; - }, + } - setItemSize: function ( itemSize ) { + add() { - this.itemSize = itemSize; + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; - return this; + let knownObject = undefined, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_; - }, + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { - setCount: function ( count ) { + const object = arguments[ i ], + uuid = object.uuid; + let index = indicesByUUID[ uuid ]; - this.count = count; + if ( index === undefined ) { - return this; + // 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 -function Raycaster( origin, direction, near = 0, far = Infinity ) { + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - this.ray = new Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); - this.near = near; - this.far = far; - this.camera = null; - this.layers = new Layers(); + } - this.params = { - Mesh: {}, - Line: { threshold: 1 }, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; + } else if ( index < nCachedObjects ) { - Object.defineProperties( this.params, { - PointCloud: { - get: function () { + knownObject = objects[ index ]; - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; + // move existing object to the ACTIVE region - } - } - } ); + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; -} + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; -function ascSort( a, b ) { + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; - return a.distance - b.distance; + // accounting is done, now do the same for all bindings -} + for ( let j = 0, m = nBindings; j !== m; ++ j ) { -function intersectObject( object, raycaster, intersects, recursive ) { + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ]; - if ( object.layers.test( raycaster.layers ) ) { + let binding = bindingsForPath[ index ]; - object.raycast( raycaster, intersects ); + bindingsForPath[ index ] = lastCached; - } + if ( binding === undefined ) { - if ( recursive === true ) { + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist - const children = object.children; + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); - for ( let i = 0, l = children.length; i < l; i ++ ) { + } - intersectObject( children[ i ], raycaster, intersects, true ); + bindingsForPath[ firstActiveIndex ] = binding; - } + } - } + } else if ( objects[ index ] !== knownObject ) { -} + console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); -Object.assign( Raycaster.prototype, { + } // else the object is already where we want it to be - set: function ( origin, direction ) { + } // for arguments - // direction is assumed to be normalized (for accurate distance calculations) + this.nCachedObjects_ = nCachedObjects; - this.ray.set( origin, direction ); + } - }, + remove() { - setFromCamera: function ( coords, camera ) { + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - if ( camera && camera.isPerspectiveCamera ) { + let nCachedObjects = this.nCachedObjects_; - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - this.camera = camera; + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { - } else if ( camera && camera.isOrthographicCamera ) { + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - 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 ); - this.camera = camera; + if ( index !== undefined && index >= nCachedObjects ) { - } else { + // move existing object into the CACHED region - console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); + const lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; - } + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; - }, + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; - intersectObject: function ( object, recursive = false, intersects = [] ) { + // accounting is done, now do the same for all bindings - intersectObject( object, this, intersects, recursive ); + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - intersects.sort( ascSort ); + const bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; - return intersects; + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; - }, + } - intersectObjects: function ( objects, recursive = false, intersects = [] ) { + } - for ( let i = 0, l = objects.length; i < l; i ++ ) { + } // for arguments - intersectObject( objects[ i ], this, intersects, recursive ); + this.nCachedObjects_ = nCachedObjects; - } + } - intersects.sort( ascSort ); + // remove & forget + uncache() { - return intersects; + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - } + let nCachedObjects = this.nCachedObjects_, + nObjects = objects.length; -} ); + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { -/** - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. - * The azimuthal angle (theta) is measured from the positive z-axis. - */ + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; -class Spherical { + if ( index !== undefined ) { - constructor( radius = 1, phi = 0, theta = 0 ) { + delete indicesByUUID[ uuid ]; - this.radius = radius; - this.phi = phi; // polar angle - this.theta = theta; // azimuthal angle + if ( index < nCachedObjects ) { - return this; + // object is cached, shrink the CACHED region - } + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - set( radius, phi, theta ) { + // last cached object takes this object's place + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - this.radius = radius; - this.phi = phi; - this.theta = theta; + // last object goes to the activated slot and pop + indicesByUUID[ lastObject.uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = lastObject; + objects.pop(); - return this; + // accounting is done, now do the same for all bindings - } + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - copy( other ) { + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; - this.radius = other.radius; - this.phi = other.phi; - this.theta = other.theta; + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); - return this; + } - } + } else { - // restrict phi to be betwee EPS and PI-EPS - makeSafe() { + // object is active, just swap with the last and pop - const EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + const lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - return this; + if ( lastIndex > 0 ) { - } + indicesByUUID[ lastObject.uuid ] = index; - setFromVector3( v ) { + } - return this.setFromCartesianCoords( v.x, v.y, v.z ); + objects[ index ] = lastObject; + objects.pop(); - } + // accounting is done, now do the same for all bindings - setFromCartesianCoords( x, y, z ) { + for ( let j = 0, m = nBindings; j !== m; ++ j ) { - this.radius = Math.sqrt( x * x + y * y + z * z ); + const bindingsForPath = bindings[ j ]; - if ( this.radius === 0 ) { + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); - this.theta = 0; - this.phi = 0; + } - } else { + } // cached or active - this.theta = Math.atan2( x, z ); - this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) ); + } // if object is known - } + } // for arguments - return this; + this.nCachedObjects_ = nCachedObjects; } - clone() { + // Internal interface used by befriended PropertyBinding.Composite: - return new this.constructor().copy( this ); + subscribe_( path, parsedPath ) { - } + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group -} + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[ path ]; + const bindings = this._bindings; -/** - * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system - */ + if ( index !== undefined ) return bindings[ index ]; -class Cylindrical { + const paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); - constructor( radius = 1, theta = 0, y = 0 ) { + index = bindings.length; - this.radius = radius; // distance from the origin to a point in the x-z plane - this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis - this.y = y; // height above the x-z plane + indicesByPath[ path ] = index; - return this; + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); - } + for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { - set( radius, theta, y ) { + const object = objects[ i ]; + bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); - this.radius = radius; - this.theta = theta; - this.y = y; + } - return this; + return bindingsForPath; } - copy( other ) { - - this.radius = other.radius; - this.theta = other.theta; - this.y = other.y; - - return this; - - } + unsubscribe_( path ) { - setFromVector3( v ) { + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' - return this.setFromCartesianCoords( v.x, v.y, v.z ); + const indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; - } + if ( index !== undefined ) { - setFromCartesianCoords( x, y, z ) { + const paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; - this.radius = Math.sqrt( x * x + z * z ); - this.theta = Math.atan2( x, z ); - this.y = y; + indicesByPath[ lastBindingsPath ] = index; - return this; + bindings[ index ] = lastBindings; + bindings.pop(); - } + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); - clone() { + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); - return new this.constructor().copy( this ); + } } } -const _vector$8 = /*@__PURE__*/ new Vector2(); +class AnimationAction { -class Box2 { + constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { - constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; - this.min = min; - this.max = max; + const tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); - } + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; - set( min, max ) { + for ( let i = 0; i !== nTracks; ++ i ) { - this.min.copy( min ); - this.max.copy( max ); + const interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; - return this; + } - } + this._interpolantSettings = interpolantSettings; - setFromPoints( points ) { + this._interpolants = interpolants; // bound by the mixer - this.makeEmpty(); + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); - for ( let i = 0, il = points.length; i < il; i ++ ) { + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager - this.expandByPoint( points[ i ] ); + this._timeScaleInterpolant = null; + this._weightInterpolant = null; - } + this.loop = LoopRepeat; + this._loopCount = - 1; - return this; + // 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; - setFromCenterAndSize( center, size ) { + this.timeScale = 1; + this._effectiveTimeScale = 1; - const halfSize = _vector$8.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + this.weight = 1; + this._effectiveWeight = 1; - return this; + this.repetitions = Infinity; // no. of repetitions when looping - } + this.paused = false; // true -> zero effective time scale + this.enabled = true; // false -> zero effective weight - clone() { + this.clampWhenFinished = false;// keep feeding the last frame? - return new this.constructor().copy( this ); + this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true;// clips for start, loop and end } - copy( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - } + // State & Scheduling - makeEmpty() { + play() { - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; + this._mixer._activateAction( this ); return this; } - isEmpty() { + stop() { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + this._mixer._deactivateAction( this ); - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + return this.reset(); } - getCenter( target ) { - - if ( target === undefined ) { + reset() { - console.warn( 'THREE.Box2: .getCenter() target is now required' ); - target = new Vector2(); + this.paused = false; + this.enabled = true; - } + this.time = 0; // restart clip + this._loopCount = - 1;// forget previous loops + this._startTime = null;// forget scheduling - return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + return this.stopFading().stopWarping(); } - getSize( target ) { + isRunning() { - if ( target === undefined ) { + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); - console.warn( 'THREE.Box2: .getSize() target is now required' ); - target = new Vector2(); + } - } + // return true when play has been called + isScheduled() { - return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + return this._mixer._isActiveAction( this ); } - expandByPoint( point ) { + startAt( time ) { - this.min.min( point ); - this.max.max( point ); + this._startTime = time; return this; } - expandByVector( vector ) { + setLoop( mode, repetitions ) { - this.min.sub( vector ); - this.max.add( vector ); + this.loop = mode; + this.repetitions = repetitions; return this; } - expandByScalar( scalar ) { - - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + // Weight - return this; + // 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( weight ) { - } + this.weight = weight; - containsPoint( point ) { + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ? false : true; + return this.stopFading(); } - containsBox( box ) { + // return the weight considering fading and .enabled + getEffectiveWeight() { - return 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._effectiveWeight; } - getParameter( point, target ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + fadeIn( duration ) { - if ( target === undefined ) { + return this._scheduleFading( duration, 0, 1 ); - console.warn( 'THREE.Box2: .getParameter() target is now required' ); - target = new Vector2(); + } - } + fadeOut( duration ) { - return target.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._scheduleFading( duration, 1, 0 ); } - intersectsBox( box ) { - - // using 4 splitting planes to rule out intersections + crossFadeFrom( fadeOutAction, duration, warp ) { - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); - } + if ( warp ) { - clampPoint( point, target ) { + const fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, - if ( target === undefined ) { + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; - console.warn( 'THREE.Box2: .clampPoint() target is now required' ); - target = new Vector2(); + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); } - return target.copy( point ).clamp( this.min, this.max ); + return this; } - distanceToPoint( point ) { + crossFadeTo( fadeInAction, duration, warp ) { - const clampedPoint = _vector$8.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + return fadeInAction.crossFadeFrom( this, duration, warp ); } - intersect( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); + stopFading() { - return this; + const weightInterpolant = this._weightInterpolant; - } + if ( weightInterpolant !== null ) { - union( box ) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); - this.min.min( box.min ); - this.max.max( box.max ); + } return this; } - translate( offset ) { - - this.min.add( offset ); - this.max.add( offset ); - - return this; + // Time Scale Control - } + // set the time scale 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( timeScale ) { - equals( box ) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; - return box.min.equals( this.min ) && box.max.equals( this.max ); + return this.stopWarping(); } -} - -Box2.prototype.isBox2 = true; - -const _startP = /*@__PURE__*/ new Vector3(); -const _startEnd = /*@__PURE__*/ new Vector3(); - -class Line3 { - - constructor( start = new Vector3(), end = new Vector3() ) { + // return the time scale considering warping and .paused + getEffectiveTimeScale() { - this.start = start; - this.end = end; + return this._effectiveTimeScale; } - set( start, end ) { + setDuration( duration ) { - this.start.copy( start ); - this.end.copy( end ); + this.timeScale = this._clip.duration / duration; - return this; + return this.stopWarping(); } - copy( line ) { + syncWith( action ) { - this.start.copy( line.start ); - this.end.copy( line.end ); + this.time = action.time; + this.timeScale = action.timeScale; - return this; + return this.stopWarping(); } - getCenter( target ) { - - if ( target === undefined ) { + halt( duration ) { - console.warn( 'THREE.Line3: .getCenter() target is now required' ); - target = new Vector3(); + return this.warp( this._effectiveTimeScale, 0, duration ); - } + } - return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + warp( startTimeScale, endTimeScale, duration ) { - } + const mixer = this._mixer, + now = mixer.time, + timeScale = this.timeScale; - delta( target ) { + let interpolant = this._timeScaleInterpolant; - if ( target === undefined ) { + if ( interpolant === null ) { - console.warn( 'THREE.Line3: .delta() target is now required' ); - target = new Vector3(); + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; } - return target.subVectors( this.end, this.start ); + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; - } + times[ 0 ] = now; + times[ 1 ] = now + duration; - distanceSq() { + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; - return this.start.distanceToSquared( this.end ); + return this; } - distance() { - - return this.start.distanceTo( this.end ); - - } + stopWarping() { - at( t, target ) { + const timeScaleInterpolant = this._timeScaleInterpolant; - if ( target === undefined ) { + if ( timeScaleInterpolant !== null ) { - console.warn( 'THREE.Line3: .at() target is now required' ); - target = new Vector3(); + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); } - return this.delta( target ).multiplyScalar( t ).add( this.start ); + return this; } - closestPointToPointParameter( point, clampToLine ) { - - _startP.subVectors( point, this.start ); - _startEnd.subVectors( this.end, this.start ); - - const startEnd2 = _startEnd.dot( _startEnd ); - const startEnd_startP = _startEnd.dot( _startP ); - - let t = startEnd_startP / startEnd2; - - if ( clampToLine ) { - - t = MathUtils.clamp( t, 0, 1 ); + // Object Accessors - } + getMixer() { - return t; + return this._mixer; } - closestPointToPoint( point, clampToLine, target ) { - - const t = this.closestPointToPointParameter( point, clampToLine ); + getClip() { - if ( target === undefined ) { + return this._clip; - console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' ); - target = new Vector3(); + } - } + getRoot() { - return this.delta( target ).multiplyScalar( t ).add( this.start ); + return this._localRoot || this._mixer._root; } - applyMatrix4( matrix ) { - - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); - - return this; + // Interna - } + _update( time, deltaTime, timeDirection, accuIndex ) { - equals( line ) { + // called by the mixer - return line.start.equals( this.start ) && line.end.equals( this.end ); + if ( ! this.enabled ) { - } + // call ._updateWeight() to update ._effectiveWeight - clone() { + this._updateWeight( time ); + return; - return new this.constructor().copy( this ); + } - } + const startTime = this._startTime; -} + if ( startTime !== null ) { -function ImmediateRenderObject( material ) { + // check for scheduled start of action - Object3D.call( this ); + const timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { - this.material = material; - this.render = function ( /* renderCallback */ ) {}; + deltaTime = 0; - this.hasPositions = false; - this.hasNormals = false; - this.hasColors = false; - this.hasUvs = false; + } else { - this.positionArray = null; - this.normalArray = null; - this.colorArray = null; - this.uvArray = null; - this.count = 0; + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; -} + } -ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); -ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + } -ImmediateRenderObject.prototype.isImmediateRenderObject = true; + // apply time scale and advance time -const _vector$9 = /*@__PURE__*/ new Vector3(); + deltaTime *= this._updateTimeScale( time ); + const clipTime = this._updateTime( deltaTime ); -class SpotLightHelper extends Object3D { + // note: _updateTime may disable the action resulting in + // an effective weight of 0 - constructor( light, color ) { + const weight = this._updateWeight( time ); - super(); - this.light = light; - this.light.updateMatrixWorld(); + if ( weight > 0 ) { - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; - this.color = color; + switch ( this.blendMode ) { - const geometry = new BufferGeometry(); + case AdditiveAnimationBlendMode: - const 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 ( let j = 0, m = interpolants.length; j !== m; ++ j ) { - for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulateAdditive( weight ); - const p1 = ( i / l ) * Math.PI * 2; - const p2 = ( j / l ) * Math.PI * 2; + } - positions.push( - Math.cos( p1 ), Math.sin( p1 ), 1, - Math.cos( p2 ), Math.sin( p2 ), 1 - ); + break; - } + case NormalAnimationBlendMode: + default: - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { - const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); - this.cone = new LineSegments( geometry, material ); - this.add( this.cone ); + } - this.update(); + } + + } } - dispose() { + _updateWeight( time ) { - this.cone.geometry.dispose(); - this.cone.material.dispose(); + let weight = 0; - } + if ( this.enabled ) { - update() { + weight = this.weight; + const interpolant = this._weightInterpolant; - this.light.updateMatrixWorld(); + if ( interpolant !== null ) { - const coneLength = this.light.distance ? this.light.distance : 1000; - const coneWidth = coneLength * Math.tan( this.light.angle ); + const interpolantValue = interpolant.evaluate( time )[ 0 ]; - this.cone.scale.set( coneWidth, coneWidth, coneLength ); + weight *= interpolantValue; - _vector$9.setFromMatrixPosition( this.light.target.matrixWorld ); + if ( time > interpolant.parameterPositions[ 1 ] ) { - this.cone.lookAt( _vector$9 ); + this.stopFading(); - if ( this.color !== undefined ) { + if ( interpolantValue === 0 ) { - this.cone.material.color.set( this.color ); + // faded out, disable + this.enabled = false; - } else { + } - this.cone.material.color.copy( this.light.color ); + } + + } } + this._effectiveWeight = weight; + return weight; + } -} + _updateTimeScale( time ) { -const _vector$a = /*@__PURE__*/ new Vector3(); -const _boneMatrix = /*@__PURE__*/ new Matrix4(); -const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + let timeScale = 0; + if ( ! this.paused ) { -class SkeletonHelper extends LineSegments { + timeScale = this.timeScale; - constructor( object ) { + const interpolant = this._timeScaleInterpolant; - const bones = getBoneList( object ); + if ( interpolant !== null ) { - const geometry = new BufferGeometry(); + const interpolantValue = interpolant.evaluate( time )[ 0 ]; - const vertices = []; - const colors = []; + timeScale *= interpolantValue; - const color1 = new Color( 0, 0, 1 ); - const color2 = new Color( 0, 1, 0 ); + if ( time > interpolant.parameterPositions[ 1 ] ) { - for ( let i = 0; i < bones.length; i ++ ) { + this.stopWarping(); - const bone = bones[ i ]; + if ( timeScale === 0 ) { - if ( bone.parent && bone.parent.isBone ) { + // motion has halted, pause + this.paused = true; - vertices.push( 0, 0, 0 ); - vertices.push( 0, 0, 0 ); - colors.push( color1.r, color1.g, color1.b ); - colors.push( color2.r, color2.g, color2.b ); + } else { + + // warp done - apply final time scale + this.timeScale = timeScale; + + } + + } } } - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + this._effectiveTimeScale = timeScale; + return timeScale; - const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); + } - super( geometry, material ); + _updateTime( deltaTime ) { - this.type = 'SkeletonHelper'; - this.isSkeletonHelper = true; + const duration = this._clip.duration; + const loop = this.loop; - this.root = object; - this.bones = bones; + let time = this.time + deltaTime; + let loopCount = this._loopCount; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + const pingPong = ( loop === LoopPingPong ); - } + if ( deltaTime === 0 ) { - updateMatrixWorld( force ) { + if ( loopCount === - 1 ) return time; - const bones = this.bones; + return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; - const geometry = this.geometry; - const position = geometry.getAttribute( 'position' ); + } - _matrixWorldInv.copy( this.root.matrixWorld ).invert(); + if ( loop === LoopOnce ) { - for ( let i = 0, j = 0; i < bones.length; i ++ ) { + if ( loopCount === - 1 ) { - const bone = bones[ i ]; + // just started - if ( bone.parent && bone.parent.isBone ) { + this._loopCount = 0; + this._setEndings( true, true, false ); - _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); - _vector$a.setFromMatrixPosition( _boneMatrix ); - position.setXYZ( j, _vector$a.x, _vector$a.y, _vector$a.z ); + } - _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); - _vector$a.setFromMatrixPosition( _boneMatrix ); - position.setXYZ( j + 1, _vector$a.x, _vector$a.y, _vector$a.z ); + handle_stop: { - j += 2; + if ( time >= duration ) { - } + time = duration; - } + } else if ( time < 0 ) { - geometry.getAttribute( 'position' ).needsUpdate = true; + time = 0; - super.updateMatrixWorld( force ); + } else { - } + this.time = time; -} + break handle_stop; + } -function getBoneList( object ) { + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - const boneList = []; + this.time = time; - if ( object && object.isBone ) { + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? - 1 : 1 + } ); - boneList.push( object ); + } - } + } else { // repetitive Repeat or PingPong - for ( let i = 0; i < object.children.length; i ++ ) { + if ( loopCount === - 1 ) { - boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); + // just started - } + if ( deltaTime >= 0 ) { - return boneList; + loopCount = 0; -} + this._setEndings( true, this.repetitions === 0, pingPong ); -class PointLightHelper extends Mesh { + } else { - constructor( light, sphereSize, color ) { + // when looping in reverse direction, the initial + // transition through zero counts as a repetition, + // so leave loopCount at -1 - const geometry = new SphereGeometry( sphereSize, 4, 2 ); - const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + this._setEndings( this.repetitions === 0, true, pingPong ); - super( geometry, material ); + } - this.light = light; - this.light.updateMatrixWorld(); + } - this.color = color; + if ( time >= duration || time < 0 ) { - this.type = 'PointLightHelper'; + // wrap around - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + const loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; - this.update(); + loopCount += Math.abs( loopDelta ); + const pending = this.repetitions - loopCount; - /* - // TODO: delete this comment? - const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 ); - const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + if ( pending <= 0 ) { - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + // have to stop (switch state, clamp time, fire event) - const d = light.distance; + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - if ( d === 0.0 ) { + time = deltaTime > 0 ? duration : 0; - this.lightDistance.visible = false; + this.time = time; - } else { + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : - 1 + } ); - this.lightDistance.scale.set( d, d, d ); + } else { - } + // keep running - this.add( this.lightDistance ); - */ + if ( pending === 1 ) { - } + // entering the last round - dispose() { + const atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); - this.geometry.dispose(); - this.material.dispose(); + } else { - } + this._setEndings( false, false, pingPong ); - update() { + } - if ( this.color !== undefined ) { + this._loopCount = loopCount; - this.material.color.set( this.color ); + this.time = time; - } else { + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); - this.material.color.copy( this.light.color ); + } - } + } else { - /* - const d = this.light.distance; + this.time = time; - if ( d === 0.0 ) { + } - this.lightDistance.visible = false; + if ( pingPong && ( loopCount & 1 ) === 1 ) { - } else { + // invert time for the "pong round" - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + return duration - time; + + } } - */ + + return time; } -} + _setEndings( atStart, atEnd, pingPong ) { -const _vector$b = /*@__PURE__*/ new Vector3(); -const _color1 = /*@__PURE__*/ new Color(); -const _color2 = /*@__PURE__*/ new Color(); + const settings = this._interpolantSettings; -class HemisphereLightHelper extends Object3D { + if ( pingPong ) { - constructor( light, size, color ) { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; - super(); - this.light = light; - this.light.updateMatrixWorld(); + } else { - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + // assuming for LoopOnce atStart == atEnd == true - this.color = color; + if ( atStart ) { - const geometry = new OctahedronGeometry( size ); - geometry.rotateY( Math.PI * 0.5 ); + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; - this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); - if ( this.color === undefined ) this.material.vertexColors = true; + } else { - const position = geometry.getAttribute( 'position' ); - const colors = new Float32Array( position.count * 3 ); + settings.endingStart = WrapAroundEnding; - geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); + } - this.add( new Mesh( geometry, this.material ) ); + if ( atEnd ) { - this.update(); + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; - } + } else { - dispose() { + settings.endingEnd = WrapAroundEnding; - this.children[ 0 ].geometry.dispose(); - this.children[ 0 ].material.dispose(); + } + + } } - update() { + _scheduleFading( duration, weightNow, weightThen ) { - const mesh = this.children[ 0 ]; + const mixer = this._mixer, now = mixer.time; + let interpolant = this._weightInterpolant; - if ( this.color !== undefined ) { + if ( interpolant === null ) { - this.material.color.set( this.color ); + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; - } else { + } - const colors = mesh.geometry.getAttribute( 'color' ); + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; - _color1.copy( this.light.color ); - _color2.copy( this.light.groundColor ); + times[ 0 ] = now; + values[ 0 ] = weightNow; + times[ 1 ] = now + duration; + values[ 1 ] = weightThen; - for ( let i = 0, l = colors.count; i < l; i ++ ) { + return this; - const color = ( i < ( l / 2 ) ) ? _color1 : _color2; + } - colors.setXYZ( i, color.r, color.g, color.b ); +} - } +const _controlInterpolantsResultBuffer = new Float32Array( 1 ); - colors.needsUpdate = true; - } +class AnimationMixer extends EventDispatcher { - mesh.lookAt( _vector$b.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + constructor( root ) { - } + super(); -} + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1.0; -class GridHelper extends LineSegments { + } - constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { + _bindAction( action, prototypeAction ) { - color1 = new Color( color1 ); - color2 = new Color( color2 ); + const root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName; - const center = divisions / 2; - const step = size / divisions; - const halfSize = size / 2; + let bindingsByName = bindingsByRoot[ rootUuid ]; - const vertices = [], colors = []; + if ( bindingsByName === undefined ) { - for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; - vertices.push( - halfSize, 0, k, halfSize, 0, k ); - vertices.push( k, 0, - halfSize, k, 0, halfSize ); + } - const color = i === center ? color1 : color2; + for ( let i = 0; i !== nTracks; ++ i ) { - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; + const track = tracks[ i ], + trackName = track.name; - } + let binding = bindingsByName[ trackName ]; - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + if ( binding !== undefined ) { - const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + ++ binding.referenceCount; + bindings[ i ] = binding; - super( geometry, material ); + } else { - this.type = 'GridHelper'; + binding = bindings[ i ]; - } + if ( binding !== undefined ) { -} + // existing binding, make sure the cache knows -class PolarGridHelper extends LineSegments { + if ( binding._cacheIndex === null ) { - constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - color1 = new Color( color1 ); - color2 = new Color( color2 ); + } - const vertices = []; - const colors = []; + continue; - // create the radials + } - for ( let i = 0; i <= radials; i ++ ) { + const path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; - const v = ( i / radials ) * ( Math.PI * 2 ); + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); - const x = Math.sin( v ) * radius; - const z = Math.cos( v ) * radius; + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - vertices.push( 0, 0, 0 ); - vertices.push( x, 0, z ); + bindings[ i ] = binding; - const color = ( i & 1 ) ? color1 : color2; + } - colors.push( color.r, color.g, color.b ); - colors.push( color.r, color.g, color.b ); + interpolants[ i ].resultBuffer = binding.buffer; } - // create the circles - - for ( let i = 0; i <= circles; i ++ ) { + } - const color = ( i & 1 ) ? color1 : color2; + _activateAction( action ) { - const r = radius - ( radius / circles * i ); + if ( ! this._isActiveAction( action ) ) { - for ( let j = 0; j < divisions; j ++ ) { + if ( action._cacheIndex === null ) { - // first vertex + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind - let v = ( j / divisions ) * ( Math.PI * 2 ); + const rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; - let x = Math.sin( v ) * r; - let z = Math.cos( v ) * r; + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); - vertices.push( x, 0, z ); - colors.push( color.r, color.g, color.b ); + this._addInactiveAction( action, clipUuid, rootUuid ); - // second vertex + } - v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); + const bindings = action._propertyBindings; - x = Math.sin( v ) * r; - z = Math.cos( v ) * r; + // increment reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { - vertices.push( x, 0, z ); - colors.push( color.r, color.g, color.b ); + const binding = bindings[ i ]; - } + if ( binding.useCount ++ === 0 ) { - } + this._lendBinding( binding ); + binding.saveOriginalState(); - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + } - const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + } - super( geometry, material ); + this._lendAction( action ); - this.type = 'PolarGridHelper'; + } } -} - -const _v1$6 = /*@__PURE__*/ new Vector3(); -const _v2$3 = /*@__PURE__*/ new Vector3(); -const _v3$1 = /*@__PURE__*/ new Vector3(); + _deactivateAction( action ) { -class DirectionalLightHelper extends Object3D { + if ( this._isActiveAction( action ) ) { - constructor( light, size, color ) { + const bindings = action._propertyBindings; - super(); - this.light = light; - this.light.updateMatrixWorld(); + // decrement reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + const binding = bindings[ i ]; - this.color = color; + if ( -- binding.useCount === 0 ) { - if ( size === undefined ) size = 1; + binding.restoreOriginalState(); + this._takeBackBinding( binding ); - let geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( [ - - size, size, 0, - size, size, 0, - size, - size, 0, - - size, - size, 0, - - size, size, 0 - ], 3 ) ); + } - const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + } - this.lightPlane = new Line( geometry, material ); - this.add( this.lightPlane ); + this._takeBackAction( action ); - geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + } - this.targetLine = new Line( geometry, material ); - this.add( this.targetLine ); + } - this.update(); + // Memory manager - } + _initMemoryManager() { - dispose() { + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; - this.lightPlane.geometry.dispose(); - this.lightPlane.material.dispose(); - this.targetLine.geometry.dispose(); - this.targetLine.material.dispose(); + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< AnimationAction > - used as prototypes + // actionByRoot: AnimationAction - lookup + // } - } - update() { + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; - _v1$6.setFromMatrixPosition( this.light.matrixWorld ); - _v2$3.setFromMatrixPosition( this.light.target.matrixWorld ); - _v3$1.subVectors( _v2$3, _v1$6 ); + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > - this.lightPlane.lookAt( _v2$3 ); - if ( this.color !== undefined ) { + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; - this.lightPlane.material.color.set( this.color ); - this.targetLine.material.color.set( this.color ); + const scope = this; - } else { + this.stats = { - this.lightPlane.material.color.copy( this.light.color ); - this.targetLine.material.color.copy( this.light.color ); + actions: { + get total() { - } + return scope._actions.length; - this.targetLine.lookAt( _v2$3 ); - this.targetLine.scale.z = _v3$1.length(); + }, + get inUse() { - } + return scope._nActiveActions; -} + } + }, + bindings: { + get total() { -const _vector$c = /*@__PURE__*/ new Vector3(); -const _camera = /*@__PURE__*/ new Camera(); + return scope._bindings.length; -/** - * - 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 - */ + }, + get inUse() { -class CameraHelper extends LineSegments { + return scope._nActiveBindings; - constructor( camera ) { + } + }, + controlInterpolants: { + get total() { - const geometry = new BufferGeometry(); - const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); + return scope._controlInterpolants.length; - const vertices = []; - const colors = []; + }, + get inUse() { - const pointMap = {}; + return scope._nActiveControlInterpolants; - // colors + } + } - const colorFrustum = new Color( 0xffaa00 ); - const colorCone = new Color( 0xff0000 ); - const colorUp = new Color( 0x00aaff ); - const colorTarget = new Color( 0xffffff ); - const colorCross = new Color( 0x333333 ); + }; - // near + } - addLine( 'n1', 'n2', colorFrustum ); - addLine( 'n2', 'n4', colorFrustum ); - addLine( 'n4', 'n3', colorFrustum ); - addLine( 'n3', 'n1', colorFrustum ); + // Memory management for AnimationAction objects - // far + _isActiveAction( action ) { - addLine( 'f1', 'f2', colorFrustum ); - addLine( 'f2', 'f4', colorFrustum ); - addLine( 'f4', 'f3', colorFrustum ); - addLine( 'f3', 'f1', colorFrustum ); + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; - // sides + } - addLine( 'n1', 'f1', colorFrustum ); - addLine( 'n2', 'f2', colorFrustum ); - addLine( 'n3', 'f3', colorFrustum ); - addLine( 'n4', 'f4', colorFrustum ); + _addInactiveAction( action, clipUuid, rootUuid ) { - // cone + const actions = this._actions, + actionsByClip = this._actionsByClip; - addLine( 'p', 'n1', colorCone ); - addLine( 'p', 'n2', colorCone ); - addLine( 'p', 'n3', colorCone ); - addLine( 'p', 'n4', colorCone ); + let actionsForClip = actionsByClip[ clipUuid ]; - // up + if ( actionsForClip === undefined ) { - addLine( 'u1', 'u2', colorUp ); - addLine( 'u2', 'u3', colorUp ); - addLine( 'u3', 'u1', colorUp ); + actionsForClip = { - // target + knownActions: [ action ], + actionByRoot: {} - addLine( 'c', 't', colorTarget ); - addLine( 'p', 'c', colorCross ); + }; - // cross + action._byClipCacheIndex = 0; - addLine( 'cn1', 'cn2', colorCross ); - addLine( 'cn3', 'cn4', colorCross ); + actionsByClip[ clipUuid ] = actionsForClip; - addLine( 'cf1', 'cf2', colorCross ); - addLine( 'cf3', 'cf4', colorCross ); + } else { - function addLine( a, b, color ) { + const knownActions = actionsForClip.knownActions; - addPoint( a, color ); - addPoint( b, color ); + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); } - function addPoint( id, color ) { + action._cacheIndex = actions.length; + actions.push( action ); - vertices.push( 0, 0, 0 ); - colors.push( color.r, color.g, color.b ); + actionsForClip.actionByRoot[ rootUuid ] = action; - if ( pointMap[ id ] === undefined ) { + } - pointMap[ id ] = []; + _removeInactiveAction( action ) { - } + const actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; - pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - } + action._cacheIndex = null; - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - super( geometry, material ); + const clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, - this.type = 'CameraHelper'; + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], - this.camera = camera; - if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + byClipCacheIndex = action._byClipCacheIndex; - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); - this.pointMap = pointMap; + action._byClipCacheIndex = null; - this.update(); - } + const actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( action._localRoot || this._root ).uuid; - update() { + delete actionByRoot[ rootUuid ]; - const geometry = this.geometry; - const pointMap = this.pointMap; + if ( knownActionsForClip.length === 0 ) { - const w = 1, h = 1; + delete actionsByClip[ clipUuid ]; - // we need just camera projection matrix inverse - // world matrix must be identity + } - _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); + this._removeInactiveBindingsForAction( action ); - // center / target + } - setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); - setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); + _removeInactiveBindingsForAction( action ) { - // near + const bindings = action._propertyBindings; - setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); - setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); - setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); - setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { - // far + const binding = bindings[ i ]; - setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); - setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); - setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); - setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); + if ( -- binding.referenceCount === 0 ) { - // up + this._removeInactiveBinding( binding ); - setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); - setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); - setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); + } - // cross + } - setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); - setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); - setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); - setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); + } - setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); - setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); - setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); - setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); + _lendAction( action ) { - geometry.getAttribute( 'position' ).needsUpdate = true; + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s - } + const actions = this._actions, + prevIndex = action._cacheIndex, -} + lastActiveIndex = this._nActiveActions ++, + firstInactiveAction = actions[ lastActiveIndex ]; -function setPoint( point, pointMap, geometry, camera, x, y, z ) { + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; - _vector$c.set( x, y, z ).unproject( camera ); + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; - const points = pointMap[ point ]; + } - if ( points !== undefined ) { + _takeBackAction( action ) { - const position = geometry.getAttribute( 'position' ); + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a - for ( let i = 0, l = points.length; i < l; i ++ ) { + const actions = this._actions, + prevIndex = action._cacheIndex, - position.setXYZ( points[ i ], _vector$c.x, _vector$c.y, _vector$c.z ); + firstInactiveIndex = -- this._nActiveActions, - } + lastActiveAction = actions[ firstInactiveIndex ]; - } + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; -} + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; -const _box$3 = /*@__PURE__*/ new Box3(); + } -class BoxHelper extends LineSegments { + // Memory management for PropertyMixer objects - constructor( object, color = 0xffff00 ) { + _addInactiveBinding( binding, rootUuid, trackName ) { - const 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 ] ); - const positions = new Float32Array( 8 * 3 ); + const bindingsByRoot = this._bindingsByRootAndName, + bindings = this._bindings; - const geometry = new BufferGeometry(); - geometry.setIndex( new BufferAttribute( indices, 1 ) ); - geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + let bindingByName = bindingsByRoot[ rootUuid ]; - super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + if ( bindingByName === undefined ) { - this.object = object; - this.type = 'BoxHelper'; + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; - this.matrixAutoUpdate = false; + } - this.update(); + bindingByName[ trackName ] = binding; + + binding._cacheIndex = bindings.length; + bindings.push( binding ); } - update( object ) { + _removeInactiveBinding( binding ) { - if ( object !== undefined ) { + const bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; - } + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); - if ( this.object !== undefined ) { + delete bindingByName[ trackName ]; + + if ( Object.keys( bindingByName ).length === 0 ) { - _box$3.setFromObject( this.object ); + delete bindingsByRoot[ rootUuid ]; } - if ( _box$3.isEmpty() ) return; + } - const min = _box$3.min; - const max = _box$3.max; + _lendBinding( binding ) { - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ + const bindings = this._bindings, + prevIndex = binding._cacheIndex, - 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 - */ + lastActiveIndex = this._nActiveBindings ++, - const position = this.geometry.attributes.position; - const array = position.array; + firstInactiveBinding = bindings[ lastActiveIndex ]; - 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; + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; - position.needsUpdate = true; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; - this.geometry.computeBoundingSphere(); + } + _takeBackBinding( binding ) { - } + const bindings = this._bindings, + prevIndex = binding._cacheIndex, - setFromObject( object ) { + firstInactiveIndex = -- this._nActiveBindings, - this.object = object; - this.update(); + lastActiveBinding = bindings[ firstInactiveIndex ]; - return this; + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; + + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; } - copy( source ) { - LineSegments.prototype.copy.call( this, source ); + // Memory management of Interpolants for weight and time scale - this.object = source.object; + _lendControlInterpolant() { - return this; + const interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++; - } + let interpolant = interpolants[ lastActiveIndex ]; -} + if ( interpolant === undefined ) { -class Box3Helper extends LineSegments { + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, _controlInterpolantsResultBuffer ); - constructor( box, color = 0xffff00 ) { + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; - const 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 ] ); + } - const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; + return interpolant; - const geometry = new BufferGeometry(); + } - geometry.setIndex( new BufferAttribute( indices, 1 ) ); + _takeBackControlInterpolant( interpolant ) { - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + const interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, - super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + firstInactiveIndex = -- this._nActiveControlInterpolants, - this.box = box; + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; - this.type = 'Box3Helper'; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; - this.geometry.computeBoundingSphere(); + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; } - updateMatrixWorld( force ) { + // 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( clip, optionalRoot, blendMode ) { - const box = this.box; + const root = optionalRoot || this._root, + rootUuid = root.uuid; - if ( box.isEmpty() ) return; + let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; - box.getCenter( this.position ); + const clipUuid = clipObject !== null ? clipObject.uuid : clip; - box.getSize( this.scale ); + const actionsForClip = this._actionsByClip[ clipUuid ]; + let prototypeAction = null; - this.scale.multiplyScalar( 0.5 ); + if ( blendMode === undefined ) { - super.updateMatrixWorld( force ); + if ( clipObject !== null ) { - } + blendMode = clipObject.blendMode; -} + } else { -class PlaneHelper extends Line { + blendMode = NormalAnimationBlendMode; - constructor( plane, size = 1, hex = 0xffff00 ) { + } - const color = hex; + } - const positions = [ 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, 0, 1, 0, 0, 0 ]; + if ( actionsForClip !== undefined ) { - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); - geometry.computeBoundingSphere(); + const existingAction = actionsForClip.actionByRoot[ rootUuid ]; - super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { - this.type = 'PlaneHelper'; + return existingAction; - this.plane = plane; + } - this.size = size; + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; - const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ]; + // also, take the clip from the prototype action + if ( clipObject === null ) + clipObject = prototypeAction._clip; - const geometry2 = new BufferGeometry(); - geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); - geometry2.computeBoundingSphere(); + } - this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); + // clip must be known when specified via string + if ( clipObject === null ) return null; - } + // allocate all resources required to run it + const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); - updateMatrixWorld( force ) { + this._bindAction( newAction, prototypeAction ); - let scale = - this.plane.constant; + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); - if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter + return newAction; - this.scale.set( 0.5 * this.size, 0.5 * this.size, scale ); + } - this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here + // get an existing action + existingAction( clip, optionalRoot ) { - this.lookAt( this.plane.normal ); + const root = optionalRoot || this._root, + rootUuid = root.uuid, - super.updateMatrixWorld( force ); + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - } + clipUuid = clipObject ? clipObject.uuid : clip, -} + actionsForClip = this._actionsByClip[ clipUuid ]; -const _axis = /*@__PURE__*/ new Vector3(); -let _lineGeometry, _coneGeometry; + if ( actionsForClip !== undefined ) { -class ArrowHelper extends Object3D { + return actionsForClip.actionByRoot[ rootUuid ] || null; - // dir is assumed to be normalized + } - constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + return null; - super(); + } - this.type = 'ArrowHelper'; + // deactivates all previously scheduled actions + stopAllAction() { - if ( _lineGeometry === undefined ) { + const actions = this._actions, + nActions = this._nActiveActions; - _lineGeometry = new BufferGeometry(); - _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + for ( let i = nActions - 1; i >= 0; -- i ) { - _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 ); - _coneGeometry.translate( 0, - 0.5, 0 ); + actions[ i ].stop(); } - this.position.copy( origin ); + return this; - this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + } - this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + // advance the time and update apply the animation + update( deltaTime ) { - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + deltaTime *= this.timeScale; - } + const actions = this._actions, + nActions = this._nActiveActions, - setDirection( dir ) { + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), - // dir is assumed to be normalized + accuIndex = this._accuIndex ^= 1; - if ( dir.y > 0.99999 ) { + // run active actions - this.quaternion.set( 0, 0, 0, 1 ); + for ( let i = 0; i !== nActions; ++ i ) { - } else if ( dir.y < - 0.99999 ) { + const action = actions[ i ]; - this.quaternion.set( 1, 0, 0, 0 ); + action._update( time, deltaTime, timeDirection, accuIndex ); - } else { + } - _axis.set( dir.z, 0, - dir.x ).normalize(); + // update scene graph - const radians = Math.acos( dir.y ); + const bindings = this._bindings, + nBindings = this._nActiveBindings; + + for ( let i = 0; i !== nBindings; ++ i ) { - this.quaternion.setFromAxisAngle( _axis, radians ); + bindings[ i ].apply( accuIndex ); } + return this; + } - setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + // Allows you to seek to a specific time in an animation. + setTime( timeInSeconds ) { - this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 - this.line.updateMatrix(); + this.time = 0; // Zero out time attribute for AnimationMixer object; + for ( let i = 0; i < this._actions.length; i ++ ) { - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); + this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + + } + + return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. } - setColor( color ) { + // return this mixer's root target object + getRoot() { - this.line.material.color.set( color ); - this.cone.material.color.set( color ); + return this._root; } - copy( source ) { - - super.copy( source, false ); + // free all resources specific to a particular clip + uncacheClip( clip ) { - this.line.copy( source.line ); - this.cone.copy( source.cone ); + const actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - return this; + if ( actionsForClip !== undefined ) { - } + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away -} + const actionsToRemove = actionsForClip.knownActions; -class AxesHelper extends LineSegments { + for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { - constructor( size = 1 ) { + const action = actionsToRemove[ i ]; - const vertices = [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ]; + this._deactivateAction( action ); - const colors = [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 - ]; + const cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; - const geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + action._cacheIndex = null; + action._byClipCacheIndex = null; - const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - super( geometry, material ); + this._removeInactiveBindingsForAction( action ); - this.type = 'AxesHelper'; + } - } + delete actionsByClip[ clipUuid ]; -} + } -const _floatView = new Float32Array( 1 ); -const _int32View = new Int32Array( _floatView.buffer ); + } -const DataUtils = { + // free all resources specific to a particular root target object + uncacheRoot( root ) { - // Converts float32 to float16 (stored as uint16 value). + const rootUuid = root.uuid, + actionsByClip = this._actionsByClip; - toHalfFloat: function ( val ) { + for ( const clipUuid in actionsByClip ) { - // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410 + const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; - /* This method is faster than the OpenEXR implementation (very often - * used, eg. in Ogre), with the additional benefit of rounding, inspired - * by James Tursa?s half-precision code. */ + if ( action !== undefined ) { - _floatView[ 0 ] = val; - const x = _int32View[ 0 ]; + this._deactivateAction( action ); + this._removeInactiveAction( action ); - let bits = ( x >> 16 ) & 0x8000; /* Get the sign */ - let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */ - const e = ( x >> 23 ) & 0xff; /* Using int is faster here */ + } - /* If zero, or denormal, or exponent underflows too much for a denormal - * half, return signed zero. */ - if ( e < 103 ) return bits; + } - /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */ - if ( e > 142 ) { + const bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; - bits |= 0x7c00; - /* If exponent was 0xff and one mantissa bit was set, it means NaN, - * not Inf, so make sure we set one mantissa bit too. */ - bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff ); - return bits; + if ( bindingByName !== undefined ) { - } + for ( const trackName in bindingByName ) { - /* If exponent underflows but not too much, return a denormal */ - if ( e < 113 ) { + const binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); - m |= 0x0800; - /* Extra rounding may overflow and set mantissa to 0 and exponent - * to 1, which is OK. */ - bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 ); - return bits; + } } - bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 ); - /* Extra rounding. An overflow will set mantissa to 0 and increment - * the exponent, which is OK. */ - bits += m & 1; - return bits; - } -}; + // remove a targeted clip from the cache + uncacheAction( clip, optionalRoot ) { -const LOD_MIN = 4; -const LOD_MAX = 8; -const SIZE_MAX = Math.pow( 2, LOD_MAX ); + const action = this.existingAction( clip, optionalRoot ); -// The standard deviations (radians) associated with the extra mips. These are -// chosen to approximate a Trowbridge-Reitz distribution function times the -// geometric shadowing function. These sigma values squared must match the -// variance #defines in cube_uv_reflection_fragment.glsl.js. -const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + if ( action !== null ) { -const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + this._deactivateAction( action ); + this._removeInactiveAction( action ); -// The maximum length of the blur for loop. Smaller sigmas will use fewer -// samples and exit early, but not recompile the shader. -const MAX_SAMPLES = 20; + } -const ENCODINGS = { - [ LinearEncoding ]: 0, - [ sRGBEncoding ]: 1, - [ RGBEEncoding ]: 2, - [ RGBM7Encoding ]: 3, - [ RGBM16Encoding ]: 4, - [ RGBDEncoding ]: 5, - [ GammaEncoding ]: 6 -}; + } -const backgroundMaterial = new MeshBasicMaterial( { - side: BackSide, - depthWrite: false, - depthTest: false, -} ); -const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); +} -const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); -const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes(); -const _clearColor = /*@__PURE__*/ new Color(); -let _oldTarget = null; +class Uniform { -// Golden Ratio -const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; -const INV_PHI = 1 / PHI; + constructor( value ) { -// Vertices of a dodecahedron (except the opposites, which represent the -// same axis), used as axis directions evenly spread on a sphere. -const _axisDirections = [ - /*@__PURE__*/ new Vector3( 1, 1, 1 ), - /*@__PURE__*/ new Vector3( - 1, 1, 1 ), - /*@__PURE__*/ new Vector3( 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), - /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), - /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), - /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), - /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), - /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; + this.value = value; -/** - * This class generates a Prefiltered, Mipmapped Radiance Environment Map - * (PMREM) from a cubeMap environment texture. This allows different levels of - * blur to be quickly accessed based on material roughness. It is packed into a - * special CubeUV format that allows us to perform custom interpolation so that - * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap - * chain, it only goes down to the LOD_MIN level (above), and then creates extra - * even more filtered 'mips' at the same LOD_MIN resolution, associated with - * higher roughness levels. In this way we maintain resolution to smoothly - * interpolate diffuse lighting while limiting sampling computation. - */ + } -function convertLinearToRGBE( color ) { + clone() { - const maxComponent = Math.max( color.r, color.g, color.b ); - const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 ); - color.multiplyScalar( Math.pow( 2.0, - fExp ) ); + return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); - const alpha = ( fExp + 128.0 ) / 255.0; - return alpha; + } } -class PMREMGenerator { - - constructor( renderer ) { +let id = 0; - this._renderer = renderer; - this._pingPongRenderTarget = null; +class UniformsGroup extends EventDispatcher { - this._blurMaterial = _getBlurShader( MAX_SAMPLES ); - this._equirectShader = null; - this._cubemapShader = null; + constructor() { - this._compileMaterial( this._blurMaterial ); + super(); - } + this.isUniformsGroup = true; - /** - * Generates a PMREM from a supplied Scene, which can be faster than using an - * image if networking bandwidth is low. Optional sigma specifies a blur radius - * in radians to be applied to the scene before PMREM generation. Optional near - * and far planes ensure the scene is rendered in its entirety (the cubeCamera - * is placed at the origin). - */ - fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { + Object.defineProperty( this, 'id', { value: id ++ } ); - _oldTarget = this._renderer.getRenderTarget(); - const cubeUVRenderTarget = this._allocateTargets(); + this.name = ''; - this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); - if ( sigma > 0 ) { + this.usage = StaticDrawUsage; + this.uniforms = []; - this._blur( cubeUVRenderTarget, 0, 0, sigma ); + } - } + add( uniform ) { - this._applyPMREM( cubeUVRenderTarget ); - this._cleanup( cubeUVRenderTarget ); + this.uniforms.push( uniform ); - return cubeUVRenderTarget; + return this; } - /** - * Generates a PMREM from an equirectangular texture, which can be either LDR - * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512), - * as this matches best with the 256 x 256 cubemap output. - */ - fromEquirectangular( equirectangular ) { - - return this._fromTexture( equirectangular ); + remove( uniform ) { - } + const index = this.uniforms.indexOf( uniform ); - /** - * Generates a PMREM from an cubemap texture, which can be either LDR - * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256, - * as this matches best with the 256 x 256 cubemap output. - */ - fromCubemap( cubemap ) { + if ( index !== - 1 ) this.uniforms.splice( index, 1 ); - return this._fromTexture( cubemap ); + return this; } - /** - * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - compileCubemapShader() { - - if ( this._cubemapShader === null ) { + setName( name ) { - this._cubemapShader = _getCubemapShader(); - this._compileMaterial( this._cubemapShader ); + this.name = name; - } + return this; } - /** - * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during - * your texture's network fetch for increased concurrency. - */ - compileEquirectangularShader() { - - if ( this._equirectShader === null ) { + setUsage( value ) { - this._equirectShader = _getEquirectShader(); - this._compileMaterial( this._equirectShader ); + this.usage = value; - } + return this; } - /** - * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, - * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on - * one of them will cause any others to also become unusable. - */ dispose() { - this._blurMaterial.dispose(); + this.dispatchEvent( { type: 'dispose' } ); + + return this; + + } - if ( this._cubemapShader !== null ) this._cubemapShader.dispose(); - if ( this._equirectShader !== null ) this._equirectShader.dispose(); + copy( source ) { - for ( let i = 0; i < _lodPlanes.length; i ++ ) { + this.name = source.name; + this.usage = source.usage; - _lodPlanes[ i ].dispose(); + const uniformsSource = source.uniforms; - } + this.uniforms.length = 0; - } + for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) { - // private interface + this.uniforms.push( uniformsSource[ i ].clone() ); - _cleanup( outputTarget ) { + } - this._pingPongRenderTarget.dispose(); - this._renderer.setRenderTarget( _oldTarget ); - outputTarget.scissorTest = false; - _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + return this; } - _fromTexture( texture ) { - - _oldTarget = this._renderer.getRenderTarget(); - const cubeUVRenderTarget = this._allocateTargets( texture ); - this._textureToCubeUV( texture, cubeUVRenderTarget ); - this._applyPMREM( cubeUVRenderTarget ); - this._cleanup( cubeUVRenderTarget ); + clone() { - return cubeUVRenderTarget; + return new this.constructor().copy( this ); } - _allocateTargets( texture ) { // warning: null texture is valid +} - const params = { - magFilter: NearestFilter, - minFilter: NearestFilter, - generateMipmaps: false, - type: UnsignedByteType, - format: RGBEFormat, - encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding, - depthBuffer: false - }; +class InstancedInterleavedBuffer extends InterleavedBuffer { - const cubeUVRenderTarget = _createRenderTarget( params ); - cubeUVRenderTarget.depthBuffer = texture ? false : true; - this._pingPongRenderTarget = _createRenderTarget( params ); - return cubeUVRenderTarget; + constructor( array, stride, meshPerAttribute = 1 ) { - } + super( array, stride ); - _compileMaterial( material ) { + this.isInstancedInterleavedBuffer = true; - const tmpMesh = new Mesh( _lodPlanes[ 0 ], material ); - this._renderer.compile( tmpMesh, _flatCamera ); + this.meshPerAttribute = meshPerAttribute; } - _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { - - const fov = 90; - const aspect = 1; - const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); - const upSign = [ 1, - 1, 1, 1, 1, 1 ]; - const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; - const renderer = this._renderer; + copy( source ) { - const originalAutoClear = renderer.autoClear; - const outputEncoding = renderer.outputEncoding; - const toneMapping = renderer.toneMapping; - renderer.getClearColor( _clearColor ); + super.copy( source ); - renderer.toneMapping = NoToneMapping; - renderer.outputEncoding = LinearEncoding; - renderer.autoClear = false; + this.meshPerAttribute = source.meshPerAttribute; - let useSolidColor = false; - const background = scene.background; - if ( background ) { + return this; - if ( background.isColor ) { + } - backgroundMaterial.color.copy( background ).convertSRGBToLinear(); - scene.background = null; + clone( data ) { - const alpha = convertLinearToRGBE( backgroundMaterial.color ); - backgroundMaterial.opacity = alpha; - useSolidColor = true; + const ib = super.clone( data ); - } + ib.meshPerAttribute = this.meshPerAttribute; - } else { + return ib; - backgroundMaterial.color.copy( _clearColor ).convertSRGBToLinear(); + } - const alpha = convertLinearToRGBE( backgroundMaterial.color ); - backgroundMaterial.opacity = alpha; - useSolidColor = true; + toJSON( data ) { - } + const json = super.toJSON( data ); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; - for ( let i = 0; i < 6; i ++ ) { + return json; - const col = i % 3; - if ( col == 0 ) { + } - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); +} - } else if ( col == 1 ) { +class GLBufferAttribute { - cubeCamera.up.set( 0, 0, upSign[ i ] ); - cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + constructor( buffer, type, itemSize, elementSize, count ) { - } else { + this.isGLBufferAttribute = true; - cubeCamera.up.set( 0, upSign[ i ], 0 ); - cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; - } + this.version = 0; - _setViewport( cubeUVRenderTarget, - col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX ); - renderer.setRenderTarget( cubeUVRenderTarget ); + } - if ( useSolidColor ) { + set needsUpdate( value ) { - renderer.render( backgroundBox, cubeCamera ); + if ( value === true ) this.version ++; - } + } - renderer.render( scene, cubeCamera ); + setBuffer( buffer ) { - } + this.buffer = buffer; - renderer.toneMapping = toneMapping; - renderer.outputEncoding = outputEncoding; - renderer.autoClear = originalAutoClear; + return this; } - _textureToCubeUV( texture, cubeUVRenderTarget ) { + setType( type, elementSize ) { - const renderer = this._renderer; + this.type = type; + this.elementSize = elementSize; - if ( texture.isCubeTexture ) { + return this; - if ( this._cubemapShader == null ) { + } - this._cubemapShader = _getCubemapShader(); + setItemSize( itemSize ) { - } + this.itemSize = itemSize; - } else { + return this; - if ( this._equirectShader == null ) { + } - this._equirectShader = _getEquirectShader(); + setCount( count ) { - } + this.count = count; - } + return this; - const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader; - const mesh = new Mesh( _lodPlanes[ 0 ], material ); + } - const uniforms = material.uniforms; +} - uniforms[ 'envMap' ].value = texture; +class Raycaster { - if ( ! texture.isCubeTexture ) { + constructor( origin, direction, near = 0, far = Infinity ) { - uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height ); + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - } + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + + } - uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ]; - uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ]; + set( origin, direction ) { - _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX ); + // direction is assumed to be normalized (for accurate distance calculations) - renderer.setRenderTarget( cubeUVRenderTarget ); - renderer.render( mesh, _flatCamera ); + this.ray.set( origin, direction ); } - _applyPMREM( cubeUVRenderTarget ) { + setFromCamera( coords, camera ) { - const renderer = this._renderer; - const autoClear = renderer.autoClear; - renderer.autoClear = false; + if ( camera.isPerspectiveCamera ) { - for ( let i = 1; i < TOTAL_LODS; i ++ ) { + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; - const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] ); + } else if ( camera.isOrthographicCamera ) { - const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; + 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 ); + this.camera = camera; - this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + } else { - } + console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); - renderer.autoClear = autoClear; + } } - /** - * This is a two-pass Gaussian blur for a cubemap. Normally this is done - * vertically and horizontally, but this breaks down on a cube. Here we apply - * the blur latitudinally (around the poles), and then longitudinally (towards - * the poles) to approximate the orthogonally-separable blur. It is least - * accurate at the poles, but still does a decent job. - */ - _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { + intersectObject( object, recursive = true, intersects = [] ) { - const pingPongRenderTarget = this._pingPongRenderTarget; + intersectObject( object, this, intersects, recursive ); - this._halfBlur( - cubeUVRenderTarget, - pingPongRenderTarget, - lodIn, - lodOut, - sigma, - 'latitudinal', - poleAxis ); + intersects.sort( ascSort ); - this._halfBlur( - pingPongRenderTarget, - cubeUVRenderTarget, - lodOut, - lodOut, - sigma, - 'longitudinal', - poleAxis ); + return intersects; } - _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { - - const renderer = this._renderer; - const blurMaterial = this._blurMaterial; + intersectObjects( objects, recursive = true, intersects = [] ) { - if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { + for ( let i = 0, l = objects.length; i < l; i ++ ) { - console.error( - 'blur direction must be either latitudinal or longitudinal!' ); + intersectObject( objects[ i ], this, intersects, recursive ); } - // Number of standard deviations at which to cut off the discrete approximation. - const STANDARD_DEVIATIONS = 3; - - const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial ); - const blurUniforms = blurMaterial.uniforms; - - const pixels = _sizeLods[ lodIn ] - 1; - const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); - const sigmaPixels = sigmaRadians / radiansPerPixel; - const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; + intersects.sort( ascSort ); - if ( samples > MAX_SAMPLES ) { + return intersects; - console.warn( `sigmaRadians, ${ - sigmaRadians}, is too large and will clip, as it requested ${ - samples} samples when the maximum is set to ${MAX_SAMPLES}` ); + } - } +} - const weights = []; - let sum = 0; +function ascSort( a, b ) { - for ( let i = 0; i < MAX_SAMPLES; ++ i ) { + return a.distance - b.distance; - const x = i / sigmaPixels; - const weight = Math.exp( - x * x / 2 ); - weights.push( weight ); +} - if ( i == 0 ) { +function intersectObject( object, raycaster, intersects, recursive ) { - sum += weight; + if ( object.layers.test( raycaster.layers ) ) { - } else if ( i < samples ) { + object.raycast( raycaster, intersects ); - sum += 2 * weight; + } - } + if ( recursive === true ) { - } + const children = object.children; - for ( let i = 0; i < weights.length; i ++ ) { + for ( let i = 0, l = children.length; i < l; i ++ ) { - weights[ i ] = weights[ i ] / sum; + intersectObject( children[ i ], raycaster, intersects, true ); } - blurUniforms[ 'envMap' ].value = targetIn.texture; - blurUniforms[ 'samples' ].value = samples; - blurUniforms[ 'weights' ].value = weights; - blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; + } - if ( poleAxis ) { +} - blurUniforms[ 'poleAxis' ].value = poleAxis; +/** + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. + * The azimuthal angle (theta) is measured from the positive z-axis. + */ - } +class Spherical { - blurUniforms[ 'dTheta' ].value = radiansPerPixel; - blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn; - blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; - blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; + constructor( radius = 1, phi = 0, theta = 0 ) { - const outputSize = _sizeLods[ lodOut ]; - const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize ); - const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 ); + this.radius = radius; + this.phi = phi; // polar angle + this.theta = theta; // azimuthal angle - _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); - renderer.setRenderTarget( targetOut ); - renderer.render( blurMesh, _flatCamera ); + return this; } -} - -function _isLDR( texture ) { + set( radius, phi, theta ) { - if ( texture === undefined || texture.type !== UnsignedByteType ) return false; + this.radius = radius; + this.phi = phi; + this.theta = theta; - return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding; + return this; -} + } -function _createPlanes() { + copy( other ) { - const _lodPlanes = []; - const _sizeLods = []; - const _sigmas = []; + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; - let lod = LOD_MAX; + return this; - for ( let i = 0; i < TOTAL_LODS; i ++ ) { + } - const sizeLod = Math.pow( 2, lod ); - _sizeLods.push( sizeLod ); - let sigma = 1.0 / sizeLod; + // restrict phi to be between EPS and PI-EPS + makeSafe() { - if ( i > LOD_MAX - LOD_MIN ) { + const EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ]; + return this; - } else if ( i == 0 ) { + } - sigma = 0; + setFromVector3( v ) { - } + return this.setFromCartesianCoords( v.x, v.y, v.z ); - _sigmas.push( sigma ); + } - const texelSize = 1.0 / ( sizeLod - 1 ); - const min = - texelSize / 2; - const max = 1 + texelSize / 2; - const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + setFromCartesianCoords( x, y, z ) { - const cubeFaces = 6; - const vertices = 6; - const positionSize = 3; - const uvSize = 2; - const faceIndexSize = 1; + this.radius = Math.sqrt( x * x + y * y + z * z ); - const position = new Float32Array( positionSize * vertices * cubeFaces ); - const uv = new Float32Array( uvSize * vertices * cubeFaces ); - const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + if ( this.radius === 0 ) { - for ( let face = 0; face < cubeFaces; face ++ ) { + this.theta = 0; + this.phi = 0; - const x = ( face % 3 ) * 2 / 3 - 1; - const y = face > 2 ? 0 : - 1; - const coordinates = [ - x, y, 0, - x + 2 / 3, y, 0, - x + 2 / 3, y + 1, 0, - x, y, 0, - x + 2 / 3, y + 1, 0, - x, y + 1, 0 - ]; - position.set( coordinates, positionSize * vertices * face ); - uv.set( uv1, uvSize * vertices * face ); - const fill = [ face, face, face, face, face, face ]; - faceIndex.set( fill, faceIndexSize * vertices * face ); + } else { + + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); } - const planes = new BufferGeometry(); - planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); - planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); - planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); - _lodPlanes.push( planes ); + return this; - if ( lod > LOD_MIN ) { + } - lod --; + clone() { - } + return new this.constructor().copy( this ); } - return { _lodPlanes, _sizeLods, _sigmas }; - } -function _createRenderTarget( params ) { +/** + * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system + */ - const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params ); - cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; - cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; - cubeUVRenderTarget.scissorTest = true; - return cubeUVRenderTarget; +class Cylindrical { -} + constructor( radius = 1, theta = 0, y = 0 ) { -function _setViewport( target, x, y, width, height ) { + this.radius = radius; // distance from the origin to a point in the x-z plane + this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis + this.y = y; // height above the x-z plane - target.viewport.set( x, y, width, height ); - target.scissor.set( x, y, width, height ); + return this; -} + } -function _getBlurShader( maxSamples ) { + set( radius, theta, y ) { - const weights = new Float32Array( maxSamples ); - const poleAxis = new Vector3( 0, 1, 0 ); - const shaderMaterial = new RawShaderMaterial( { + this.radius = radius; + this.theta = theta; + this.y = y; - name: 'SphericalGaussianBlur', + return this; - defines: { 'n': maxSamples }, + } - uniforms: { - 'envMap': { value: null }, - 'samples': { value: 1 }, - 'weights': { value: weights }, - 'latitudinal': { value: false }, - 'dTheta': { value: 0 }, - 'mipInt': { value: 0 }, - 'poleAxis': { value: poleAxis }, - 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, - 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } - }, + copy( other ) { - vertexShader: _getCommonVertexShader(), + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; - fragmentShader: /* glsl */` + return this; - precision mediump float; - precision mediump int; + } - varying vec3 vOutputDirection; + setFromVector3( v ) { - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; + return this.setFromCartesianCoords( v.x, v.y, v.z ); - ${ _getEncodings() } + } - #define ENVMAP_TYPE_CUBE_UV - #include + setFromCartesianCoords( x, y, z ) { - vec3 getSample( float theta, vec3 axis ) { + this.radius = Math.sqrt( x * x + z * z ); + this.theta = Math.atan2( x, z ); + this.y = y; - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + return this; - return bilinearCubeUV( envMap, sampleDirection, mipInt ); + } - } + clone() { - void main() { + return new this.constructor().copy( this ); - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + } - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { +} - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); +const _vector$4 = /*@__PURE__*/ new Vector2(); - } +class Box2 { - axis = normalize( axis ); + constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + this.isBox2 = true; - for ( int i = 1; i < n; i++ ) { + this.min = min; + this.max = max; - if ( i >= samples ) { + } - break; + set( min, max ) { - } + this.min.copy( min ); + this.max.copy( max ); - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + return this; - } + } - gl_FragColor = linearToOutputTexel( gl_FragColor ); + setFromPoints( points ) { - } - `, + this.makeEmpty(); - blending: NoBlending, - depthTest: false, - depthWrite: false + for ( let i = 0, il = points.length; i < il; i ++ ) { - } ); + this.expandByPoint( points[ i ] ); - return shaderMaterial; + } -} + return this; -function _getEquirectShader() { + } - const texelSize = new Vector2( 1, 1 ); - const shaderMaterial = new RawShaderMaterial( { + setFromCenterAndSize( center, size ) { - name: 'EquirectangularToCubeUV', + const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - uniforms: { - 'envMap': { value: null }, - 'texelSize': { value: texelSize }, - 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, - 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } - }, + return this; - vertexShader: _getCommonVertexShader(), + } - fragmentShader: /* glsl */` + clone() { - precision mediump float; - precision mediump int; + return new this.constructor().copy( this ); - varying vec3 vOutputDirection; + } - uniform sampler2D envMap; - uniform vec2 texelSize; + copy( box ) { - ${ _getEncodings() } + this.min.copy( box.min ); + this.max.copy( box.max ); - #include + return this; - void main() { + } - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + makeEmpty() { - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - vec2 f = fract( uv / texelSize - 0.5 ); - uv -= f * texelSize; - vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; - uv.x += texelSize.x; - vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; - uv.y += texelSize.y; - vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; - uv.x -= texelSize.x; - vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; + return this; - vec3 tm = mix( tl, tr, f.x ); - vec3 bm = mix( bl, br, f.x ); - gl_FragColor.rgb = mix( tm, bm, f.y ); + } - gl_FragColor = linearToOutputTexel( gl_FragColor ); + isEmpty() { - } - `, + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - blending: NoBlending, - depthTest: false, - depthWrite: false + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - } ); + } - return shaderMaterial; + getCenter( target ) { -} + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); -function _getCubemapShader() { + } - const shaderMaterial = new RawShaderMaterial( { + getSize( target ) { - name: 'CubemapToCubeUV', + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); - uniforms: { - 'envMap': { value: null }, - 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, - 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } - }, + } - vertexShader: _getCommonVertexShader(), + expandByPoint( point ) { - fragmentShader: /* glsl */` + this.min.min( point ); + this.max.max( point ); - precision mediump float; - precision mediump int; + return this; - varying vec3 vOutputDirection; + } - uniform samplerCube envMap; + expandByVector( vector ) { - ${ _getEncodings() } + this.min.sub( vector ); + this.max.add( vector ); - void main() { + return this; - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb; - gl_FragColor = linearToOutputTexel( gl_FragColor ); + } - } - `, + expandByScalar( scalar ) { - blending: NoBlending, - depthTest: false, - depthWrite: false + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } ); + return this; - return shaderMaterial; + } -} + containsPoint( point ) { -function _getCommonVertexShader() { + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; - return /* glsl */` + } - precision mediump float; - precision mediump int; + containsBox( box ) { - attribute vec3 position; - attribute vec2 uv; - attribute float faceIndex; + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; - varying vec3 vOutputDirection; + } - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { + getParameter( point, target ) { - uv = 2.0 * uv - 1.0; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - vec3 direction = vec3( uv, 1.0 ); + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); - if ( face == 0.0 ) { + } - direction = direction.zyx; // ( 1, v, u ) pos x + intersectsBox( box ) { - } else if ( face == 1.0 ) { + // using 4 splitting planes to rule out intersections - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; - } else if ( face == 2.0 ) { + } - direction.x *= -1.0; // ( -u, v, 1 ) pos z + clampPoint( point, target ) { - } else if ( face == 3.0 ) { + return target.copy( point ).clamp( this.min, this.max ); - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x + } - } else if ( face == 4.0 ) { + distanceToPoint( point ) { - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y + const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - } else if ( face == 5.0 ) { + } - direction.z *= -1.0; // ( u, v, -1 ) neg z + intersect( box ) { - } + this.min.max( box.min ); + this.max.min( box.max ); - return direction; + return this; - } + } - void main() { + union( box ) { - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); + this.min.min( box.min ); + this.max.max( box.max ); - } - `; + return this; -} + } -function _getEncodings() { + translate( offset ) { - return /* glsl */` + this.min.add( offset ); + this.max.add( offset ); + + return this; - uniform int inputEncoding; - uniform int outputEncoding; + } + + equals( box ) { - #include + return box.min.equals( this.min ) && box.max.equals( this.max ); - vec4 inputTexelToLinear( vec4 value ) { + } - if ( inputEncoding == 0 ) { +} - return value; +const _startP = /*@__PURE__*/ new Vector3(); +const _startEnd = /*@__PURE__*/ new Vector3(); - } else if ( inputEncoding == 1 ) { +class Line3 { - return sRGBToLinear( value ); + constructor( start = new Vector3(), end = new Vector3() ) { - } else if ( inputEncoding == 2 ) { + this.start = start; + this.end = end; - return RGBEToLinear( value ); + } - } else if ( inputEncoding == 3 ) { + set( start, end ) { - return RGBMToLinear( value, 7.0 ); + this.start.copy( start ); + this.end.copy( end ); - } else if ( inputEncoding == 4 ) { + return this; - return RGBMToLinear( value, 16.0 ); + } - } else if ( inputEncoding == 5 ) { + copy( line ) { - return RGBDToLinear( value, 256.0 ); + this.start.copy( line.start ); + this.end.copy( line.end ); - } else { + return this; - return GammaToLinear( value, 2.2 ); + } - } + getCenter( target ) { - } + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - vec4 linearToOutputTexel( vec4 value ) { + } - if ( outputEncoding == 0 ) { + delta( target ) { - return value; + return target.subVectors( this.end, this.start ); - } else if ( outputEncoding == 1 ) { + } - return LinearTosRGB( value ); + distanceSq() { - } else if ( outputEncoding == 2 ) { + return this.start.distanceToSquared( this.end ); - return LinearToRGBE( value ); + } - } else if ( outputEncoding == 3 ) { + distance() { - return LinearToRGBM( value, 7.0 ); + return this.start.distanceTo( this.end ); - } else if ( outputEncoding == 4 ) { + } - return LinearToRGBM( value, 16.0 ); + at( t, target ) { - } else if ( outputEncoding == 5 ) { + return this.delta( target ).multiplyScalar( t ).add( this.start ); - return LinearToRGBD( value, 256.0 ); + } - } else { + closestPointToPointParameter( point, clampToLine ) { - return LinearToGamma( value, 2.2 ); + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); - } + const startEnd2 = _startEnd.dot( _startEnd ); + const startEnd_startP = _startEnd.dot( _startP ); - } + let t = startEnd_startP / startEnd2; - vec4 envMapTexelToLinear( vec4 color ) { + if ( clampToLine ) { - return inputTexelToLinear( color ); + t = clamp( t, 0, 1 ); } - `; -} + return t; -const LineStrip = 0; -const LinePieces = 1; -const NoColors = 0; -const FaceColors = 1; -const VertexColors = 2; + } -function MeshFaceMaterial( materials ) { + closestPointToPoint( point, clampToLine, target ) { - console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); - return materials; + const t = this.closestPointToPointParameter( point, clampToLine ); -} + return this.delta( target ).multiplyScalar( t ).add( this.start ); -function MultiMaterial( materials = [] ) { + } - console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); - materials.isMultiMaterial = true; - materials.materials = materials; - materials.clone = function () { + applyMatrix4( matrix ) { - return materials.slice(); + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - }; + return this; - return materials; + } -} + equals( line ) { -function PointCloud( geometry, material ) { + return line.start.equals( this.start ) && line.end.equals( this.end ); - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - return new Points( geometry, material ); + } -} + clone() { -function Particle( material ) { + return new this.constructor().copy( this ); - console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); - return new Sprite( material ); + } } -function ParticleSystem( geometry, material ) { +const _vector$3 = /*@__PURE__*/ new Vector3(); - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - return new Points( geometry, material ); +class SpotLightHelper extends Object3D { -} + constructor( light, color ) { -function PointCloudMaterial( parameters ) { + super(); - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + this.light = light; + this.light.updateMatrixWorld(); -} + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; -function ParticleBasicMaterial( parameters ) { + this.color = color; - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + const geometry = new BufferGeometry(); -} + const 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 + ]; -function ParticleSystemMaterial( parameters ) { + for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + const p1 = ( i / l ) * Math.PI * 2; + const p2 = ( j / l ) * Math.PI * 2; -} + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); -function Vertex( x, y, z ) { + } - console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); - return new Vector3( x, y, z ); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); -} + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); -// + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); -function DynamicBufferAttribute( array, itemSize ) { + this.update(); - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' ); - return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage ); + } -} + dispose() { -function Int8Attribute( array, itemSize ) { + this.cone.geometry.dispose(); + this.cone.material.dispose(); - console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); - return new Int8BufferAttribute( array, itemSize ); + } -} + update() { -function Uint8Attribute( array, itemSize ) { + this.light.updateMatrixWorld(); - console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); - return new Uint8BufferAttribute( array, itemSize ); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan( this.light.angle ); -} + this.cone.scale.set( coneWidth, coneWidth, coneLength ); -function Uint8ClampedAttribute( array, itemSize ) { + _vector$3.setFromMatrixPosition( this.light.target.matrixWorld ); - console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); - return new Uint8ClampedBufferAttribute( array, itemSize ); + this.cone.lookAt( _vector$3 ); -} + if ( this.color !== undefined ) { -function Int16Attribute( array, itemSize ) { + this.cone.material.color.set( this.color ); - console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); - return new Int16BufferAttribute( array, itemSize ); + } else { -} + this.cone.material.color.copy( this.light.color ); -function Uint16Attribute( array, itemSize ) { + } - console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); - return new Uint16BufferAttribute( array, itemSize ); + } } -function Int32Attribute( array, itemSize ) { +const _vector$2 = /*@__PURE__*/ new Vector3(); +const _boneMatrix = /*@__PURE__*/ new Matrix4(); +const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + - console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); - return new Int32BufferAttribute( array, itemSize ); +class SkeletonHelper extends LineSegments { -} + constructor( object ) { -function Uint32Attribute( array, itemSize ) { + const bones = getBoneList( object ); - console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); - return new Uint32BufferAttribute( array, itemSize ); + const geometry = new BufferGeometry(); -} + const vertices = []; + const colors = []; + + const color1 = new Color( 0, 0, 1 ); + const color2 = new Color( 0, 1, 0 ); -function Float32Attribute( array, itemSize ) { + for ( let i = 0; i < bones.length; i ++ ) { - console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); - return new Float32BufferAttribute( array, itemSize ); + const bone = bones[ i ]; -} + if ( bone.parent && bone.parent.isBone ) { -function Float64Attribute( array, itemSize ) { + vertices.push( 0, 0, 0 ); + vertices.push( 0, 0, 0 ); + colors.push( color1.r, color1.g, color1.b ); + colors.push( color2.r, color2.g, color2.b ); - console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); - return new Float64BufferAttribute( array, itemSize ); + } -} + } -// + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -Curve.create = function ( construct, getPoint ) { + const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); - console.log( 'THREE.Curve.create() has been deprecated' ); + super( geometry, material ); - construct.prototype = Object.create( Curve.prototype ); - construct.prototype.constructor = construct; - construct.prototype.getPoint = getPoint; + this.isSkeletonHelper = true; - return construct; + this.type = 'SkeletonHelper'; -}; + this.root = object; + this.bones = bones; -// + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; -Path.prototype.fromPoints = function ( points ) { + } - console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); - return this.setFromPoints( points ); + updateMatrixWorld( force ) { -}; + const bones = this.bones; -// + const geometry = this.geometry; + const position = geometry.getAttribute( 'position' ); -function AxisHelper( size ) { + _matrixWorldInv.copy( this.root.matrixWorld ).invert(); - console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); - return new AxesHelper( size ); + for ( let i = 0, j = 0; i < bones.length; i ++ ) { -} + const bone = bones[ i ]; -function BoundingBoxHelper( object, color ) { + if ( bone.parent && bone.parent.isBone ) { - console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); - return new BoxHelper( object, color ); + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z ); -} + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z ); -function EdgesHelper( object, hex ) { + j += 2; - console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); - return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + } -} + } -GridHelper.prototype.setColors = function () { + geometry.getAttribute( 'position' ).needsUpdate = true; - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); + super.updateMatrixWorld( force ); -}; + } -SkeletonHelper.prototype.update = function () { +} - console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); -}; +function getBoneList( object ) { -function WireframeHelper( object, hex ) { + const boneList = []; - console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); - return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + if ( object.isBone === true ) { -} + boneList.push( object ); -// + } -Loader.prototype.extractUrlBase = function ( url ) { + for ( let i = 0; i < object.children.length; i ++ ) { - console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); - return LoaderUtils.extractUrlBase( url ); + boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); -}; + } -Loader.Handlers = { + return boneList; - add: function ( /* regex, loader */ ) { +} - console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' ); +class PointLightHelper extends Mesh { - }, + constructor( light, sphereSize, color ) { - get: function ( /* file */ ) { + const geometry = new SphereGeometry( sphereSize, 4, 2 ); + const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); - console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' ); + super( geometry, material ); - } + this.light = light; + this.light.updateMatrixWorld(); -}; + this.color = color; -function XHRLoader( manager ) { + this.type = 'PointLightHelper'; - console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); - return new FileLoader( manager ); + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; -} + this.update(); -function BinaryTextureLoader( manager ) { - console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); - return new DataTextureLoader( manager ); + /* + // TODO: delete this comment? + const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); -} + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); -// + const d = light.distance; -Box2.prototype.center = function ( optionalTarget ) { + if ( d === 0.0 ) { - console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + this.lightDistance.visible = false; -}; + } else { -Box2.prototype.empty = function () { + this.lightDistance.scale.set( d, d, d ); - console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); + } -}; + this.add( this.lightDistance ); + */ -Box2.prototype.isIntersectionBox = function ( box ) { + } - console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + dispose() { -}; + this.geometry.dispose(); + this.material.dispose(); -Box2.prototype.size = function ( optionalTarget ) { + } - console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); + update() { -}; + if ( this.color !== undefined ) { -// + this.material.color.set( this.color ); -Box3.prototype.center = function ( optionalTarget ) { + } else { - console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + this.material.color.copy( this.light.color ); -}; + } -Box3.prototype.empty = function () { + /* + const d = this.light.distance; - console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); + if ( d === 0.0 ) { -}; + this.lightDistance.visible = false; -Box3.prototype.isIntersectionBox = function ( box ) { + } else { - console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); -}; + } + */ -Box3.prototype.isIntersectionSphere = function ( sphere ) { + } - console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); +} -}; +const _vector$1 = /*@__PURE__*/ new Vector3(); +const _color1 = /*@__PURE__*/ new Color(); +const _color2 = /*@__PURE__*/ new Color(); -Box3.prototype.size = function ( optionalTarget ) { +class HemisphereLightHelper extends Object3D { - console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); + constructor( light, size, color ) { -}; + super(); -// + this.light = light; + this.light.updateMatrixWorld(); -Sphere.prototype.empty = function () { + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); + this.color = color; -}; + const geometry = new OctahedronGeometry( size ); + geometry.rotateY( Math.PI * 0.5 ); -// + this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + if ( this.color === undefined ) this.material.vertexColors = true; -Frustum.prototype.setFromMatrix = function ( m ) { + const position = geometry.getAttribute( 'position' ); + const colors = new Float32Array( position.count * 3 ); - console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' ); - return this.setFromProjectionMatrix( m ); + geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); -}; + this.add( new Mesh( geometry, this.material ) ); -// + this.update(); -Line3.prototype.center = function ( optionalTarget ) { + } - console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + dispose() { -}; + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); -// + } -MathUtils.random16 = function () { + update() { - console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); + const mesh = this.children[ 0 ]; -}; + if ( this.color !== undefined ) { -MathUtils.nearestPowerOfTwo = function ( value ) { + this.material.color.set( this.color ); - console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' ); - return MathUtils.floorPowerOfTwo( value ); + } else { -}; + const colors = mesh.geometry.getAttribute( 'color' ); -MathUtils.nextPowerOfTwo = function ( value ) { + _color1.copy( this.light.color ); + _color2.copy( this.light.groundColor ); - console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' ); - return MathUtils.ceilPowerOfTwo( value ); + for ( let i = 0, l = colors.count; i < l; i ++ ) { -}; + const color = ( i < ( l / 2 ) ) ? _color1 : _color2; -// + colors.setXYZ( i, color.r, color.g, color.b ); -Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) { + } - console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); + colors.needsUpdate = true; -}; + } -Matrix3.prototype.multiplyVector3 = function ( vector ) { + mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); + } -}; +} -Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) { +class GridHelper extends LineSegments { - console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); + constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { -}; + color1 = new Color( color1 ); + color2 = new Color( color2 ); -Matrix3.prototype.applyToBufferAttribute = function ( attribute ) { + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; - console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' ); - return attribute.applyMatrix3( this ); + const vertices = [], colors = []; -}; + for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { -Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { + vertices.push( - halfSize, 0, k, halfSize, 0, k ); + vertices.push( k, 0, - halfSize, k, 0, halfSize ); - console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); + const color = i === center ? color1 : color2; -}; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; -Matrix3.prototype.getInverse = function ( matrix ) { + } - console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -}; + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); -// + super( geometry, material ); -Matrix4.prototype.extractPosition = function ( m ) { + this.type = 'GridHelper'; - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); + } -}; +} -Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) { +class PolarGridHelper extends LineSegments { - console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' ); - return this.toArray( array, offset ); + constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { -}; + color1 = new Color( color1 ); + color2 = new Color( color2 ); -Matrix4.prototype.getPosition = function () { + const vertices = []; + const colors = []; - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - return new Vector3().setFromMatrixColumn( this, 3 ); + // create the sectors -}; + if ( sectors > 1 ) { -Matrix4.prototype.setRotationFromQuaternion = function ( q ) { + for ( let i = 0; i < sectors; i ++ ) { - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - return this.makeRotationFromQuaternion( q ); + const v = ( i / sectors ) * ( Math.PI * 2 ); -}; + const x = Math.sin( v ) * radius; + const z = Math.cos( v ) * radius; -Matrix4.prototype.multiplyToArray = function () { + vertices.push( 0, 0, 0 ); + vertices.push( x, 0, z ); - console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); + const color = ( i & 1 ) ? color1 : color2; -}; + colors.push( color.r, color.g, color.b ); + colors.push( color.r, color.g, color.b ); -Matrix4.prototype.multiplyVector3 = function ( vector ) { + } - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + } -}; + // create the rings -Matrix4.prototype.multiplyVector4 = function ( vector ) { + for ( let i = 0; i < rings; i ++ ) { - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + const color = ( i & 1 ) ? color1 : color2; -}; + const r = radius - ( radius / rings * i ); -Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) { + for ( let j = 0; j < divisions; j ++ ) { - console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); + // first vertex -}; + let v = ( j / divisions ) * ( Math.PI * 2 ); -Matrix4.prototype.rotateAxis = function ( v ) { + let x = Math.sin( v ) * r; + let z = Math.cos( v ) * r; - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - v.transformDirection( this ); + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); -}; + // second vertex -Matrix4.prototype.crossVector = function ( vector ) { + v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; -}; + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); -Matrix4.prototype.translate = function () { + } - console.error( 'THREE.Matrix4: .translate() has been removed.' ); + } -}; + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -Matrix4.prototype.rotateX = function () { + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); + super( geometry, material ); -}; + this.type = 'PolarGridHelper'; -Matrix4.prototype.rotateY = function () { + } - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); +} -}; +const _v1 = /*@__PURE__*/ new Vector3(); +const _v2 = /*@__PURE__*/ new Vector3(); +const _v3 = /*@__PURE__*/ new Vector3(); -Matrix4.prototype.rotateZ = function () { +class DirectionalLightHelper extends Object3D { - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); + constructor( light, size, color ) { -}; + super(); -Matrix4.prototype.rotateByAxis = function () { + this.light = light; + this.light.updateMatrixWorld(); - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; -}; + this.color = color; -Matrix4.prototype.applyToBufferAttribute = function ( attribute ) { + if ( size === undefined ) size = 1; - console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' ); - return attribute.applyMatrix4( this ); + let geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); -}; + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); -Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) { + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); - console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); + geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); -}; + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); -Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) { + this.update(); - console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); - return this.makePerspective( left, right, top, bottom, near, far ); + } -}; + dispose() { -Matrix4.prototype.getInverse = function ( matrix ) { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); - console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' ); - return this.copy( matrix ).invert(); + } -}; + update() { -// + _v1.setFromMatrixPosition( this.light.matrixWorld ); + _v2.setFromMatrixPosition( this.light.target.matrixWorld ); + _v3.subVectors( _v2, _v1 ); -Plane.prototype.isIntersectionLine = function ( line ) { + this.lightPlane.lookAt( _v2 ); - console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); - return this.intersectsLine( line ); + if ( this.color !== undefined ) { -}; + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); -// + } else { -Quaternion.prototype.multiplyVector3 = function ( vector ) { + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); + } -}; + this.targetLine.lookAt( _v2 ); + this.targetLine.scale.z = _v3.length(); -Quaternion.prototype.inverse = function ( ) { + } - console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' ); - return this.invert(); +} -}; +const _vector = /*@__PURE__*/ new Vector3(); +const _camera = /*@__PURE__*/ new Camera(); -// +/** + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html + */ -Ray.prototype.isIntersectionBox = function ( box ) { +class CameraHelper extends LineSegments { - console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + constructor( camera ) { -}; + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); -Ray.prototype.isIntersectionPlane = function ( plane ) { + const vertices = []; + const colors = []; - console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); - return this.intersectsPlane( plane ); + const pointMap = {}; -}; + // near -Ray.prototype.isIntersectionSphere = function ( sphere ) { + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); - console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); + // far -}; + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); -// + // sides -Triangle.prototype.area = function () { + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); - console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); - return this.getArea(); + // cone -}; + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); -Triangle.prototype.barycoordFromPoint = function ( point, target ) { + // up - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return this.getBarycoord( point, target ); + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); -}; + // target -Triangle.prototype.midpoint = function ( target ) { + addLine( 'c', 't' ); + addLine( 'p', 'c' ); - console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); - return this.getMidpoint( target ); + // cross -}; + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); -Triangle.prototypenormal = function ( target ) { + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return this.getNormal( target ); + function addLine( a, b ) { -}; + addPoint( a ); + addPoint( b ); -Triangle.prototype.plane = function ( target ) { + } - console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); - return this.getPlane( target ); + function addPoint( id ) { -}; + vertices.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); -Triangle.barycoordFromPoint = function ( point, a, b, c, target ) { + if ( pointMap[ id ] === undefined ) { - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return Triangle.getBarycoord( point, a, b, c, target ); + pointMap[ id ] = []; -}; + } -Triangle.normal = function ( a, b, c, target ) { + pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return Triangle.getNormal( a, b, c, target ); + } -}; + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); -// + super( geometry, material ); -Shape.prototype.extractAllPoints = function ( divisions ) { + this.type = 'CameraHelper'; - console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); - return this.extractPoints( divisions ); + this.camera = camera; + if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); -}; + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; -Shape.prototype.extrude = function ( options ) { + this.pointMap = pointMap; - console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); - return new ExtrudeGeometry( this, options ); + this.update(); -}; + // colors -Shape.prototype.makeGeometry = function ( options ) { + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); - console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); - return new ShapeGeometry( this, options ); + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); -}; + } -// + setColors( frustum, cone, up, target, cross ) { -Vector2.prototype.fromAttribute = function ( attribute, index, offset ) { + const geometry = this.geometry; - console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + const colorAttribute = geometry.getAttribute( 'color' ); -}; + // near -Vector2.prototype.distanceToManhattan = function ( v ) { + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 - console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); + // far -}; + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 -Vector2.prototype.lengthManhattan = function () { + // sides - console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 -}; + // cone -// + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 -Vector3.prototype.setEulerFromRotationMatrix = function () { + // up - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 -}; + // target -Vector3.prototype.setEulerFromQuaternion = function () { + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); + // cross -}; + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 -Vector3.prototype.getPositionFromMatrix = function ( m ) { + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - return this.setFromMatrixPosition( m ); + colorAttribute.needsUpdate = true; -}; + } -Vector3.prototype.getScaleFromMatrix = function ( m ) { + update() { - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - return this.setFromMatrixScale( m ); + const geometry = this.geometry; + const pointMap = this.pointMap; -}; + const w = 1, h = 1; -Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) { + // we need just camera projection matrix inverse + // world matrix must be identity - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - return this.setFromMatrixColumn( matrix, index ); + _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); -}; + // center / target -Vector3.prototype.applyProjection = function ( m ) { + setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); + setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); - console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); - return this.applyMatrix4( m ); + // near -}; + setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); + setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); + setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); + setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); -Vector3.prototype.fromAttribute = function ( attribute, index, offset ) { + // far - console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); + setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); + setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); + setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); -}; + // up -Vector3.prototype.distanceToManhattan = function ( v ) { + setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); + setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); + setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); - console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); + // cross -}; + setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); + setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); + setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); + setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); -Vector3.prototype.lengthManhattan = function () { + setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); + setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); + setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); + setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); - console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); + geometry.getAttribute( 'position' ).needsUpdate = true; -}; + } -// + dispose() { -Vector4.prototype.fromAttribute = function ( attribute, index, offset ) { + this.geometry.dispose(); + this.material.dispose(); - console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + } -}; +} -Vector4.prototype.lengthManhattan = function () { - console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); +function setPoint( point, pointMap, geometry, camera, x, y, z ) { -}; + _vector.set( x, y, z ).unproject( camera ); -// + const points = pointMap[ point ]; -Object3D.prototype.getChildByName = function ( name ) { + if ( points !== undefined ) { - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); + const position = geometry.getAttribute( 'position' ); -}; + for ( let i = 0, l = points.length; i < l; i ++ ) { -Object3D.prototype.renderDepth = function () { + position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z ); - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); + } -}; + } -Object3D.prototype.translate = function ( distance, axis ) { +} - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); +const _box = /*@__PURE__*/ new Box3(); -}; +class BoxHelper extends LineSegments { -Object3D.prototype.getWorldRotation = function () { + constructor( object, color = 0xffff00 ) { - console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); + const 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 ] ); + const positions = new Float32Array( 8 * 3 ); -}; + const geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); -Object3D.prototype.applyMatrix = function ( matrix ) { + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); + this.object = object; + this.type = 'BoxHelper'; -}; + this.matrixAutoUpdate = false; -Object.defineProperties( Object3D.prototype, { + this.update(); - eulerOrder: { - get: function () { + } - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - return this.rotation.order; + update( object ) { - }, - set: function ( value ) { + if ( object !== undefined ) { - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - this.rotation.order = value; + console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); } - }, - useQuaternion: { - get: function () { - - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); - }, - set: function () { + if ( this.object !== undefined ) { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + _box.setFromObject( this.object ); } - } -} ); + if ( _box.isEmpty() ) return; -Mesh.prototype.setDrawMode = function () { + const min = _box.min; + const max = _box.max; - console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); + /* + 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 + */ -Object.defineProperties( Mesh.prototype, { + const position = this.geometry.attributes.position; + const array = position.array; - drawMode: { - get: function () { + 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; - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' ); - return TrianglesDrawMode; + position.needsUpdate = true; - }, - set: function () { + this.geometry.computeBoundingSphere(); - console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); - } } -} ); - -Object.defineProperties( LOD.prototype, { + setFromObject( object ) { - objects: { - get: function () { + this.object = object; + this.update(); - console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); - return this.levels; + return this; - } } -} ); - -Object.defineProperty( Skeleton.prototype, 'useVertexTexture', { - - get: function () { + copy( source, recursive ) { - console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); + super.copy( source, recursive ); - }, - set: function () { + this.object = source.object; - console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); + return this; } -} ); - -SkinnedMesh.prototype.initBones = function () { - - console.error( 'THREE.SkinnedMesh: initBones() has been removed.' ); +} -}; +class Box3Helper extends LineSegments { -Object.defineProperty( Curve.prototype, '__arcLengthDivisions', { + constructor( box, color = 0xffff00 ) { - get: function () { + const 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 ] ); - console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); - return this.arcLengthDivisions; + const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; - }, - set: function ( value ) { + const geometry = new BufferGeometry(); - console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); - this.arcLengthDivisions = value; + geometry.setIndex( new BufferAttribute( indices, 1 ) ); - } + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); -} ); + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); -// + this.box = box; -PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { + this.type = 'Box3Helper'; - console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' + - 'Use .setFocalLength and .filmGauge for a photographic setup.' ); + this.geometry.computeBoundingSphere(); - if ( filmGauge !== undefined ) this.filmGauge = filmGauge; - this.setFocalLength( focalLength ); + } -}; + updateMatrixWorld( force ) { -// + const box = this.box; -Object.defineProperties( Light.prototype, { - onlyShadow: { - set: function () { + if ( box.isEmpty() ) return; - console.warn( 'THREE.Light: .onlyShadow has been removed.' ); + box.getCenter( this.position ); - } - }, - shadowCameraFov: { - set: function ( value ) { + box.getSize( this.scale ); - console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); - this.shadow.camera.fov = value; + this.scale.multiplyScalar( 0.5 ); - } - }, - shadowCameraLeft: { - set: function ( value ) { + super.updateMatrixWorld( force ); - 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; +class PlaneHelper extends Line { - } - }, - shadowCameraTop: { - set: function ( value ) { + constructor( plane, size = 1, hex = 0xffff00 ) { - console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); - this.shadow.camera.top = value; + const color = hex; - } - }, - shadowCameraBottom: { - set: function ( value ) { + const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; - console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); - this.shadow.camera.bottom = value; + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); - } - }, - shadowCameraNear: { - set: function ( value ) { + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); - this.shadow.camera.near = value; + this.type = 'PlaneHelper'; - } - }, - shadowCameraFar: { - set: function ( value ) { + this.plane = plane; - console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); - this.shadow.camera.far = value; + this.size = size; - } - }, - shadowCameraVisible: { - set: function () { + const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; - console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); - } - }, - shadowBias: { - set: function ( value ) { + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); - console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); - this.shadow.bias = value; + } - } - }, - shadowDarkness: { - set: function () { + updateMatrixWorld( force ) { - console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); + this.position.set( 0, 0, 0 ); - } - }, - shadowMapWidth: { - set: function ( value ) { + this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 ); - console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); - this.shadow.mapSize.width = value; + this.lookAt( this.plane.normal ); - } - }, - shadowMapHeight: { - set: function ( value ) { + this.translateZ( - this.plane.constant ); - console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); - this.shadow.mapSize.height = value; + super.updateMatrixWorld( force ); - } } -} ); -// - -Object.defineProperties( BufferAttribute.prototype, { +} - length: { - get: function () { +const _axis = /*@__PURE__*/ new Vector3(); +let _lineGeometry, _coneGeometry; - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); - return this.array.length; +class ArrowHelper extends Object3D { - } - }, - dynamic: { - get: function () { + // dir is assumed to be normalized - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; + constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { - }, - set: function ( /* value */ ) { + super(); - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - this.setUsage( DynamicDrawUsage ); + this.type = 'ArrowHelper'; - } - } + if ( _lineGeometry === undefined ) { -} ); + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); -BufferAttribute.prototype.setDynamic = function ( value ) { + _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 ); + _coneGeometry.translate( 0, - 0.5, 0 ); - console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; + } -}; + this.position.copy( origin ); -BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) { + this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); - console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); + this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); -}, + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); -BufferAttribute.prototype.setArray = function ( /* array */ ) { + } - console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); + setDirection( dir ) { -}; + // dir is assumed to be normalized -// + if ( dir.y > 0.99999 ) { -BufferGeometry.prototype.addIndex = function ( index ) { + this.quaternion.set( 0, 0, 0, 1 ); - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); + } else if ( dir.y < - 0.99999 ) { -}; + this.quaternion.set( 1, 0, 0, 0 ); -BufferGeometry.prototype.addAttribute = function ( name, attribute ) { + } else { - console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' ); + _axis.set( dir.z, 0, - dir.x ).normalize(); - if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { + const radians = Math.acos( dir.y ); - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + this.quaternion.setFromAxisAngle( _axis, radians ); - return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + } } - if ( name === 'index' ) { + setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 + this.line.updateMatrix(); - return this; + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); } - return this.setAttribute( name, attribute ); + setColor( color ) { -}; + this.line.material.color.set( color ); + this.cone.material.color.set( color ); + + } -BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) { + copy( source ) { + + super.copy( source, false ); - if ( indexOffset !== undefined ) { + this.line.copy( source.line ); + this.cone.copy( source.cone ); - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); + return this; } - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); +} -}; +class AxesHelper extends LineSegments { -BufferGeometry.prototype.clearDrawCalls = function () { + constructor( size = 1 ) { - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); + const vertices = [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ]; -}; + const colors = [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ]; -BufferGeometry.prototype.computeOffsets = function () { + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); -}; + super( geometry, material ); -BufferGeometry.prototype.removeAttribute = function ( name ) { + this.type = 'AxesHelper'; - console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' ); + } - return this.deleteAttribute( name ); + setColors( xAxisColor, yAxisColor, zAxisColor ) { -}; + const color = new Color(); + const array = this.geometry.attributes.color.array; -BufferGeometry.prototype.applyMatrix = function ( matrix ) { + color.set( xAxisColor ); + color.toArray( array, 0 ); + color.toArray( array, 3 ); - console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' ); - return this.applyMatrix4( matrix ); + color.set( yAxisColor ); + color.toArray( array, 6 ); + color.toArray( array, 9 ); -}; + color.set( zAxisColor ); + color.toArray( array, 12 ); + color.toArray( array, 15 ); -Object.defineProperties( BufferGeometry.prototype, { + this.geometry.attributes.color.needsUpdate = true; - drawcalls: { - get: function () { + return this; - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; + } - } - }, - offsets: { - get: function () { + dispose() { - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; + this.geometry.dispose(); + this.material.dispose(); - } } -} ); +} -Object.defineProperties( InstancedBufferGeometry.prototype, { +class ShapePath { - maxInstancedCount: { - get: function () { + constructor() { - console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' ); - return this.instanceCount; + this.type = 'ShapePath'; - }, - set: function ( value ) { + this.color = new Color(); - console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' ); - this.instanceCount = value; + this.subPaths = []; + this.currentPath = null; - } } -} ); + moveTo( x, y ) { + + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); -Object.defineProperties( Raycaster.prototype, { + return this; - linePrecision: { - get: function () { + } - console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' ); - return this.params.Line.threshold; + lineTo( x, y ) { - }, - set: function ( value ) { + this.currentPath.lineTo( x, y ); - console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' ); - this.params.Line.threshold = value; + return this; - } } -} ); + quadraticCurveTo( aCPx, aCPy, aX, aY ) { -Object.defineProperties( InterleavedBuffer.prototype, { + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); - dynamic: { - get: function () { + return this; - console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; + } - }, - set: function ( value ) { + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); - this.setUsage( value ); + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); - } - } + return this; -} ); + } -InterleavedBuffer.prototype.setDynamic = function ( value ) { + splineThru( pts ) { - console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; + this.currentPath.splineThru( pts ); -}; + return this; -InterleavedBuffer.prototype.setArray = function ( /* array */ ) { + } - console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); + toShapes( isCCW ) { -}; + function toShapesNoHoles( inSubpaths ) { -// + const shapes = []; -ExtrudeGeometry.prototype.getArrays = function () { + for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { - console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' ); + const tmpPath = inSubpaths[ i ]; -}; + const tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; -ExtrudeGeometry.prototype.addShapeList = function () { + shapes.push( tmpShape ); - console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' ); + } -}; + return shapes; -ExtrudeGeometry.prototype.addShape = function () { + } - console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' ); + function isPointInsidePolygon( inPt, inPolygon ) { -}; + const 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 + let inside = false; + for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { -Scene.prototype.dispose = function () { + let edgeLowPt = inPolygon[ p ]; + let edgeHighPt = inPolygon[ q ]; - console.error( 'THREE.Scene: .dispose() has been removed.' ); + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; -}; + if ( Math.abs( edgeDy ) > Number.EPSILON ) { -// + // not parallel + if ( edgeDy < 0 ) { -Object.defineProperties( Uniform.prototype, { + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; - dynamic: { - set: function () { + } - console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' ); + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; - } - }, - onUpdate: { - value: function () { + if ( inPt.y === edgeLowPt.y ) { - console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); - return this; + if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! - } - } + } else { -} ); + const 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 -// + } -Object.defineProperties( Material.prototype, { + } else { - wrapAround: { - get: function () { + // 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.Material: .wrapAround has been removed.' ); + } - }, - set: function () { + } - console.warn( 'THREE.Material: .wrapAround has been removed.' ); + return inside; } - }, - - overdraw: { - get: function () { - console.warn( 'THREE.Material: .overdraw has been removed.' ); - - }, - set: function () { + const isClockWise = ShapeUtils.isClockWise; - console.warn( 'THREE.Material: .overdraw has been removed.' ); + const subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - } - }, + let solid, tmpPath, tmpShape; + const shapes = []; - wrapRGB: { - get: function () { + if ( subPaths.length === 1 ) { - console.warn( 'THREE.Material: .wrapRGB has been removed.' ); - return new Color(); + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; } - }, - shading: { - get: function () { - - console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - }, - set: function ( value ) { + // console.log("Holes first", holesFirst); - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( value === FlatShading ); + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; - } - }, + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - stencilMask: { - get: function () { + for ( let i = 0, l = subPaths.length; i < l; i ++ ) { - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - return this.stencilFuncMask; + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - }, - set: function ( value ) { + if ( solid ) { - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - this.stencilFuncMask = value; + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - } - } + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; -} ); + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; -Object.defineProperties( MeshPhongMaterial.prototype, { + //console.log('cw', i); - metal: { - get: function () { + } else { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); - return false; + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); - }, - set: function () { + //console.log('ccw', i); - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); + } } - } -} ); + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); -Object.defineProperties( MeshPhysicalMaterial.prototype, { - transparency: { - get: function () { + if ( newShapes.length > 1 ) { - console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' ); - return this.transmission; + let ambiguous = false; + let toChange = 0; - }, - set: function ( value ) { + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' ); - this.transmission = value; + betterShapeHoles[ sIdx ] = []; - } - } + } -} ); + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { -Object.defineProperties( ShaderMaterial.prototype, { + const sho = newShapeHoles[ sIdx ]; - derivatives: { - get: function () { + for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { - console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - return this.extensions.derivatives; + const ho = sho[ hIdx ]; + let hole_unassigned = true; - }, - set: function ( value ) { + for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - this.extensions.derivatives = value; + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { - } - } + if ( sIdx !== s2Idx ) toChange ++; -} ); + if ( hole_unassigned ) { -// + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); -WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) { + } else { - console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' ); - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + ambiguous = true; -}; + } -WebGLRenderer.prototype.animate = function ( callback ) { + } - console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' ); - this.setAnimationLoop( callback ); + } -}; + if ( hole_unassigned ) { -WebGLRenderer.prototype.getCurrentRenderTarget = function () { + betterShapeHoles[ sIdx ].push( ho ); - console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); - return this.getRenderTarget(); + } -}; + } -WebGLRenderer.prototype.getMaxAnisotropy = function () { + } - console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); - return this.capabilities.getMaxAnisotropy(); + if ( toChange > 0 && ambiguous === false ) { -}; + newShapeHoles = betterShapeHoles; -WebGLRenderer.prototype.getPrecision = function () { + } - console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); - return this.capabilities.precision; + } -}; + let tmpHoles; -WebGLRenderer.prototype.resetGLState = function () { + for ( let i = 0, il = newShapes.length; i < il; i ++ ) { - console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); - return this.state.reset(); + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; -}; + for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { -WebGLRenderer.prototype.supportsFloatTextures = function () { + tmpShape.holes.push( tmpHoles[ j ].h ); - console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); - return this.extensions.get( 'OES_texture_float' ); + } -}; + } -WebGLRenderer.prototype.supportsHalfFloatTextures = function () { + //console.log("shape", shapes); - console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); - return this.extensions.get( 'OES_texture_half_float' ); + return shapes; -}; + } -WebGLRenderer.prototype.supportsStandardDerivatives = function () { +} - console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); - return this.extensions.get( 'OES_standard_derivatives' ); +// Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf -}; +const _tables = /*@__PURE__*/ _generateTables(); -WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () { +function _generateTables() { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); + // float32 to float16 helpers -}; + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); -WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () { + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + for ( let i = 0; i < 256; ++ i ) { -}; + const e = i - 127; -WebGLRenderer.prototype.supportsBlendMinMax = function () { + // very small number (0, -0) - console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); - return this.extensions.get( 'EXT_blend_minmax' ); + if ( e < - 27 ) { -}; + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -WebGLRenderer.prototype.supportsVertexTextures = function () { + // small number (denorm) - console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); - return this.capabilities.vertexTextures; + } else if ( e < - 14 ) { -}; + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; -WebGLRenderer.prototype.supportsInstancedArrays = function () { + // normal number - console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); - return this.extensions.get( 'ANGLE_instanced_arrays' ); + } else if ( e <= 15 ) { -}; + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; -WebGLRenderer.prototype.enableScissorTest = function ( boolean ) { + // large number (Infinity, -Infinity) - console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); - this.setScissorTest( boolean ); + } else if ( e < 128 ) { -}; + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; -WebGLRenderer.prototype.initMaterial = function () { + // stay (NaN, Infinity, -Infinity) - console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); + } else { -}; + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; -WebGLRenderer.prototype.addPrePlugin = function () { + } - console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); + } -}; + // float16 to float32 helpers -WebGLRenderer.prototype.addPostPlugin = function () { + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); - console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); + for ( let i = 1; i < 1024; ++ i ) { -}; + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent -WebGLRenderer.prototype.updateShadowMap = function () { + // normalized + while ( ( m & 0x00800000 ) === 0 ) { - console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); + m <<= 1; + e -= 0x00800000; // decrement exponent -}; + } -WebGLRenderer.prototype.setFaceCulling = function () { + m &= ~ 0x00800000; // clear leading 1 bit + e += 0x38800000; // adjust bias - console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); + mantissaTable[ i ] = m | e; -}; + } -WebGLRenderer.prototype.allocTextureUnit = function () { + for ( let i = 1024; i < 2048; ++ i ) { - console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' ); + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); -}; + } -WebGLRenderer.prototype.setTexture = function () { + for ( let i = 1; i < 31; ++ i ) { - console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' ); + exponentTable[ i ] = i << 23; -}; + } -WebGLRenderer.prototype.setTexture2D = function () { + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; - console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' ); + for ( let i = 33; i < 63; ++ i ) { -}; + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); -WebGLRenderer.prototype.setTextureCube = function () { + } - console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' ); + exponentTable[ 63 ] = 0xc7800000; -}; + for ( let i = 1; i < 64; ++ i ) { -WebGLRenderer.prototype.getActiveMipMapLevel = function () { + if ( i !== 32 ) { - console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' ); - return this.getActiveMipmapLevel(); + offsetTable[ i ] = 1024; -}; + } -Object.defineProperties( WebGLRenderer.prototype, { + } - shadowMapEnabled: { - get: function () { + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable + }; - return this.shadowMap.enabled; +} - }, - set: function ( value ) { +// float32 to float16 - console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); - this.shadowMap.enabled = value; +function toHalfFloat( val ) { - } - }, - shadowMapType: { - get: function () { + if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); - return this.shadowMap.type; + val = clamp( val, - 65504, 65504 ); - }, - set: function ( value ) { + _tables.floatView[ 0 ] = val; + const f = _tables.uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] ); - console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); - this.shadowMap.type = value; +} - } - }, - shadowMapCullFace: { - get: function () { +// float16 to float32 - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; +function fromHalfFloat( val ) { - }, - set: function ( /* value */ ) { + const m = val >> 10; + _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ]; + return _tables.floatView[ 0 ]; - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); +} - } - }, - context: { - get: function () { +var DataUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + toHalfFloat: toHalfFloat, + fromHalfFloat: fromHalfFloat +}); - console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' ); - return this.getContext(); +// r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0 - } - }, - vr: { - get: function () { +function ImmediateRenderObject() { - console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' ); - return this.xr; + console.error( 'THREE.ImmediateRenderObject has been removed.' ); - } - }, - gammaInput: { - get: function () { +} - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); - return false; +// r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17 - }, - set: function () { +class WebGLMultisampleRenderTarget extends WebGLRenderTarget { - console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); + constructor( width, height, options ) { - } - }, - gammaOutput: { - get: function () { + console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' ); + super( width, height, options ); + this.samples = 4; - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - return false; + } - }, - set: function ( value ) { +} - console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); - this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding; +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce - } - }, - toneMappingWhitePoint: { - get: function () { +class DataTexture2DArray extends DataArrayTexture { - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); - return 1.0; + constructor( data, width, height, depth ) { - }, - set: function () { + console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' ); + super( data, width, height, depth ); - console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' ); + } - } - }, +} -} ); +// r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce -Object.defineProperties( WebGLShadowMap.prototype, { +class DataTexture3D extends Data3DTexture { - cullFace: { - get: function () { + constructor( data, width, height, depth ) { - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; + console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' ); + super( data, width, height, depth ); - }, - set: function ( /* cullFace */ ) { + } - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); +} - } - }, - renderReverseSided: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - return undefined; +class BoxBufferGeometry extends BoxGeometry { - }, - set: function () { + constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) { - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); + console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' ); + super( width, height, depth, widthSegments, heightSegments, depthSegments ); - } - }, - renderSingleSided: { - get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - return undefined; + } - }, - set: function () { +} - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); +// r144 - } - } +class CapsuleBufferGeometry extends CapsuleGeometry { -} ); + constructor( radius, length, capSegments, radialSegments ) { -function WebGLRenderTargetCube( width, height, options ) { + console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' ); + super( radius, length, capSegments, radialSegments ); - console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' ); - return new WebGLCubeRenderTarget( width, options ); + } } -// - -Object.defineProperties( WebGLRenderTarget.prototype, { +// r144 - wrapS: { - get: function () { +class CircleBufferGeometry extends CircleGeometry { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - return this.texture.wrapS; - - }, - set: function ( value ) { + constructor( radius, segments, thetaStart, thetaLength ) { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - this.texture.wrapS = value; + console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' ); + super( radius, segments, thetaStart, thetaLength ); - } - }, - wrapT: { - get: function () { + } - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - return this.texture.wrapT; +} - }, - set: function ( value ) { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - this.texture.wrapT = value; +class ConeBufferGeometry extends ConeGeometry { - } - }, - magFilter: { - get: function () { + constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - return this.texture.magFilter; + console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' ); + super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - }, - set: function ( value ) { + } - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - this.texture.magFilter = value; +} - } - }, - minFilter: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - return this.texture.minFilter; +class CylinderBufferGeometry extends CylinderGeometry { - }, - set: function ( value ) { + constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - this.texture.minFilter = value; + console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' ); + super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - } - }, - anisotropy: { - get: function () { + } - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - return this.texture.anisotropy; +} - }, - set: function ( value ) { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - this.texture.anisotropy = value; +class DodecahedronBufferGeometry extends DodecahedronGeometry { - } - }, - offset: { - get: function () { + constructor( radius, detail ) { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - return this.texture.offset; + console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' ); + super( radius, detail ); - }, - set: function ( value ) { + } - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - this.texture.offset = value; +} - } - }, - repeat: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - return this.texture.repeat; +class ExtrudeBufferGeometry extends ExtrudeGeometry { - }, - set: function ( value ) { + constructor( shapes, options ) { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - this.texture.repeat = value; + console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' ); + super( shapes, options ); - } - }, - format: { - get: function () { + } - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - return this.texture.format; +} - }, - set: function ( value ) { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - this.texture.format = value; +class IcosahedronBufferGeometry extends IcosahedronGeometry { - } - }, - type: { - get: function () { + constructor( radius, detail ) { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - return this.texture.type; + console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' ); + super( radius, detail ); - }, - set: function ( value ) { + } - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - this.texture.type = value; +} - } - }, - generateMipmaps: { - get: function () { +// r144 - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - return this.texture.generateMipmaps; +class LatheBufferGeometry extends LatheGeometry { - }, - set: function ( value ) { + constructor( points, segments, phiStart, phiLength ) { - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - this.texture.generateMipmaps = value; + console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' ); + super( points, segments, phiStart, phiLength ); - } } -} ); - -// +} -Object.defineProperties( Audio.prototype, { +// r144 - load: { - value: function ( file ) { +class OctahedronBufferGeometry extends OctahedronGeometry { - console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); - const scope = this; - const audioLoader = new AudioLoader(); - audioLoader.load( file, function ( buffer ) { + constructor( radius, detail ) { - scope.setBuffer( buffer ); + console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' ); + super( radius, detail ); - } ); - return this; + } - } - }, - startTime: { - set: function () { +} - console.warn( 'THREE.Audio: .startTime is now .play( delay ).' ); +// r144 - } - } +class PlaneBufferGeometry extends PlaneGeometry { -} ); + constructor( width, height, widthSegments, heightSegments ) { -AudioAnalyser.prototype.getData = function () { + console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' ); + super( width, height, widthSegments, heightSegments ); - console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); - return this.getFrequencyData(); + } -}; +} -// +// r144 -CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { +class PolyhedronBufferGeometry extends PolyhedronGeometry { - console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); - return this.update( renderer, scene ); + constructor( vertices, indices, radius, detail ) { -}; + console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' ); + super( vertices, indices, radius, detail ); -CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) { + } - console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' ); - return this.renderTarget.clear( renderer, color, depth, stencil ); +} -}; +// r144 -ImageUtils.crossOrigin = undefined; +class RingBufferGeometry extends RingGeometry { -ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) { + constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); + console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' ); + super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ); - const loader = new TextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); + } - const texture = loader.load( url, onLoad, undefined, onError ); +} - if ( mapping ) texture.mapping = mapping; +// r144 - return texture; +class ShapeBufferGeometry extends ShapeGeometry { -}; + constructor( shapes, curveSegments ) { -ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) { + console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' ); + super( shapes, curveSegments ); - console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); + } - const loader = new CubeTextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); +} - const texture = loader.load( urls, onLoad, undefined, onError ); +// r144 - if ( mapping ) texture.mapping = mapping; +class SphereBufferGeometry extends SphereGeometry { - return texture; + constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { -}; + console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' ); + super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ); -ImageUtils.loadCompressedTexture = function () { + } - console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); +} -}; +// r144 -ImageUtils.loadCompressedTextureCube = function () { +class TetrahedronBufferGeometry extends TetrahedronGeometry { - console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); + constructor( radius, detail ) { -}; + console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' ); + super( radius, detail ); -// + } -function CanvasRenderer() { +} - console.error( 'THREE.CanvasRenderer has been removed' ); +// r144 -} +class TorusBufferGeometry extends TorusGeometry { -// + constructor( radius, tube, radialSegments, tubularSegments, arc ) { -function JSONLoader() { + console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' ); + super( radius, tube, radialSegments, tubularSegments, arc ); - console.error( 'THREE.JSONLoader has been removed.' ); + } } -// +// r144 -const SceneUtils = { +class TorusKnotBufferGeometry extends TorusKnotGeometry { - createMultiMaterialObject: function ( /* geometry, materials */ ) { + constructor( radius, tube, tubularSegments, radialSegments, p, q ) { - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); + console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' ); + super( radius, tube, tubularSegments, radialSegments, p, q ); - }, + } - detach: function ( /* child, parent, scene */ ) { +} - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); +// r144 - }, +class TubeBufferGeometry extends TubeGeometry { - attach: function ( /* child, scene, parent */ ) { + constructor( path, tubularSegments, radius, radialSegments, closed ) { - console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); + console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' ); + super( path, tubularSegments, radius, radialSegments, closed ); } -}; - -// - -function LensFlare() { - - console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' ); - } if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - /* eslint-disable no-undef */ __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { revision: REVISION, } } ) ); - /* eslint-enable no-undef */ } @@ -48953,18 +49671,15 @@ var THREE = /*#__PURE__*/Object.freeze({ AudioListener: AudioListener, AudioLoader: AudioLoader, AxesHelper: AxesHelper, - AxisHelper: AxisHelper, BackSide: BackSide, BasicDepthPacking: BasicDepthPacking, BasicShadowMap: BasicShadowMap, - BinaryTextureLoader: BinaryTextureLoader, Bone: Bone, BooleanKeyframeTrack: BooleanKeyframeTrack, - BoundingBoxHelper: BoundingBoxHelper, Box2: Box2, Box3: Box3, Box3Helper: Box3Helper, - BoxBufferGeometry: BoxGeometry, + BoxBufferGeometry: BoxBufferGeometry, BoxGeometry: BoxGeometry, BoxHelper: BoxHelper, BufferAttribute: BufferAttribute, @@ -48974,19 +49689,21 @@ var THREE = /*#__PURE__*/Object.freeze({ Cache: Cache, Camera: Camera, CameraHelper: CameraHelper, - CanvasRenderer: CanvasRenderer, CanvasTexture: CanvasTexture, + CapsuleBufferGeometry: CapsuleBufferGeometry, + CapsuleGeometry: CapsuleGeometry, CatmullRomCurve3: CatmullRomCurve3, CineonToneMapping: CineonToneMapping, - CircleBufferGeometry: CircleGeometry, + CircleBufferGeometry: CircleBufferGeometry, CircleGeometry: CircleGeometry, ClampToEdgeWrapping: ClampToEdgeWrapping, Clock: Clock, Color: Color, ColorKeyframeTrack: ColorKeyframeTrack, + ColorManagement: ColorManagement, CompressedTexture: CompressedTexture, CompressedTextureLoader: CompressedTextureLoader, - ConeBufferGeometry: ConeGeometry, + ConeBufferGeometry: ConeBufferGeometry, ConeGeometry: ConeGeometry, CubeCamera: CubeCamera, CubeReflectionMapping: CubeReflectionMapping, @@ -48994,7 +49711,6 @@ var THREE = /*#__PURE__*/Object.freeze({ CubeTexture: CubeTexture, CubeTextureLoader: CubeTextureLoader, CubeUVReflectionMapping: CubeUVReflectionMapping, - CubeUVRefractionMapping: CubeUVRefractionMapping, CubicBezierCurve: CubicBezierCurve, CubicBezierCurve3: CubicBezierCurve3, CubicInterpolant: CubicInterpolant, @@ -49006,9 +49722,11 @@ var THREE = /*#__PURE__*/Object.freeze({ CurvePath: CurvePath, CustomBlending: CustomBlending, CustomToneMapping: CustomToneMapping, - CylinderBufferGeometry: CylinderGeometry, + CylinderBufferGeometry: CylinderBufferGeometry, CylinderGeometry: CylinderGeometry, Cylindrical: Cylindrical, + Data3DTexture: Data3DTexture, + DataArrayTexture: DataArrayTexture, DataTexture: DataTexture, DataTexture2DArray: DataTexture2DArray, DataTexture3D: DataTexture3D, @@ -49023,17 +49741,15 @@ var THREE = /*#__PURE__*/Object.freeze({ DirectionalLight: DirectionalLight, DirectionalLightHelper: DirectionalLightHelper, DiscreteInterpolant: DiscreteInterpolant, - DodecahedronBufferGeometry: DodecahedronGeometry, + DodecahedronBufferGeometry: DodecahedronBufferGeometry, DodecahedronGeometry: DodecahedronGeometry, DoubleSide: DoubleSide, DstAlphaFactor: DstAlphaFactor, DstColorFactor: DstColorFactor, - DynamicBufferAttribute: DynamicBufferAttribute, DynamicCopyUsage: DynamicCopyUsage, DynamicDrawUsage: DynamicDrawUsage, DynamicReadUsage: DynamicReadUsage, EdgesGeometry: EdgesGeometry, - EdgesHelper: EdgesHelper, EllipseCurve: EllipseCurve, EqualDepth: EqualDepth, EqualStencilFunc: EqualStencilFunc, @@ -49041,27 +49757,21 @@ var THREE = /*#__PURE__*/Object.freeze({ EquirectangularRefractionMapping: EquirectangularRefractionMapping, Euler: Euler, EventDispatcher: EventDispatcher, - ExtrudeBufferGeometry: ExtrudeGeometry, + ExtrudeBufferGeometry: ExtrudeBufferGeometry, ExtrudeGeometry: ExtrudeGeometry, - FaceColors: FaceColors, FileLoader: FileLoader, - FlatShading: FlatShading, Float16BufferAttribute: Float16BufferAttribute, - Float32Attribute: Float32Attribute, Float32BufferAttribute: Float32BufferAttribute, - Float64Attribute: Float64Attribute, Float64BufferAttribute: Float64BufferAttribute, FloatType: FloatType, Fog: Fog, FogExp2: FogExp2, - Font: Font, - FontLoader: FontLoader, + FramebufferTexture: FramebufferTexture, FrontSide: FrontSide, Frustum: Frustum, GLBufferAttribute: GLBufferAttribute, GLSL1: GLSL1, GLSL3: GLSL3, - GammaEncoding: GammaEncoding, GreaterDepth: GreaterDepth, GreaterEqualDepth: GreaterEqualDepth, GreaterEqualStencilFunc: GreaterEqualStencilFunc, @@ -49072,7 +49782,7 @@ var THREE = /*#__PURE__*/Object.freeze({ HemisphereLight: HemisphereLight, HemisphereLightHelper: HemisphereLightHelper, HemisphereLightProbe: HemisphereLightProbe, - IcosahedronBufferGeometry: IcosahedronGeometry, + IcosahedronBufferGeometry: IcosahedronBufferGeometry, IcosahedronGeometry: IcosahedronGeometry, ImageBitmapLoader: ImageBitmapLoader, ImageLoader: ImageLoader, @@ -49084,11 +49794,8 @@ var THREE = /*#__PURE__*/Object.freeze({ InstancedBufferGeometry: InstancedBufferGeometry, InstancedInterleavedBuffer: InstancedInterleavedBuffer, InstancedMesh: InstancedMesh, - Int16Attribute: Int16Attribute, Int16BufferAttribute: Int16BufferAttribute, - Int32Attribute: Int32Attribute, Int32BufferAttribute: Int32BufferAttribute, - Int8Attribute: Int8Attribute, Int8BufferAttribute: Int8BufferAttribute, IntType: IntType, InterleavedBuffer: InterleavedBuffer, @@ -49098,14 +49805,12 @@ var THREE = /*#__PURE__*/Object.freeze({ InterpolateLinear: InterpolateLinear, InterpolateSmooth: InterpolateSmooth, InvertStencilOp: InvertStencilOp, - JSONLoader: JSONLoader, KeepStencilOp: KeepStencilOp, KeyframeTrack: KeyframeTrack, LOD: LOD, - LatheBufferGeometry: LatheGeometry, + LatheBufferGeometry: LatheBufferGeometry, LatheGeometry: LatheGeometry, Layers: Layers, - LensFlare: LensFlare, LessDepth: LessDepth, LessEqualDepth: LessEqualDepth, LessEqualStencilFunc: LessEqualStencilFunc, @@ -49119,9 +49824,7 @@ var THREE = /*#__PURE__*/Object.freeze({ LineCurve3: LineCurve3, LineDashedMaterial: LineDashedMaterial, LineLoop: LineLoop, - LinePieces: LinePieces, LineSegments: LineSegments, - LineStrip: LineStrip, LinearEncoding: LinearEncoding, LinearFilter: LinearFilter, LinearInterpolant: LinearInterpolant, @@ -49129,11 +49832,11 @@ var THREE = /*#__PURE__*/Object.freeze({ LinearMipMapNearestFilter: LinearMipMapNearestFilter, LinearMipmapLinearFilter: LinearMipmapLinearFilter, LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearSRGBColorSpace: LinearSRGBColorSpace, LinearToneMapping: LinearToneMapping, Loader: Loader, LoaderUtils: LoaderUtils, LoadingManager: LoadingManager, - LogLuvEncoding: LogLuvEncoding, LoopOnce: LoopOnce, LoopPingPong: LoopPingPong, LoopRepeat: LoopRepeat, @@ -49142,7 +49845,6 @@ var THREE = /*#__PURE__*/Object.freeze({ MOUSE: MOUSE, Material: Material, MaterialLoader: MaterialLoader, - Math: MathUtils, MathUtils: MathUtils, Matrix3: Matrix3, Matrix4: Matrix4, @@ -49151,7 +49853,6 @@ var THREE = /*#__PURE__*/Object.freeze({ MeshBasicMaterial: MeshBasicMaterial, MeshDepthMaterial: MeshDepthMaterial, MeshDistanceMaterial: MeshDistanceMaterial, - MeshFaceMaterial: MeshFaceMaterial, MeshLambertMaterial: MeshLambertMaterial, MeshMatcapMaterial: MeshMatcapMaterial, MeshNormalMaterial: MeshNormalMaterial, @@ -49162,7 +49863,6 @@ var THREE = /*#__PURE__*/Object.freeze({ MinEquation: MinEquation, MirroredRepeatWrapping: MirroredRepeatWrapping, MixOperation: MixOperation, - MultiMaterial: MultiMaterial, MultiplyBlending: MultiplyBlending, MultiplyOperation: MultiplyOperation, NearestFilter: NearestFilter, @@ -49173,7 +49873,7 @@ var THREE = /*#__PURE__*/Object.freeze({ NeverDepth: NeverDepth, NeverStencilFunc: NeverStencilFunc, NoBlending: NoBlending, - NoColors: NoColors, + NoColorSpace: NoColorSpace, NoToneMapping: NoToneMapping, NormalAnimationBlendMode: NormalAnimationBlendMode, NormalBlending: NormalBlending, @@ -49183,7 +49883,7 @@ var THREE = /*#__PURE__*/Object.freeze({ Object3D: Object3D, ObjectLoader: ObjectLoader, ObjectSpaceNormalMap: ObjectSpaceNormalMap, - OctahedronBufferGeometry: OctahedronGeometry, + OctahedronBufferGeometry: OctahedronBufferGeometry, OctahedronGeometry: OctahedronGeometry, OneFactor: OneFactor, OneMinusDstAlphaFactor: OneMinusDstAlphaFactor, @@ -49194,26 +49894,18 @@ var THREE = /*#__PURE__*/Object.freeze({ PCFShadowMap: PCFShadowMap, PCFSoftShadowMap: PCFSoftShadowMap, PMREMGenerator: PMREMGenerator, - ParametricBufferGeometry: ParametricGeometry, - ParametricGeometry: ParametricGeometry, - Particle: Particle, - ParticleBasicMaterial: ParticleBasicMaterial, - ParticleSystem: ParticleSystem, - ParticleSystemMaterial: ParticleSystemMaterial, Path: Path, PerspectiveCamera: PerspectiveCamera, Plane: Plane, - PlaneBufferGeometry: PlaneGeometry, + PlaneBufferGeometry: PlaneBufferGeometry, PlaneGeometry: PlaneGeometry, PlaneHelper: PlaneHelper, - PointCloud: PointCloud, - PointCloudMaterial: PointCloudMaterial, PointLight: PointLight, PointLightHelper: PointLightHelper, Points: Points, PointsMaterial: PointsMaterial, PolarGridHelper: PolarGridHelper, - PolyhedronBufferGeometry: PolyhedronGeometry, + PolyhedronBufferGeometry: PolyhedronBufferGeometry, PolyhedronGeometry: PolyhedronGeometry, PositionalAudio: PositionalAudio, PropertyBinding: PropertyBinding, @@ -49248,13 +49940,7 @@ var THREE = /*#__PURE__*/Object.freeze({ RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format, - RGBDEncoding: RGBDEncoding, - RGBEEncoding: RGBEEncoding, - RGBEFormat: RGBEFormat, RGBFormat: RGBFormat, - RGBIntegerFormat: RGBIntegerFormat, - RGBM16Encoding: RGBM16Encoding, - RGBM7Encoding: RGBM7Encoding, RGB_ETC1_Format: RGB_ETC1_Format, RGB_ETC2_Format: RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format, @@ -49272,30 +49958,16 @@ var THREE = /*#__PURE__*/Object.freeze({ RepeatWrapping: RepeatWrapping, ReplaceStencilOp: ReplaceStencilOp, ReverseSubtractEquation: ReverseSubtractEquation, - RingBufferGeometry: RingGeometry, + RingBufferGeometry: RingBufferGeometry, RingGeometry: RingGeometry, - SRGB8_ALPHA8_ASTC_10x10_Format: SRGB8_ALPHA8_ASTC_10x10_Format, - SRGB8_ALPHA8_ASTC_10x5_Format: SRGB8_ALPHA8_ASTC_10x5_Format, - SRGB8_ALPHA8_ASTC_10x6_Format: SRGB8_ALPHA8_ASTC_10x6_Format, - SRGB8_ALPHA8_ASTC_10x8_Format: SRGB8_ALPHA8_ASTC_10x8_Format, - SRGB8_ALPHA8_ASTC_12x10_Format: SRGB8_ALPHA8_ASTC_12x10_Format, - SRGB8_ALPHA8_ASTC_12x12_Format: SRGB8_ALPHA8_ASTC_12x12_Format, - SRGB8_ALPHA8_ASTC_4x4_Format: SRGB8_ALPHA8_ASTC_4x4_Format, - SRGB8_ALPHA8_ASTC_5x4_Format: SRGB8_ALPHA8_ASTC_5x4_Format, - SRGB8_ALPHA8_ASTC_5x5_Format: SRGB8_ALPHA8_ASTC_5x5_Format, - SRGB8_ALPHA8_ASTC_6x5_Format: SRGB8_ALPHA8_ASTC_6x5_Format, - SRGB8_ALPHA8_ASTC_6x6_Format: SRGB8_ALPHA8_ASTC_6x6_Format, - SRGB8_ALPHA8_ASTC_8x5_Format: SRGB8_ALPHA8_ASTC_8x5_Format, - SRGB8_ALPHA8_ASTC_8x6_Format: SRGB8_ALPHA8_ASTC_8x6_Format, - SRGB8_ALPHA8_ASTC_8x8_Format: SRGB8_ALPHA8_ASTC_8x8_Format, + SRGBColorSpace: SRGBColorSpace, Scene: Scene, - SceneUtils: SceneUtils, ShaderChunk: ShaderChunk, ShaderLib: ShaderLib, ShaderMaterial: ShaderMaterial, ShadowMaterial: ShadowMaterial, Shape: Shape, - ShapeBufferGeometry: ShapeGeometry, + ShapeBufferGeometry: ShapeBufferGeometry, ShapeGeometry: ShapeGeometry, ShapePath: ShapePath, ShapeUtils: ShapeUtils, @@ -49303,9 +49975,9 @@ var THREE = /*#__PURE__*/Object.freeze({ Skeleton: Skeleton, SkeletonHelper: SkeletonHelper, SkinnedMesh: SkinnedMesh, - SmoothShading: SmoothShading, + Source: Source, Sphere: Sphere, - SphereBufferGeometry: SphereGeometry, + SphereBufferGeometry: SphereBufferGeometry, SphereGeometry: SphereGeometry, Spherical: Spherical, SphericalHarmonics3: SphericalHarmonics3, @@ -49329,32 +50001,27 @@ var THREE = /*#__PURE__*/Object.freeze({ SubtractiveBlending: SubtractiveBlending, TOUCH: TOUCH, TangentSpaceNormalMap: TangentSpaceNormalMap, - TetrahedronBufferGeometry: TetrahedronGeometry, + TetrahedronBufferGeometry: TetrahedronBufferGeometry, TetrahedronGeometry: TetrahedronGeometry, - TextBufferGeometry: TextGeometry, - TextGeometry: TextGeometry, Texture: Texture, TextureLoader: TextureLoader, - TorusBufferGeometry: TorusGeometry, + TorusBufferGeometry: TorusBufferGeometry, TorusGeometry: TorusGeometry, - TorusKnotBufferGeometry: TorusKnotGeometry, + TorusKnotBufferGeometry: TorusKnotBufferGeometry, TorusKnotGeometry: TorusKnotGeometry, Triangle: Triangle, TriangleFanDrawMode: TriangleFanDrawMode, TriangleStripDrawMode: TriangleStripDrawMode, TrianglesDrawMode: TrianglesDrawMode, - TubeBufferGeometry: TubeGeometry, + TubeBufferGeometry: TubeBufferGeometry, TubeGeometry: TubeGeometry, UVMapping: UVMapping, - Uint16Attribute: Uint16Attribute, Uint16BufferAttribute: Uint16BufferAttribute, - Uint32Attribute: Uint32Attribute, Uint32BufferAttribute: Uint32BufferAttribute, - Uint8Attribute: Uint8Attribute, Uint8BufferAttribute: Uint8BufferAttribute, - Uint8ClampedAttribute: Uint8ClampedAttribute, Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute, Uniform: Uniform, + UniformsGroup: UniformsGroup, UniformsLib: UniformsLib, UniformsUtils: UniformsUtils, UnsignedByteType: UnsignedByteType, @@ -49362,31 +50029,29 @@ var THREE = /*#__PURE__*/Object.freeze({ UnsignedIntType: UnsignedIntType, UnsignedShort4444Type: UnsignedShort4444Type, UnsignedShort5551Type: UnsignedShort5551Type, - UnsignedShort565Type: UnsignedShort565Type, UnsignedShortType: UnsignedShortType, VSMShadowMap: VSMShadowMap, Vector2: Vector2, Vector3: Vector3, Vector4: Vector4, VectorKeyframeTrack: VectorKeyframeTrack, - Vertex: Vertex, - VertexColors: VertexColors, VideoTexture: VideoTexture, WebGL1Renderer: WebGL1Renderer, + WebGL3DRenderTarget: WebGL3DRenderTarget, + WebGLArrayRenderTarget: WebGLArrayRenderTarget, WebGLCubeRenderTarget: WebGLCubeRenderTarget, + WebGLMultipleRenderTargets: WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget, WebGLRenderTarget: WebGLRenderTarget, - WebGLRenderTargetCube: WebGLRenderTargetCube, WebGLRenderer: WebGLRenderer, WebGLUtils: WebGLUtils, WireframeGeometry: WireframeGeometry, - WireframeHelper: WireframeHelper, WrapAroundEnding: WrapAroundEnding, - XHRLoader: XHRLoader, ZeroCurvatureEnding: ZeroCurvatureEnding, ZeroFactor: ZeroFactor, ZeroSlopeEnding: ZeroSlopeEnding, ZeroStencilOp: ZeroStencilOp, + _SRGBAFormat: _SRGBAFormat, sRGBEncoding: sRGBEncoding }); @@ -49397,1190 +50062,1207 @@ var THREE = /*#__PURE__*/Object.freeze({ // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move -var OrbitControls = function ( object, domElement ) { +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; - if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); - if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); +class OrbitControls extends EventDispatcher { - this.object = object; - this.domElement = domElement; + constructor( object, domElement ) { - // Set to false to disable this control - this.enabled = true; + super(); - // "target" sets the location of focus, where the object orbits around - this.target = new Vector3(); + this.object = object; + this.domElement = domElement; + this.domElement.style.touchAction = 'none'; // disable touch scroll - // How far you can dolly in and out ( PerspectiveCamera only ) - this.minDistance = 0; - this.maxDistance = Infinity; + // Set to false to disable this control + this.enabled = true; - // How far you can zoom in and out ( OrthographicCamera only ) - this.minZoom = 0; - this.maxZoom = Infinity; + // "target" sets the location of focus, where the object orbits around + this.target = new Vector3(); - // How far you can orbit vertically, upper and lower limits. - // Range is 0 to Math.PI radians. - this.minPolarAngle = 0; // radians - this.maxPolarAngle = Math.PI; // radians + // How far you can dolly in and out ( PerspectiveCamera only ) + this.minDistance = 0; + this.maxDistance = Infinity; - // How far you can orbit horizontally, upper and lower limits. - // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) - this.minAzimuthAngle = - Infinity; // radians - this.maxAzimuthAngle = Infinity; // radians + // How far you can zoom in and out ( OrthographicCamera only ) + this.minZoom = 0; + this.maxZoom = Infinity; - // Set to true to enable damping (inertia) - // If damping is enabled, you must call controls.update() in your animation loop - this.enableDamping = false; - this.dampingFactor = 0.05; + // How far you can orbit vertically, upper and lower limits. + // Range is 0 to Math.PI radians. + this.minPolarAngle = 0; // radians + this.maxPolarAngle = Math.PI; // radians - // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. - // Set to false to disable zooming - this.enableZoom = true; - this.zoomSpeed = 1.0; + // How far you can orbit horizontally, upper and lower limits. + // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) + this.minAzimuthAngle = - Infinity; // radians + this.maxAzimuthAngle = Infinity; // radians - // Set to false to disable rotating - this.enableRotate = true; - this.rotateSpeed = 1.0; + // Set to true to enable damping (inertia) + // If damping is enabled, you must call controls.update() in your animation loop + this.enableDamping = false; + this.dampingFactor = 0.05; - // Set to false to disable panning - this.enablePan = true; - this.panSpeed = 1.0; - this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up - this.keyPanSpeed = 7.0; // pixels moved per arrow key push + // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. + // Set to false to disable zooming + this.enableZoom = true; + this.zoomSpeed = 1.0; - // Set to true to automatically rotate around the target - // If auto-rotate is enabled, you must call controls.update() in your animation loop - this.autoRotate = false; - this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 + // Set to false to disable rotating + this.enableRotate = true; + this.rotateSpeed = 1.0; - // The four arrow keys - this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; + // Set to false to disable panning + this.enablePan = true; + this.panSpeed = 1.0; + this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up + this.keyPanSpeed = 7.0; // pixels moved per arrow key push - // Mouse buttons - this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + // Set to true to automatically rotate around the target + // If auto-rotate is enabled, you must call controls.update() in your animation loop + this.autoRotate = false; + this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 - // Touch fingers - this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + // The four arrow keys + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; - // for reset - this.target0 = this.target.clone(); - this.position0 = this.object.position.clone(); - this.zoom0 = this.object.zoom; + // Mouse buttons + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; - // the target DOM element for key events - this._domElementKeyEvents = null; + // Touch fingers + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; - // - // public methods - // + // for reset + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; - this.getPolarAngle = function () { + // the target DOM element for key events + this._domElementKeyEvents = null; - return spherical.phi; + // + // public methods + // - }; + this.getPolarAngle = function () { - this.getAzimuthalAngle = function () { + return spherical.phi; - return spherical.theta; + }; - }; + this.getAzimuthalAngle = function () { - this.listenToKeyEvents = function ( domElement ) { + return spherical.theta; - domElement.addEventListener( 'keydown', onKeyDown ); - this._domElementKeyEvents = domElement; + }; - }; + this.getDistance = function () { - this.saveState = function () { + return this.object.position.distanceTo( this.target ); - scope.target0.copy( scope.target ); - scope.position0.copy( scope.object.position ); - scope.zoom0 = scope.object.zoom; + }; - }; + this.listenToKeyEvents = function ( domElement ) { - this.reset = function () { + domElement.addEventListener( 'keydown', onKeyDown ); + this._domElementKeyEvents = domElement; - scope.target.copy( scope.target0 ); - scope.object.position.copy( scope.position0 ); - scope.object.zoom = scope.zoom0; + }; - scope.object.updateProjectionMatrix(); - scope.dispatchEvent( changeEvent ); + this.saveState = function () { - scope.update(); + scope.target0.copy( scope.target ); + scope.position0.copy( scope.object.position ); + scope.zoom0 = scope.object.zoom; - state = STATE.NONE; + }; - }; + this.reset = function () { - // this method is exposed, but perhaps it would be better if we can make it private... - this.update = function () { + scope.target.copy( scope.target0 ); + scope.object.position.copy( scope.position0 ); + scope.object.zoom = scope.zoom0; - var offset = new Vector3(); + scope.object.updateProjectionMatrix(); + scope.dispatchEvent( _changeEvent ); - // so camera.up is the orbit axis - var quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); - var quatInverse = quat.clone().invert(); + scope.update(); - var lastPosition = new Vector3(); - var lastQuaternion = new Quaternion(); + state = STATE.NONE; - var twoPI = 2 * Math.PI; + }; - return function update() { + // this method is exposed, but perhaps it would be better if we can make it private... + this.update = function () { - var position = scope.object.position; + const offset = new Vector3(); - offset.copy( position ).sub( scope.target ); + // so camera.up is the orbit axis + const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + const quatInverse = quat.clone().invert(); - // rotate offset to "y-axis-is-up" space - offset.applyQuaternion( quat ); + const lastPosition = new Vector3(); + const lastQuaternion = new Quaternion(); - // angle from z-axis around y-axis - spherical.setFromVector3( offset ); + const twoPI = 2 * Math.PI; - if ( scope.autoRotate && state === STATE.NONE ) { + return function update() { - rotateLeft( getAutoRotationAngle() ); + const position = scope.object.position; - } + offset.copy( position ).sub( scope.target ); - if ( scope.enableDamping ) { + // rotate offset to "y-axis-is-up" space + offset.applyQuaternion( quat ); - spherical.theta += sphericalDelta.theta * scope.dampingFactor; - spherical.phi += sphericalDelta.phi * scope.dampingFactor; + // angle from z-axis around y-axis + spherical.setFromVector3( offset ); - } else { + if ( scope.autoRotate && state === STATE.NONE ) { - spherical.theta += sphericalDelta.theta; - spherical.phi += sphericalDelta.phi; + rotateLeft( getAutoRotationAngle() ); - } + } - // restrict theta to be between desired limits + if ( scope.enableDamping ) { - var min = scope.minAzimuthAngle; - var max = scope.maxAzimuthAngle; + spherical.theta += sphericalDelta.theta * scope.dampingFactor; + spherical.phi += sphericalDelta.phi * scope.dampingFactor; - if ( isFinite( min ) && isFinite( max ) ) { + } else { - if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; + spherical.theta += sphericalDelta.theta; + spherical.phi += sphericalDelta.phi; - if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; + } - if ( min <= max ) { + // restrict theta to be between desired limits - spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); + let min = scope.minAzimuthAngle; + let max = scope.maxAzimuthAngle; - } else { + if ( isFinite( min ) && isFinite( max ) ) { + + if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; + + if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; - spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? - Math.max( min, spherical.theta ) : - Math.min( max, spherical.theta ); + if ( min <= max ) { + + spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); + + } else { + + spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, spherical.theta ) : + Math.min( max, spherical.theta ); + + } } - } + // restrict phi to be between desired limits + spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); - // restrict phi to be between desired limits - spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); + spherical.makeSafe(); - spherical.makeSafe(); + spherical.radius *= scale; - spherical.radius *= scale; + // restrict radius to be between desired limits + spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); - // restrict radius to be between desired limits - spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); + // move target to panned location - // move target to panned location + if ( scope.enableDamping === true ) { - if ( scope.enableDamping === true ) { + scope.target.addScaledVector( panOffset, scope.dampingFactor ); - scope.target.addScaledVector( panOffset, scope.dampingFactor ); + } else { - } else { + scope.target.add( panOffset ); - scope.target.add( panOffset ); + } - } + offset.setFromSpherical( spherical ); - offset.setFromSpherical( spherical ); + // rotate offset back to "camera-up-vector-is-up" space + offset.applyQuaternion( quatInverse ); - // rotate offset back to "camera-up-vector-is-up" space - offset.applyQuaternion( quatInverse ); + position.copy( scope.target ).add( offset ); - position.copy( scope.target ).add( offset ); + scope.object.lookAt( scope.target ); - scope.object.lookAt( scope.target ); + if ( scope.enableDamping === true ) { - if ( scope.enableDamping === true ) { + sphericalDelta.theta *= ( 1 - scope.dampingFactor ); + sphericalDelta.phi *= ( 1 - scope.dampingFactor ); - sphericalDelta.theta *= ( 1 - scope.dampingFactor ); - sphericalDelta.phi *= ( 1 - scope.dampingFactor ); + panOffset.multiplyScalar( 1 - scope.dampingFactor ); - panOffset.multiplyScalar( 1 - scope.dampingFactor ); + } else { - } else { + sphericalDelta.set( 0, 0, 0 ); - sphericalDelta.set( 0, 0, 0 ); + panOffset.set( 0, 0, 0 ); - panOffset.set( 0, 0, 0 ); + } - } + scale = 1; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + lastPosition.distanceToSquared( scope.object.position ) > EPS || + 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastQuaternion.copy( scope.object.quaternion ); + zoomChanged = false; + + return true; + + } + + return false; + + }; + + }(); + + this.dispose = function () { - scale = 1; + scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); - // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); + scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.removeEventListener( 'wheel', onMouseWheel ); - if ( zoomChanged || - lastPosition.distanceToSquared( scope.object.position ) > EPS || - 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - scope.dispatchEvent( changeEvent ); - lastPosition.copy( scope.object.position ); - lastQuaternion.copy( scope.object.quaternion ); - zoomChanged = false; + if ( scope._domElementKeyEvents !== null ) { - return true; + scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); } - return false; + //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? }; - }(); + // + // internals + // - this.dispose = function () { + const scope = this; - scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); + const STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 + }; - scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); - scope.domElement.removeEventListener( 'wheel', onMouseWheel ); + let state = STATE.NONE; - scope.domElement.removeEventListener( 'touchstart', onTouchStart ); - scope.domElement.removeEventListener( 'touchend', onTouchEnd ); - scope.domElement.removeEventListener( 'touchmove', onTouchMove ); + const EPS = 0.000001; - scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp ); + // current position in spherical coordinates + const spherical = new Spherical(); + const sphericalDelta = new Spherical(); + let scale = 1; + const panOffset = new Vector3(); + let zoomChanged = false; - if ( scope._domElementKeyEvents !== null ) { + const rotateStart = new Vector2(); + const rotateEnd = new Vector2(); + const rotateDelta = new Vector2(); - scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); + const panStart = new Vector2(); + const panEnd = new Vector2(); + const panDelta = new Vector2(); - } + const dollyStart = new Vector2(); + const dollyEnd = new Vector2(); + const dollyDelta = new Vector2(); - //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? + const pointers = []; + const pointerPositions = {}; - }; + function getAutoRotationAngle() { - // - // internals - // + return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - var scope = this; - - var changeEvent = { type: 'change' }; - var startEvent = { type: 'start' }; - var endEvent = { type: 'end' }; - - var STATE = { - NONE: - 1, - ROTATE: 0, - DOLLY: 1, - PAN: 2, - TOUCH_ROTATE: 3, - TOUCH_PAN: 4, - TOUCH_DOLLY_PAN: 5, - TOUCH_DOLLY_ROTATE: 6 - }; + } - var state = STATE.NONE; + function getZoomScale() { - var EPS = 0.000001; + return Math.pow( 0.95, scope.zoomSpeed ); - // current position in spherical coordinates - var spherical = new Spherical(); - var sphericalDelta = new Spherical(); + } - var scale = 1; - var panOffset = new Vector3(); - var zoomChanged = false; + function rotateLeft( angle ) { - var rotateStart = new Vector2(); - var rotateEnd = new Vector2(); - var rotateDelta = new Vector2(); + sphericalDelta.theta -= angle; - var panStart = new Vector2(); - var panEnd = new Vector2(); - var panDelta = new Vector2(); + } - var dollyStart = new Vector2(); - var dollyEnd = new Vector2(); - var dollyDelta = new Vector2(); + function rotateUp( angle ) { - function getAutoRotationAngle() { + sphericalDelta.phi -= angle; - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; + } - } + const panLeft = function () { - function getZoomScale() { + const v = new Vector3(); - return Math.pow( 0.95, scope.zoomSpeed ); + return function panLeft( distance, objectMatrix ) { - } + v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + v.multiplyScalar( - distance ); - function rotateLeft( angle ) { + panOffset.add( v ); - sphericalDelta.theta -= angle; + }; - } + }(); - function rotateUp( angle ) { + const panUp = function () { - sphericalDelta.phi -= angle; + const v = new Vector3(); - } + return function panUp( distance, objectMatrix ) { - var panLeft = function () { + if ( scope.screenSpacePanning === true ) { - var v = new Vector3(); + v.setFromMatrixColumn( objectMatrix, 1 ); - return function panLeft( distance, objectMatrix ) { + } else { - v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix - v.multiplyScalar( - distance ); + v.setFromMatrixColumn( objectMatrix, 0 ); + v.crossVectors( scope.object.up, v ); - panOffset.add( v ); + } - }; + v.multiplyScalar( distance ); - }(); + panOffset.add( v ); - var panUp = function () { + }; - var v = new Vector3(); + }(); - return function panUp( distance, objectMatrix ) { + // deltaX and deltaY are in pixels; right and down are positive + const pan = function () { - if ( scope.screenSpacePanning === true ) { + const offset = new Vector3(); - v.setFromMatrixColumn( objectMatrix, 1 ); + return function pan( deltaX, deltaY ) { - } else { + const element = scope.domElement; - v.setFromMatrixColumn( objectMatrix, 0 ); - v.crossVectors( scope.object.up, v ); + if ( scope.object.isPerspectiveCamera ) { - } + // perspective + const position = scope.object.position; + offset.copy( position ).sub( scope.target ); + let targetDistance = offset.length(); - v.multiplyScalar( distance ); + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); - panOffset.add( v ); + // we use only clientHeight here so aspect ratio does not distort speed + panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); + panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); - }; + } else if ( scope.object.isOrthographicCamera ) { - }(); + // orthographic + panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); + panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); - // deltaX and deltaY are in pixels; right and down are positive - var pan = function () { + } else { - var offset = new Vector3(); + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + scope.enablePan = false; - return function pan( deltaX, deltaY ) { + } - var element = scope.domElement; + }; - if ( scope.object.isPerspectiveCamera ) { + }(); - // perspective - var position = scope.object.position; - offset.copy( position ).sub( scope.target ); - var targetDistance = offset.length(); + function dollyOut( dollyScale ) { - // half of the fov is center to top of screen - targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); + if ( scope.object.isPerspectiveCamera ) { - // we use only clientHeight here so aspect ratio does not distort speed - panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); - panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); + scale /= dollyScale; } else if ( scope.object.isOrthographicCamera ) { - // orthographic - panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); - panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; } else { - // camera neither orthographic nor perspective - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); - scope.enablePan = false; + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; } - }; + } - }(); + function dollyIn( dollyScale ) { - function dollyOut( dollyScale ) { + if ( scope.object.isPerspectiveCamera ) { - if ( scope.object.isPerspectiveCamera ) { + scale *= dollyScale; - scale /= dollyScale; + } else if ( scope.object.isOrthographicCamera ) { - } else if ( scope.object.isOrthographicCamera ) { + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; + } else { - } else { + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; + } } - } + // + // event callbacks - update the object state + // - function dollyIn( dollyScale ) { + function handleMouseDownRotate( event ) { - if ( scope.object.isPerspectiveCamera ) { + rotateStart.set( event.clientX, event.clientY ); - scale *= dollyScale; + } - } else if ( scope.object.isOrthographicCamera ) { + function handleMouseDownDolly( event ) { - scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); - scope.object.updateProjectionMatrix(); - zoomChanged = true; + dollyStart.set( event.clientX, event.clientY ); - } else { + } - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); - scope.enableZoom = false; + function handleMouseDownPan( event ) { - } + panStart.set( event.clientX, event.clientY ); - } + } - // - // event callbacks - update the object state - // + function handleMouseMoveRotate( event ) { - function handleMouseDownRotate( event ) { + rotateEnd.set( event.clientX, event.clientY ); - rotateStart.set( event.clientX, event.clientY ); + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - } + const element = scope.domElement; - function handleMouseDownDolly( event ) { + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - dollyStart.set( event.clientX, event.clientY ); + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - } + rotateStart.copy( rotateEnd ); - function handleMouseDownPan( event ) { + scope.update(); - panStart.set( event.clientX, event.clientY ); + } - } + function handleMouseMoveDolly( event ) { - function handleMouseMoveRotate( event ) { + dollyEnd.set( event.clientX, event.clientY ); - rotateEnd.set( event.clientX, event.clientY ); + dollyDelta.subVectors( dollyEnd, dollyStart ); - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); + if ( dollyDelta.y > 0 ) { - var element = scope.domElement; + dollyOut( getZoomScale() ); - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height + } else if ( dollyDelta.y < 0 ) { - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); + dollyIn( getZoomScale() ); - rotateStart.copy( rotateEnd ); + } - scope.update(); + dollyStart.copy( dollyEnd ); - } + scope.update(); - function handleMouseMoveDolly( event ) { + } - dollyEnd.set( event.clientX, event.clientY ); + function handleMouseMovePan( event ) { - dollyDelta.subVectors( dollyEnd, dollyStart ); + panEnd.set( event.clientX, event.clientY ); - if ( dollyDelta.y > 0 ) { + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - dollyOut( getZoomScale() ); + pan( panDelta.x, panDelta.y ); - } else if ( dollyDelta.y < 0 ) { + panStart.copy( panEnd ); - dollyIn( getZoomScale() ); + scope.update(); } - dollyStart.copy( dollyEnd ); + function handleMouseWheel( event ) { - scope.update(); + if ( event.deltaY < 0 ) { - } + dollyIn( getZoomScale() ); - function handleMouseMovePan( event ) { + } else if ( event.deltaY > 0 ) { - panEnd.set( event.clientX, event.clientY ); + dollyOut( getZoomScale() ); - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); + } - pan( panDelta.x, panDelta.y ); + scope.update(); - panStart.copy( panEnd ); + } - scope.update(); + function handleKeyDown( event ) { - } + let needsUpdate = false; - function handleMouseUp( /*event*/ ) { + switch ( event.code ) { - // no-op + case scope.keys.UP: + pan( 0, scope.keyPanSpeed ); + needsUpdate = true; + break; - } + case scope.keys.BOTTOM: + pan( 0, - scope.keyPanSpeed ); + needsUpdate = true; + break; - function handleMouseWheel( event ) { + case scope.keys.LEFT: + pan( scope.keyPanSpeed, 0 ); + needsUpdate = true; + break; - if ( event.deltaY < 0 ) { + case scope.keys.RIGHT: + pan( - scope.keyPanSpeed, 0 ); + needsUpdate = true; + break; - dollyIn( getZoomScale() ); + } - } else if ( event.deltaY > 0 ) { + if ( needsUpdate ) { - dollyOut( getZoomScale() ); + // prevent the browser from scrolling on cursor keys + event.preventDefault(); - } + scope.update(); - scope.update(); + } - } - function handleKeyDown( event ) { + } - var needsUpdate = false; + function handleTouchStartRotate() { - switch ( event.keyCode ) { + if ( pointers.length === 1 ) { - case scope.keys.UP: - pan( 0, scope.keyPanSpeed ); - needsUpdate = true; - break; + rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - case scope.keys.BOTTOM: - pan( 0, - scope.keyPanSpeed ); - needsUpdate = true; - break; + } else { - case scope.keys.LEFT: - pan( scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - case scope.keys.RIGHT: - pan( - scope.keyPanSpeed, 0 ); - needsUpdate = true; - break; + rotateStart.set( x, y ); + + } } - if ( needsUpdate ) { + function handleTouchStartPan() { - // prevent the browser from scrolling on cursor keys - event.preventDefault(); + if ( pointers.length === 1 ) { - scope.update(); + panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); - } + } else { + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); - } + panStart.set( x, y ); - function handleTouchStartRotate( event ) { + } - if ( event.touches.length == 1 ) { + } - rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + function handleTouchStartDolly() { - } else { + const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX; + const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY; - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + const distance = Math.sqrt( dx * dx + dy * dy ); - rotateStart.set( x, y ); + dollyStart.set( 0, distance ); } - } + function handleTouchStartDollyPan() { - function handleTouchStartPan( event ) { + if ( scope.enableZoom ) handleTouchStartDolly(); - if ( event.touches.length == 1 ) { + if ( scope.enablePan ) handleTouchStartPan(); - panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + } - } else { + function handleTouchStartDollyRotate() { - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + if ( scope.enableZoom ) handleTouchStartDolly(); - panStart.set( x, y ); + if ( scope.enableRotate ) handleTouchStartRotate(); } - } + function handleTouchMoveRotate( event ) { - function handleTouchStartDolly( event ) { + if ( pointers.length == 1 ) { - var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; - var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; + rotateEnd.set( event.pageX, event.pageY ); - var distance = Math.sqrt( dx * dx + dy * dy ); + } else { - dollyStart.set( 0, distance ); + const position = getSecondPointerPosition( event ); - } + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + rotateEnd.set( x, y ); - function handleTouchStartDollyPan( event ) { + } - if ( scope.enableZoom ) handleTouchStartDolly( event ); + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); - if ( scope.enablePan ) handleTouchStartPan( event ); + const element = scope.domElement; - } + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height - function handleTouchStartDollyRotate( event ) { + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); - if ( scope.enableZoom ) handleTouchStartDolly( event ); + rotateStart.copy( rotateEnd ); - if ( scope.enableRotate ) handleTouchStartRotate( event ); + } - } + function handleTouchMovePan( event ) { - function handleTouchMoveRotate( event ) { + if ( pointers.length === 1 ) { - if ( event.touches.length == 1 ) { + panEnd.set( event.pageX, event.pageY ); - rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + } else { - } else { + const position = getSecondPointerPosition( event ); - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); - rotateEnd.set( x, y ); + panEnd.set( x, y ); - } + } - rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); - var element = scope.domElement; + pan( panDelta.x, panDelta.y ); - rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height + panStart.copy( panEnd ); - rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); + } - rotateStart.copy( rotateEnd ); + function handleTouchMoveDolly( event ) { - } + const position = getSecondPointerPosition( event ); - function handleTouchMovePan( event ) { + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; - if ( event.touches.length == 1 ) { + const distance = Math.sqrt( dx * dx + dy * dy ); - panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + dollyEnd.set( 0, distance ); - } else { + dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); - var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ); - var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ); + dollyOut( dollyDelta.y ); - panEnd.set( x, y ); + dollyStart.copy( dollyEnd ); } - panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); + function handleTouchMoveDollyPan( event ) { - pan( panDelta.x, panDelta.y ); + if ( scope.enableZoom ) handleTouchMoveDolly( event ); - panStart.copy( panEnd ); + if ( scope.enablePan ) handleTouchMovePan( event ); - } + } - function handleTouchMoveDolly( event ) { + function handleTouchMoveDollyRotate( event ) { - var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; - var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; + if ( scope.enableZoom ) handleTouchMoveDolly( event ); - var distance = Math.sqrt( dx * dx + dy * dy ); + if ( scope.enableRotate ) handleTouchMoveRotate( event ); - dollyEnd.set( 0, distance ); + } - dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); + // + // event handlers - FSM: listen for events and reset state + // - dollyOut( dollyDelta.y ); + function onPointerDown( event ) { - dollyStart.copy( dollyEnd ); + if ( scope.enabled === false ) return; - } + if ( pointers.length === 0 ) { - function handleTouchMoveDollyPan( event ) { + scope.domElement.setPointerCapture( event.pointerId ); - if ( scope.enableZoom ) handleTouchMoveDolly( event ); + scope.domElement.addEventListener( 'pointermove', onPointerMove ); + scope.domElement.addEventListener( 'pointerup', onPointerUp ); - if ( scope.enablePan ) handleTouchMovePan( event ); + } - } + // - function handleTouchMoveDollyRotate( event ) { + addPointer( event ); - if ( scope.enableZoom ) handleTouchMoveDolly( event ); + if ( event.pointerType === 'touch' ) { - if ( scope.enableRotate ) handleTouchMoveRotate( event ); + onTouchStart( event ); - } + } else { - function handleTouchEnd( /*event*/ ) { + onMouseDown( event ); - // no-op + } - } + } - // - // event handlers - FSM: listen for events and reset state - // + function onPointerMove( event ) { - function onPointerDown( event ) { + if ( scope.enabled === false ) return; - if ( scope.enabled === false ) return; + if ( event.pointerType === 'touch' ) { - switch ( event.pointerType ) { + onTouchMove( event ); - case 'mouse': - case 'pen': - onMouseDown( event ); - break; + } else { - // TODO touch + onMouseMove( event ); - } + } - } + } - function onPointerMove( event ) { + function onPointerUp( event ) { - if ( scope.enabled === false ) return; + removePointer( event ); - switch ( event.pointerType ) { + if ( pointers.length === 0 ) { - case 'mouse': - case 'pen': - onMouseMove( event ); - break; + scope.domElement.releasePointerCapture( event.pointerId ); - // TODO touch + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); - } + } - } + scope.dispatchEvent( _endEvent ); - function onPointerUp( event ) { + state = STATE.NONE; - switch ( event.pointerType ) { + } - case 'mouse': - case 'pen': - onMouseUp( event ); - break; + function onPointerCancel( event ) { - // TODO touch + removePointer( event ); } - } + function onMouseDown( event ) { - function onMouseDown( event ) { + let mouseAction; - // Prevent the browser from scrolling. - event.preventDefault(); + switch ( event.button ) { - // Manually set the focus since calling preventDefault above - // prevents the browser from setting it automatically. + case 0: - scope.domElement.focus ? scope.domElement.focus() : window.focus(); + mouseAction = scope.mouseButtons.LEFT; + break; - var mouseAction; + case 1: - switch ( event.button ) { + mouseAction = scope.mouseButtons.MIDDLE; + break; - case 0: + case 2: - mouseAction = scope.mouseButtons.LEFT; - break; + mouseAction = scope.mouseButtons.RIGHT; + break; - case 1: + default: - mouseAction = scope.mouseButtons.MIDDLE; - break; + mouseAction = - 1; - case 2: + } - mouseAction = scope.mouseButtons.RIGHT; - break; + switch ( mouseAction ) { - default: + case MOUSE.DOLLY: - mouseAction = - 1; + if ( scope.enableZoom === false ) return; - } + handleMouseDownDolly( event ); - switch ( mouseAction ) { + state = STATE.DOLLY; - case MOUSE.DOLLY: + break; - if ( scope.enableZoom === false ) return; + case MOUSE.ROTATE: - handleMouseDownDolly( event ); + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - state = STATE.DOLLY; + if ( scope.enablePan === false ) return; - break; + handleMouseDownPan( event ); - case MOUSE.ROTATE: + state = STATE.PAN; - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + } else { - if ( scope.enablePan === false ) return; + if ( scope.enableRotate === false ) return; - handleMouseDownPan( event ); + handleMouseDownRotate( event ); - state = STATE.PAN; + state = STATE.ROTATE; - } else { + } - if ( scope.enableRotate === false ) return; + break; - handleMouseDownRotate( event ); + case MOUSE.PAN: - state = STATE.ROTATE; + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - } + if ( scope.enableRotate === false ) return; - break; + handleMouseDownRotate( event ); - case MOUSE.PAN: + state = STATE.ROTATE; - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + } else { - if ( scope.enableRotate === false ) return; + if ( scope.enablePan === false ) return; - handleMouseDownRotate( event ); + handleMouseDownPan( event ); - state = STATE.ROTATE; + state = STATE.PAN; - } else { + } - if ( scope.enablePan === false ) return; + break; - handleMouseDownPan( event ); + default: - state = STATE.PAN; + state = STATE.NONE; - } + } - break; + if ( state !== STATE.NONE ) { - default: + scope.dispatchEvent( _startEvent ); - state = STATE.NONE; + } } - if ( state !== STATE.NONE ) { + function onMouseMove( event ) { - scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove ); - scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp ); + switch ( state ) { - scope.dispatchEvent( startEvent ); + case STATE.ROTATE: - } + if ( scope.enableRotate === false ) return; - } + handleMouseMoveRotate( event ); + + break; - function onMouseMove( event ) { + case STATE.DOLLY: - if ( scope.enabled === false ) return; + if ( scope.enableZoom === false ) return; - event.preventDefault(); + handleMouseMoveDolly( event ); - switch ( state ) { + break; - case STATE.ROTATE: + case STATE.PAN: - if ( scope.enableRotate === false ) return; + if ( scope.enablePan === false ) return; - handleMouseMoveRotate( event ); + handleMouseMovePan( event ); - break; + break; - case STATE.DOLLY: + } - if ( scope.enableZoom === false ) return; + } - handleMouseMoveDolly( event ); + function onMouseWheel( event ) { - break; + if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return; - case STATE.PAN: + event.preventDefault(); - if ( scope.enablePan === false ) return; + scope.dispatchEvent( _startEvent ); - handleMouseMovePan( event ); + handleMouseWheel( event ); - break; + scope.dispatchEvent( _endEvent ); } - } - - function onMouseUp( event ) { + function onKeyDown( event ) { - scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove ); - scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp ); + if ( scope.enabled === false || scope.enablePan === false ) return; - if ( scope.enabled === false ) return; + handleKeyDown( event ); - handleMouseUp( event ); + } - scope.dispatchEvent( endEvent ); + function onTouchStart( event ) { - state = STATE.NONE; + trackPointer( event ); - } + switch ( pointers.length ) { - function onMouseWheel( event ) { + case 1: - if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return; + switch ( scope.touches.ONE ) { - event.preventDefault(); - event.stopPropagation(); + case TOUCH.ROTATE: - scope.dispatchEvent( startEvent ); + if ( scope.enableRotate === false ) return; - handleMouseWheel( event ); + handleTouchStartRotate(); - scope.dispatchEvent( endEvent ); + state = STATE.TOUCH_ROTATE; - } + break; - function onKeyDown( event ) { + case TOUCH.PAN: - if ( scope.enabled === false || scope.enablePan === false ) return; + if ( scope.enablePan === false ) return; - handleKeyDown( event ); + handleTouchStartPan(); - } + state = STATE.TOUCH_PAN; - function onTouchStart( event ) { + break; - if ( scope.enabled === false ) return; + default: - event.preventDefault(); // prevent scrolling + state = STATE.NONE; - switch ( event.touches.length ) { + } - case 1: + break; - switch ( scope.touches.ONE ) { + case 2: - case TOUCH.ROTATE: + switch ( scope.touches.TWO ) { - if ( scope.enableRotate === false ) return; + case TOUCH.DOLLY_PAN: - handleTouchStartRotate( event ); + if ( scope.enableZoom === false && scope.enablePan === false ) return; - state = STATE.TOUCH_ROTATE; + handleTouchStartDollyPan(); - break; + state = STATE.TOUCH_DOLLY_PAN; - case TOUCH.PAN: + break; - if ( scope.enablePan === false ) return; + case TOUCH.DOLLY_ROTATE: - handleTouchStartPan( event ); + if ( scope.enableZoom === false && scope.enableRotate === false ) return; - state = STATE.TOUCH_PAN; + handleTouchStartDollyRotate(); - break; + state = STATE.TOUCH_DOLLY_ROTATE; - default: + break; - state = STATE.NONE; + default: - } + state = STATE.NONE; - break; + } - case 2: + break; - switch ( scope.touches.TWO ) { + default: - case TOUCH.DOLLY_PAN: + state = STATE.NONE; - if ( scope.enableZoom === false && scope.enablePan === false ) return; + } - handleTouchStartDollyPan( event ); + if ( state !== STATE.NONE ) { - state = STATE.TOUCH_DOLLY_PAN; + scope.dispatchEvent( _startEvent ); - break; + } - case TOUCH.DOLLY_ROTATE: + } - if ( scope.enableZoom === false && scope.enableRotate === false ) return; + function onTouchMove( event ) { - handleTouchStartDollyRotate( event ); + trackPointer( event ); - state = STATE.TOUCH_DOLLY_ROTATE; + switch ( state ) { - break; + case STATE.TOUCH_ROTATE: - default: + if ( scope.enableRotate === false ) return; - state = STATE.NONE; + handleTouchMoveRotate( event ); - } + scope.update(); - break; + break; - default: + case STATE.TOUCH_PAN: - state = STATE.NONE; + if ( scope.enablePan === false ) return; - } + handleTouchMovePan( event ); - if ( state !== STATE.NONE ) { + scope.update(); - scope.dispatchEvent( startEvent ); + break; - } + case STATE.TOUCH_DOLLY_PAN: - } + if ( scope.enableZoom === false && scope.enablePan === false ) return; - function onTouchMove( event ) { + handleTouchMoveDollyPan( event ); - if ( scope.enabled === false ) return; + scope.update(); - event.preventDefault(); // prevent scrolling - event.stopPropagation(); + break; - switch ( state ) { + case STATE.TOUCH_DOLLY_ROTATE: - case STATE.TOUCH_ROTATE: + if ( scope.enableZoom === false && scope.enableRotate === false ) return; - if ( scope.enableRotate === false ) return; + handleTouchMoveDollyRotate( event ); - handleTouchMoveRotate( event ); + scope.update(); - scope.update(); + break; - break; + default: - case STATE.TOUCH_PAN: + state = STATE.NONE; - if ( scope.enablePan === false ) return; + } - handleTouchMovePan( event ); + } - scope.update(); + function onContextMenu( event ) { - break; + if ( scope.enabled === false ) return; - case STATE.TOUCH_DOLLY_PAN: + event.preventDefault(); - if ( scope.enableZoom === false && scope.enablePan === false ) return; + } - handleTouchMoveDollyPan( event ); + function addPointer( event ) { - scope.update(); + pointers.push( event ); - break; + } - case STATE.TOUCH_DOLLY_ROTATE: + function removePointer( event ) { - if ( scope.enableZoom === false && scope.enableRotate === false ) return; + delete pointerPositions[ event.pointerId ]; - handleTouchMoveDollyRotate( event ); + for ( let i = 0; i < pointers.length; i ++ ) { - scope.update(); + if ( pointers[ i ].pointerId == event.pointerId ) { - break; + pointers.splice( i, 1 ); + return; - default: + } - state = STATE.NONE; + } } - } + function trackPointer( event ) { - function onTouchEnd( event ) { + let position = pointerPositions[ event.pointerId ]; - if ( scope.enabled === false ) return; + if ( position === undefined ) { - handleTouchEnd( event ); + position = new Vector2(); + pointerPositions[ event.pointerId ] = position; - scope.dispatchEvent( endEvent ); + } - state = STATE.NONE; + position.set( event.pageX, event.pageY ); - } + } - function onContextMenu( event ) { + function getSecondPointerPosition( event ) { - if ( scope.enabled === false ) return; + const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ]; - event.preventDefault(); - - } + return pointerPositions[ pointer.pointerId ]; - // + } - scope.domElement.addEventListener( 'contextmenu', onContextMenu ); + // - scope.domElement.addEventListener( 'pointerdown', onPointerDown ); - scope.domElement.addEventListener( 'wheel', onMouseWheel ); + scope.domElement.addEventListener( 'contextmenu', onContextMenu ); - scope.domElement.addEventListener( 'touchstart', onTouchStart ); - scope.domElement.addEventListener( 'touchend', onTouchEnd ); - scope.domElement.addEventListener( 'touchmove', onTouchMove ); + scope.domElement.addEventListener( 'pointerdown', onPointerDown ); + scope.domElement.addEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); - // force an update at start + // force an update at start - this.update(); + this.update(); -}; + } -OrbitControls.prototype = Object.create( EventDispatcher.prototype ); -OrbitControls.prototype.constructor = OrbitControls; +} // This set of controls performs orbiting, dollying (zooming), and panning. @@ -50591,28 +51273,29 @@ OrbitControls.prototype.constructor = OrbitControls; // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - left mouse, or arrow keys / touch: one-finger move -var MapControls = function ( object, domElement ) { +class MapControls extends OrbitControls { - OrbitControls.call( this, object, domElement ); + constructor( object, domElement ) { - this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up + super( object, domElement ); - this.mouseButtons.LEFT = MOUSE.PAN; - this.mouseButtons.RIGHT = MOUSE.ROTATE; + this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up - this.touches.ONE = TOUCH.PAN; - this.touches.TWO = TOUCH.DOLLY_ROTATE; + this.mouseButtons.LEFT = MOUSE.PAN; + this.mouseButtons.RIGHT = MOUSE.ROTATE; -}; + this.touches.ONE = TOUCH.PAN; + this.touches.TWO = TOUCH.DOLLY_ROTATE; + + } -MapControls.prototype = Object.create( EventDispatcher.prototype ); -MapControls.prototype.constructor = MapControls; +} -var GLTFLoader = ( function () { +class GLTFLoader extends Loader { - function GLTFLoader( manager ) { + constructor( manager ) { - Loader.call( this, manager ); + super( manager ); this.dracoLoader = null; this.ktx2Loader = null; @@ -50638,12 +51321,48 @@ var GLTFLoader = ( function () { } ); + this.register( function ( parser ) { + + return new GLTFMaterialsSheenExtension( parser ); + + } ); + this.register( function ( parser ) { return new GLTFMaterialsTransmissionExtension( parser ); } ); + this.register( function ( parser ) { + + return new GLTFMaterialsVolumeExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsIorExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsEmissiveStrengthExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsSpecularExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsIridescenceExtension( parser ); + + } ); + this.register( function ( parser ) { return new GLTFLightsExtension( parser ); @@ -50658,320 +51377,336 @@ var GLTFLoader = ( function () { } - GLTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + load( url, onLoad, onProgress, onError ) { - constructor: GLTFLoader, + const scope = this; - load: function ( url, onLoad, onProgress, onError ) { + let resourcePath; - var scope = this; + if ( this.resourcePath !== '' ) { - var resourcePath; + resourcePath = this.resourcePath; - if ( this.resourcePath !== '' ) { + } else if ( this.path !== '' ) { - resourcePath = this.resourcePath; + resourcePath = this.path; - } else if ( this.path !== '' ) { + } else { + + resourcePath = LoaderUtils.extractUrlBase( url ); - resourcePath = this.path; + } + + // Tells the LoadingManager to track an extra item, which resolves after + // the model is fully loaded. This means the count of items loaded will + // be incorrect, but ensures manager.onLoad() does not fire early. + this.manager.itemStart( url ); + + const _onError = function ( e ) { + + if ( onError ) { + + onError( e ); } else { - resourcePath = LoaderUtils.extractUrlBase( url ); + console.error( e ); } - // Tells the LoadingManager to track an extra item, which resolves after - // the model is fully loaded. This means the count of items loaded will - // be incorrect, but ensures manager.onLoad() does not fire early. - this.manager.itemStart( url ); + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - var _onError = function ( e ) { + }; - if ( onError ) { + const loader = new FileLoader( this.manager ); - onError( e ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); - } else { + loader.load( url, function ( data ) { - console.error( e ); + try { - } + scope.parse( data, resourcePath, function ( gltf ) { - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + onLoad( gltf ); - }; + scope.manager.itemEnd( url ); - var loader = new FileLoader( this.manager ); + }, _onError ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); - loader.setRequestHeader( this.requestHeader ); - loader.setWithCredentials( this.withCredentials ); + } catch ( e ) { - loader.load( url, function ( data ) { + _onError( e ); - try { + } - scope.parse( data, resourcePath, function ( gltf ) { + }, onProgress, _onError ); - onLoad( gltf ); + } - scope.manager.itemEnd( url ); + setDRACOLoader( dracoLoader ) { - }, _onError ); + this.dracoLoader = dracoLoader; + return this; - } catch ( e ) { + } - _onError( e ); + setDDSLoader() { - } + throw new Error( - }, onProgress, _onError ); + 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".' - }, + ); - setDRACOLoader: function ( dracoLoader ) { + } - this.dracoLoader = dracoLoader; - return this; + setKTX2Loader( ktx2Loader ) { - }, + this.ktx2Loader = ktx2Loader; + return this; - setDDSLoader: function () { + } - throw new Error( + setMeshoptDecoder( meshoptDecoder ) { - 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".' + this.meshoptDecoder = meshoptDecoder; + return this; - ); + } - }, + register( callback ) { - setKTX2Loader: function ( ktx2Loader ) { + if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) { - this.ktx2Loader = ktx2Loader; - return this; + this.pluginCallbacks.push( callback ); - }, + } - setMeshoptDecoder: function ( meshoptDecoder ) { + return this; - this.meshoptDecoder = meshoptDecoder; - return this; + } - }, + unregister( callback ) { - register: function ( callback ) { + if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) { - if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) { + this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 ); - this.pluginCallbacks.push( callback ); + } - } + return this; - return this; + } - }, + parse( data, path, onLoad, onError ) { - unregister: function ( callback ) { + let content; + const extensions = {}; + const plugins = {}; - if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) { + if ( typeof data === 'string' ) { - this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 ); + content = data; - } + } else { - return this; + const magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); - }, + if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { - parse: function ( data, path, onLoad, onError ) { + try { - var content; - var extensions = {}; - var plugins = {}; + extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); - if ( typeof data === 'string' ) { + } catch ( error ) { - content = data; + if ( onError ) onError( error ); + return; - } else { + } - var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); + content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; - if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { + } else { - try { + content = LoaderUtils.decodeText( new Uint8Array( data ) ); - extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); + } - } catch ( error ) { + } - if ( onError ) onError( error ); - return; + const json = JSON.parse( content ); - } + if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { - content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; + if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) ); + return; - } else { + } - content = LoaderUtils.decodeText( new Uint8Array( data ) ); + const parser = new GLTFParser( json, { - } + path: path || this.resourcePath || '', + crossOrigin: this.crossOrigin, + requestHeader: this.requestHeader, + manager: this.manager, + ktx2Loader: this.ktx2Loader, + meshoptDecoder: this.meshoptDecoder - } + } ); - var json = JSON.parse( content ); + parser.fileLoader.setRequestHeader( this.requestHeader ); - if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { + for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) { - if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) ); - return; + const plugin = this.pluginCallbacks[ i ]( parser ); + plugins[ plugin.name ] = plugin; - } + // Workaround to avoid determining as unknown extension + // in addUnknownExtensionsToUserData(). + // Remove this workaround if we move all the existing + // extension handlers to plugin system + extensions[ plugin.name ] = true; - var parser = new GLTFParser( json, { + } - path: path || this.resourcePath || '', - crossOrigin: this.crossOrigin, - requestHeader: this.requestHeader, - manager: this.manager, - ktx2Loader: this.ktx2Loader, - meshoptDecoder: this.meshoptDecoder + if ( json.extensionsUsed ) { - } ); + for ( let i = 0; i < json.extensionsUsed.length; ++ i ) { - parser.fileLoader.setRequestHeader( this.requestHeader ); + const extensionName = json.extensionsUsed[ i ]; + const extensionsRequired = json.extensionsRequired || []; - for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) { + switch ( extensionName ) { - var plugin = this.pluginCallbacks[ i ]( parser ); - plugins[ plugin.name ] = plugin; + case EXTENSIONS.KHR_MATERIALS_UNLIT: + extensions[ extensionName ] = new GLTFMaterialsUnlitExtension(); + break; - // Workaround to avoid determining as unknown extension - // in addUnknownExtensionsToUserData(). - // Remove this workaround if we move all the existing - // extension handlers to plugin system - extensions[ plugin.name ] = true; + case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: + extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension(); + break; - } + case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: + extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader ); + break; - if ( json.extensionsUsed ) { + case EXTENSIONS.KHR_TEXTURE_TRANSFORM: + extensions[ extensionName ] = new GLTFTextureTransformExtension(); + break; - for ( var i = 0; i < json.extensionsUsed.length; ++ i ) { + case EXTENSIONS.KHR_MESH_QUANTIZATION: + extensions[ extensionName ] = new GLTFMeshQuantizationExtension(); + break; - var extensionName = json.extensionsUsed[ i ]; - var extensionsRequired = json.extensionsRequired || []; + default: - switch ( extensionName ) { + if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) { - case EXTENSIONS.KHR_MATERIALS_UNLIT: - extensions[ extensionName ] = new GLTFMaterialsUnlitExtension(); - break; + console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' ); - case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: - extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension(); - break; + } - case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: - extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader ); - break; + } - case EXTENSIONS.KHR_TEXTURE_TRANSFORM: - extensions[ extensionName ] = new GLTFTextureTransformExtension(); - break; + } - case EXTENSIONS.KHR_MESH_QUANTIZATION: - extensions[ extensionName ] = new GLTFMeshQuantizationExtension(); - break; + } - default: + parser.setExtensions( extensions ); + parser.setPlugins( plugins ); + parser.parse( onLoad, onError ); - if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) { + } - console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' ); + parseAsync( data, path ) { - } + const scope = this; - } + return new Promise( function ( resolve, reject ) { - } + scope.parse( data, path, resolve, reject ); - } + } ); - parser.setExtensions( extensions ); - parser.setPlugins( plugins ); - parser.parse( onLoad, onError ); + } - } +} - } ); +/* GLTFREGISTRY */ - /* GLTFREGISTRY */ +function GLTFRegistry() { - function GLTFRegistry() { + let objects = {}; - var objects = {}; + return { - return { + get: function ( key ) { - get: function ( key ) { + return objects[ key ]; - return objects[ key ]; + }, - }, + add: function ( key, object ) { - add: function ( key, object ) { + objects[ key ] = object; - objects[ key ] = object; + }, - }, + remove: function ( key ) { - remove: function ( key ) { + delete objects[ key ]; - delete objects[ key ]; + }, - }, + removeAll: function () { - removeAll: function () { + objects = {}; - objects = {}; + } - } + }; - }; +} - } +/*********************************/ +/********** EXTENSIONS ***********/ +/*********************************/ + +const EXTENSIONS = { + KHR_BINARY_GLTF: 'KHR_binary_glTF', + KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', + KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', + KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat', + KHR_MATERIALS_IOR: 'KHR_materials_ior', + KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', + KHR_MATERIALS_SHEEN: 'KHR_materials_sheen', + KHR_MATERIALS_SPECULAR: 'KHR_materials_specular', + KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', + KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence', + KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', + KHR_MATERIALS_VOLUME: 'KHR_materials_volume', + KHR_TEXTURE_BASISU: 'KHR_texture_basisu', + KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', + KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', + KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength', + EXT_TEXTURE_WEBP: 'EXT_texture_webp', + EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression' +}; - /*********************************/ - /********** EXTENSIONS ***********/ - /*********************************/ - - var EXTENSIONS = { - KHR_BINARY_GLTF: 'KHR_binary_glTF', - KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', - KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', - KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat', - KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', - KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', - KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', - KHR_TEXTURE_BASISU: 'KHR_texture_basisu', - KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', - KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', - EXT_TEXTURE_WEBP: 'EXT_texture_webp', - EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression' - }; +/** + * Punctual Lights Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual + */ +class GLTFLightsExtension { - /** - * Punctual Lights Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual - */ - function GLTFLightsExtension( parser ) { + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; @@ -50981,18 +51716,18 @@ var GLTFLoader = ( function () { } - GLTFLightsExtension.prototype._markDefs = function () { + _markDefs() { - var parser = this.parser; - var nodeDefs = this.parser.json.nodes || []; + const parser = this.parser; + const nodeDefs = this.parser.json.nodes || []; - for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { + for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { - var nodeDef = nodeDefs[ nodeIndex ]; + const nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.extensions - && nodeDef.extensions[ this.name ] - && nodeDef.extensions[ this.name ].light !== undefined ) { + && nodeDef.extensions[ this.name ] + && nodeDef.extensions[ this.name ].light !== undefined ) { parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light ); @@ -51000,27 +51735,27 @@ var GLTFLoader = ( function () { } - }; + } - GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) { + _loadLight( lightIndex ) { - var parser = this.parser; - var cacheKey = 'light:' + lightIndex; - var dependency = parser.cache.get( cacheKey ); + const parser = this.parser; + const cacheKey = 'light:' + lightIndex; + let dependency = parser.cache.get( cacheKey ); if ( dependency ) return dependency; - var json = parser.json; - var extensions = ( json.extensions && json.extensions[ this.name ] ) || {}; - var lightDefs = extensions.lights || []; - var lightDef = lightDefs[ lightIndex ]; - var lightNode; + const json = parser.json; + const extensions = ( json.extensions && json.extensions[ this.name ] ) || {}; + const lightDefs = extensions.lights || []; + const lightDef = lightDefs[ lightIndex ]; + let lightNode; - var color = new Color( 0xffffff ); + const color = new Color( 0xffffff ); if ( lightDef.color !== undefined ) color.fromArray( lightDef.color ); - var range = lightDef.range !== undefined ? lightDef.range : 0; + const range = lightDef.range !== undefined ? lightDef.range : 0; switch ( lightDef.type ) { @@ -51069,16 +51804,16 @@ var GLTFLoader = ( function () { return dependency; - }; + } - GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) { + createNodeAttachment( nodeIndex ) { - var self = this; - var parser = this.parser; - var json = parser.json; - var nodeDef = json.nodes[ nodeIndex ]; - var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {}; - var lightIndex = lightDef.light; + const self = this; + const parser = this.parser; + const json = parser.json; + const nodeDef = json.nodes[ nodeIndex ]; + const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {}; + const lightIndex = lightDef.light; if ( lightIndex === undefined ) return null; @@ -51088,39 +51823,43 @@ var GLTFLoader = ( function () { } ); - }; + } - /** - * Unlit Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit - */ - function GLTFMaterialsUnlitExtension() { +} + +/** + * Unlit Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit + */ +class GLTFMaterialsUnlitExtension { + + constructor() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } - GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () { + getMaterialType() { return MeshBasicMaterial; - }; + } - GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) { + extendParams( materialParams, materialDef, parser ) { - var pending = []; + const pending = []; materialParams.color = new Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; - var metallicRoughness = materialDef.pbrMetallicRoughness; + const metallicRoughness = materialDef.pbrMetallicRoughness; if ( metallicRoughness ) { if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { - var array = metallicRoughness.baseColorFactor; + const array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; @@ -51129,7 +51868,7 @@ var GLTFLoader = ( function () { if ( metallicRoughness.baseColorTexture !== undefined ) { - pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); + pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding ) ); } @@ -51137,35 +51876,78 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } - /** - * Clearcoat Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat - */ - function GLTFMaterialsClearcoatExtension( parser ) { +} + +/** + * Materials Emissive Strength Extension + * + * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md + */ +class GLTFMaterialsEmissiveStrengthExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength; + + if ( emissiveStrength !== undefined ) { + + materialParams.emissiveIntensity = emissiveStrength; + + } + + return Promise.resolve(); + + } + +} + +/** + * Clearcoat Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat + */ +class GLTFMaterialsClearcoatExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; } - GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) { + getMaterialType( materialIndex ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; return MeshPhysicalMaterial; - }; + } - GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) { + extendMaterialParams( materialIndex, materialParams ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { @@ -51173,9 +51955,9 @@ var GLTFLoader = ( function () { } - var pending = []; + const pending = []; - var extension = materialDef.extensions[ this.name ]; + const extension = materialDef.extensions[ this.name ]; if ( extension.clearcoatFactor !== undefined ) { @@ -51207,10 +51989,9 @@ var GLTFLoader = ( function () { if ( extension.clearcoatNormalTexture.scale !== undefined ) { - var scale = extension.clearcoatNormalTexture.scale; + const scale = extension.clearcoatNormalTexture.scale; - // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 - materialParams.clearcoatNormalScale = new Vector2( scale, - scale ); + materialParams.clearcoatNormalScale = new Vector2( scale, scale ); } @@ -51218,36 +51999,202 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } - /** - * Transmission Materials Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission - * Draft: https://github.com/KhronosGroup/glTF/pull/1698 - */ - function GLTFMaterialsTransmissionExtension( parser ) { +} + +/** + * Iridescence Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence + */ +class GLTFMaterialsIridescenceExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.iridescenceFactor !== undefined ) { + + materialParams.iridescence = extension.iridescenceFactor; + + } + + if ( extension.iridescenceTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) ); + + } + + if ( extension.iridescenceIor !== undefined ) { + + materialParams.iridescenceIOR = extension.iridescenceIor; + + } + + if ( materialParams.iridescenceThicknessRange === undefined ) { + + materialParams.iridescenceThicknessRange = [ 100, 400 ]; + + } + + if ( extension.iridescenceThicknessMinimum !== undefined ) { + + materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum; + + } + + if ( extension.iridescenceThicknessMaximum !== undefined ) { + + materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum; + + } + + if ( extension.iridescenceThicknessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Sheen Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen + */ +class GLTFMaterialsSheenExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + materialParams.sheenColor = new Color( 0, 0, 0 ); + materialParams.sheenRoughness = 0; + materialParams.sheen = 1; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.sheenColorFactor !== undefined ) { + + materialParams.sheenColor.fromArray( extension.sheenColorFactor ); + + } + + if ( extension.sheenRoughnessFactor !== undefined ) { + + materialParams.sheenRoughness = extension.sheenRoughnessFactor; + + } + + if ( extension.sheenColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, sRGBEncoding ) ); + + } + + if ( extension.sheenRoughnessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Transmission Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission + * Draft: https://github.com/KhronosGroup/glTF/pull/1698 + */ +class GLTFMaterialsTransmissionExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; } - GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) { + getMaterialType( materialIndex ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; return MeshPhysicalMaterial; - }; + } - GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) { + extendMaterialParams( materialIndex, materialParams ) { - var parser = this.parser; - var materialDef = parser.json.materials[ materialIndex ]; + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { @@ -51255,9 +52202,9 @@ var GLTFLoader = ( function () { } - var pending = []; + const pending = []; - var extension = materialDef.extensions[ this.name ]; + const extension = materialDef.extensions[ this.name ]; if ( extension.transmissionFactor !== undefined ) { @@ -51273,26 +52220,198 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } - /** - * BasisU Texture Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu - */ - function GLTFTextureBasisUExtension( parser ) { +} + +/** + * Materials Volume Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume + */ +class GLTFMaterialsVolumeExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; + + if ( extension.thicknessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) ); + + } + + materialParams.attenuationDistance = extension.attenuationDistance || 0; + + const colorArray = extension.attenuationColor || [ 1, 1, 1 ]; + materialParams.attenuationColor = new Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] ); + + return Promise.all( pending ); + + } + +} + +/** + * Materials ior Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior + */ +class GLTFMaterialsIorExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IOR; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const extension = materialDef.extensions[ this.name ]; + + materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; + + return Promise.resolve(); + + } + +} + +/** + * Materials specular Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular + */ +class GLTFMaterialsSpecularExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0; + + if ( extension.specularTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) ); + + } + + const colorArray = extension.specularColorFactor || [ 1, 1, 1 ]; + materialParams.specularColor = new Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] ); + + if ( extension.specularColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, sRGBEncoding ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * BasisU Texture Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu + */ +class GLTFTextureBasisUExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.KHR_TEXTURE_BASISU; } - GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) { + loadTexture( textureIndex ) { - var parser = this.parser; - var json = parser.json; + const parser = this.parser; + const json = parser.json; - var textureDef = json.textures[ textureIndex ]; + const textureDef = json.textures[ textureIndex ]; if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) { @@ -51300,9 +52419,8 @@ var GLTFLoader = ( function () { } - var extension = textureDef.extensions[ this.name ]; - var source = json.images[ extension.source ]; - var loader = parser.options.ktx2Loader; + const extension = textureDef.extensions[ this.name ]; + const loader = parser.options.ktx2Loader; if ( ! loader ) { @@ -51319,16 +52437,20 @@ var GLTFLoader = ( function () { } - return parser.loadTextureImage( textureIndex, source, loader ); + return parser.loadTextureImage( textureIndex, extension.source, loader ); - }; + } - /** - * WebP Texture Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp - */ - function GLTFTextureWebPExtension( parser ) { +} + +/** + * WebP Texture Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp + */ +class GLTFTextureWebPExtension { + + constructor( parser ) { this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_WEBP; @@ -51336,13 +52458,13 @@ var GLTFLoader = ( function () { } - GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) { + loadTexture( textureIndex ) { - var name = this.name; - var parser = this.parser; - var json = parser.json; + const name = this.name; + const parser = this.parser; + const json = parser.json; - var textureDef = json.textures[ textureIndex ]; + const textureDef = json.textures[ textureIndex ]; if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) { @@ -51350,20 +52472,20 @@ var GLTFLoader = ( function () { } - var extension = textureDef.extensions[ name ]; - var source = json.images[ extension.source ]; + const extension = textureDef.extensions[ name ]; + const source = json.images[ extension.source ]; - var loader = parser.textureLoader; + let loader = parser.textureLoader; if ( source.uri ) { - var handler = parser.options.manager.getHandler( source.uri ); + const handler = parser.options.manager.getHandler( source.uri ); if ( handler !== null ) loader = handler; } return this.detectSupport().then( function ( isSupported ) { - if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader ); + if ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader ); if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) { @@ -51376,15 +52498,15 @@ var GLTFLoader = ( function () { } ); - }; + } - GLTFTextureWebPExtension.prototype.detectSupport = function () { + detectSupport() { if ( ! this.isSupported ) { this.isSupported = new Promise( function ( resolve ) { - var image = new Image(); + const image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all // WebP images, unfortunately. @@ -51402,31 +52524,35 @@ var GLTFLoader = ( function () { return this.isSupported; - }; + } - /** - * meshopt BufferView Compression Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression - */ - function GLTFMeshoptCompression( parser ) { +} + +/** + * meshopt BufferView Compression Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression + */ +class GLTFMeshoptCompression { + + constructor( parser ) { this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; this.parser = parser; } - GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) { + loadBufferView( index ) { - var json = this.parser.json; - var bufferView = json.bufferViews[ index ]; + const json = this.parser.json; + const bufferView = json.bufferViews[ index ]; if ( bufferView.extensions && bufferView.extensions[ this.name ] ) { - var extensionDef = bufferView.extensions[ this.name ]; + const extensionDef = bufferView.extensions[ this.name ]; - var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer ); - var decoder = this.parser.options.meshoptDecoder; + const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer ); + const decoder = this.parser.options.meshoptDecoder; if ( ! decoder || ! decoder.supported ) { @@ -51443,19 +52569,36 @@ var GLTFLoader = ( function () { } - return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) { + return buffer.then( function ( res ) { + + const byteOffset = extensionDef.byteOffset || 0; + const byteLength = extensionDef.byteLength || 0; + + const count = extensionDef.count; + const stride = extensionDef.byteStride; + + const source = new Uint8Array( res, byteOffset, byteLength ); + + if ( decoder.decodeGltfBufferAsync ) { + + return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) { + + return res.buffer; + + } ); + + } else { - var byteOffset = extensionDef.byteOffset || 0; - var byteLength = extensionDef.byteLength || 0; + // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync + return decoder.ready.then( function () { - var count = extensionDef.count; - var stride = extensionDef.byteStride; + const result = new ArrayBuffer( count * stride ); + decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter ); + return result; - var result = new ArrayBuffer( count * stride ); - var source = new Uint8Array( res[ 0 ], byteOffset, byteLength ); + } ); - decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter ); - return result; + } } ); @@ -51465,20 +52608,24 @@ var GLTFLoader = ( function () { } - }; + } + +} + +/* BINARY EXTENSION */ +const BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; +const BINARY_EXTENSION_HEADER_LENGTH = 12; +const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; - /* BINARY EXTENSION */ - var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; - var BINARY_EXTENSION_HEADER_LENGTH = 12; - var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; +class GLTFBinaryExtension { - function GLTFBinaryExtension( data ) { + constructor( data ) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; - var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); + const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); this.header = { magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ), @@ -51496,26 +52643,26 @@ var GLTFLoader = ( function () { } - var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; - var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); - var chunkIndex = 0; + const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; + const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); + let chunkIndex = 0; while ( chunkIndex < chunkContentsLength ) { - var chunkLength = chunkView.getUint32( chunkIndex, true ); + const chunkLength = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; - var chunkType = chunkView.getUint32( chunkIndex, true ); + const chunkType = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) { - var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); + const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); this.content = LoaderUtils.decodeText( contentArray ); } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) { - var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; + const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice( byteOffset, byteOffset + chunkLength ); } @@ -51534,12 +52681,16 @@ var GLTFLoader = ( function () { } - /** - * DRACO Mesh Compression Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression - */ - function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { +} + +/** + * DRACO Mesh Compression Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression + */ +class GLTFDracoMeshCompressionExtension { + + constructor( json, dracoLoader ) { if ( ! dracoLoader ) { @@ -51554,34 +52705,34 @@ var GLTFLoader = ( function () { } - GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) { + decodePrimitive( primitive, parser ) { - var json = this.json; - var dracoLoader = this.dracoLoader; - var bufferViewIndex = primitive.extensions[ this.name ].bufferView; - var gltfAttributeMap = primitive.extensions[ this.name ].attributes; - var threeAttributeMap = {}; - var attributeNormalizedMap = {}; - var attributeTypeMap = {}; + const json = this.json; + const dracoLoader = this.dracoLoader; + const bufferViewIndex = primitive.extensions[ this.name ].bufferView; + const gltfAttributeMap = primitive.extensions[ this.name ].attributes; + const threeAttributeMap = {}; + const attributeNormalizedMap = {}; + const attributeTypeMap = {}; - for ( var attributeName in gltfAttributeMap ) { + for ( const attributeName in gltfAttributeMap ) { - var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); + const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ]; } - for ( attributeName in primitive.attributes ) { + for ( const attributeName in primitive.attributes ) { - var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); + const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); if ( gltfAttributeMap[ attributeName ] !== undefined ) { - var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ]; - var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; + const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ]; + const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; - attributeTypeMap[ threeAttributeName ] = componentType; + attributeTypeMap[ threeAttributeName ] = componentType.name; attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true; } @@ -51594,10 +52745,10 @@ var GLTFLoader = ( function () { dracoLoader.decodeDracoFile( bufferView, function ( geometry ) { - for ( var attributeName in geometry.attributes ) { + for ( const attributeName in geometry.attributes ) { - var attribute = geometry.attributes[ attributeName ]; - var normalized = attributeNormalizedMap[ attributeName ]; + const attribute = geometry.attributes[ attributeName ]; + const normalized = attributeNormalizedMap[ attributeName ]; if ( normalized !== undefined ) attribute.normalized = normalized; @@ -51611,20 +52762,37 @@ var GLTFLoader = ( function () { } ); - }; + } - /** - * Texture Transform Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform - */ - function GLTFTextureTransformExtension() { +} + +/** + * Texture Transform Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform + */ +class GLTFTextureTransformExtension { + + constructor() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } - GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) { + extendTexture( texture, transform ) { + + if ( transform.texCoord !== undefined ) { + + console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' ); + + } + + if ( transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined ) { + + // See https://github.com/mrdoob/three.js/issues/21819. + return texture; + + } texture = texture.clone(); @@ -51646,60 +52814,56 @@ var GLTFLoader = ( function () { } - if ( transform.texCoord !== undefined ) { - - console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' ); - - } - texture.needsUpdate = true; return texture; - }; + } - /** - * Specular-Glossiness Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness - */ +} - /** - * A sub class of StandardMaterial with some of the functionality - * changed via the `onBeforeCompile` callback - * @pailhead - */ +/** + * Specular-Glossiness Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness + */ - function GLTFMeshStandardSGMaterial( params ) { +/** + * A sub class of StandardMaterial with some of the functionality + * changed via the `onBeforeCompile` callback + * @pailhead + */ +class GLTFMeshStandardSGMaterial extends MeshStandardMaterial { - MeshStandardMaterial.call( this ); + constructor( params ) { + + super(); this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing - var specularMapParsFragmentChunk = [ + const specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' ); - var glossinessMapParsFragmentChunk = [ + const glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' ); - var specularMapFragmentChunk = [ + const specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', - ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' ); - var glossinessMapFragmentChunk = [ + const glossinessMapFragmentChunk = [ 'float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', @@ -51708,18 +52872,18 @@ var GLTFLoader = ( function () { '#endif' ].join( '\n' ); - var lightPhysicalFragmentChunk = [ + const lightPhysicalFragmentChunk = [ 'PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', - 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', - 'material.specularRoughness += geometryRoughness;', - 'material.specularRoughness = min( material.specularRoughness, 1.0 );', + 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', + 'material.roughness += geometryRoughness;', + 'material.roughness = min( material.roughness, 1.0 );', 'material.specularColor = specularFactor;', ].join( '\n' ); - var uniforms = { + const uniforms = { specular: { value: new Color().setHex( 0xffffff ) }, glossiness: { value: 1 }, specularMap: { value: null }, @@ -51730,7 +52894,7 @@ var GLTFLoader = ( function () { this.onBeforeCompile = function ( shader ) { - for ( var uniformName in uniforms ) { + for ( const uniformName in uniforms ) { shader.uniforms[ uniformName ] = uniforms[ uniformName ]; @@ -51834,12 +52998,10 @@ var GLTFLoader = ( function () { } - GLTFMeshStandardSGMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); - GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial; + copy( source ) { - GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) { + super.copy( source ); - MeshStandardMaterial.prototype.copy.call( this, source ); this.specularMap = source.specularMap; this.specular.copy( source.specular ); this.glossinessMap = source.glossinessMap; @@ -51850,182 +53012,185 @@ var GLTFLoader = ( function () { delete this.roughnessMap; return this; - }; + } - function GLTFMaterialsPbrSpecularGlossinessExtension() { +} - return { - name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS, - - specularGlossinessParams: [ - 'color', - 'map', - 'lightMap', - 'lightMapIntensity', - 'aoMap', - 'aoMapIntensity', - 'emissive', - 'emissiveIntensity', - 'emissiveMap', - 'bumpMap', - 'bumpScale', - 'normalMap', - 'normalMapType', - 'displacementMap', - 'displacementScale', - 'displacementBias', - 'specularMap', - 'specular', - 'glossinessMap', - 'glossiness', - 'alphaMap', - 'envMap', - 'envMapIntensity', - 'refractionRatio', - ], - - getMaterialType: function () { - - return GLTFMeshStandardSGMaterial; +class GLTFMaterialsPbrSpecularGlossinessExtension { - }, + constructor() { - extendParams: function ( materialParams, materialDef, parser ) { + this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS; + + this.specularGlossinessParams = [ + 'color', + 'map', + 'lightMap', + 'lightMapIntensity', + 'aoMap', + 'aoMapIntensity', + 'emissive', + 'emissiveIntensity', + 'emissiveMap', + 'bumpMap', + 'bumpScale', + 'normalMap', + 'normalMapType', + 'displacementMap', + 'displacementScale', + 'displacementBias', + 'specularMap', + 'specular', + 'glossinessMap', + 'glossiness', + 'alphaMap', + 'envMap', + 'envMapIntensity' + ]; - var pbrSpecularGlossiness = materialDef.extensions[ this.name ]; + } - materialParams.color = new Color( 1.0, 1.0, 1.0 ); - materialParams.opacity = 1.0; + getMaterialType() { - var pending = []; + return GLTFMeshStandardSGMaterial; - if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) { + } - var array = pbrSpecularGlossiness.diffuseFactor; + extendParams( materialParams, materialDef, parser ) { - materialParams.color.fromArray( array ); - materialParams.opacity = array[ 3 ]; + const pbrSpecularGlossiness = materialDef.extensions[ this.name ]; - } + materialParams.color = new Color( 1.0, 1.0, 1.0 ); + materialParams.opacity = 1.0; - if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) { + const pending = []; - pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) ); + if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) { - } + const array = pbrSpecularGlossiness.diffuseFactor; - materialParams.emissive = new Color( 0.0, 0.0, 0.0 ); - materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; - materialParams.specular = new Color( 1.0, 1.0, 1.0 ); + materialParams.color.fromArray( array ); + materialParams.opacity = array[ 3 ]; - if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { + } - materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor ); + if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) { - } + pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture, sRGBEncoding ) ); - if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) { + } - var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; - pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) ); - pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) ); + materialParams.emissive = new Color( 0.0, 0.0, 0.0 ); + materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; + materialParams.specular = new Color( 1.0, 1.0, 1.0 ); - } + if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { - return Promise.all( pending ); + materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor ); - }, + } - createMaterial: function ( materialParams ) { + if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) { - var material = new GLTFMeshStandardSGMaterial( materialParams ); - material.fog = true; + const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; + pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) ); + pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef, sRGBEncoding ) ); - material.color = materialParams.color; + } - material.map = materialParams.map === undefined ? null : materialParams.map; + return Promise.all( pending ); - material.lightMap = null; - material.lightMapIntensity = 1.0; + } - material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap; - material.aoMapIntensity = 1.0; + createMaterial( materialParams ) { - material.emissive = materialParams.emissive; - material.emissiveIntensity = 1.0; - material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap; + const material = new GLTFMeshStandardSGMaterial( materialParams ); + material.fog = true; - material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap; - material.bumpScale = 1; + material.color = materialParams.color; - material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap; - material.normalMapType = TangentSpaceNormalMap; + material.map = materialParams.map === undefined ? null : materialParams.map; - if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale; + material.lightMap = null; + material.lightMapIntensity = 1.0; - material.displacementMap = null; - material.displacementScale = 1; - material.displacementBias = 0; + material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap; + material.aoMapIntensity = 1.0; - material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap; - material.specular = materialParams.specular; + material.emissive = materialParams.emissive; + material.emissiveIntensity = materialParams.emissiveIntensity === undefined ? 1.0 : materialParams.emissiveIntensity; + material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap; - material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap; - material.glossiness = materialParams.glossiness; + material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap; + material.bumpScale = 1; - material.alphaMap = null; + material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap; + material.normalMapType = TangentSpaceNormalMap; - material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap; - material.envMapIntensity = 1.0; + if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale; - material.refractionRatio = 0.98; + material.displacementMap = null; + material.displacementScale = 1; + material.displacementBias = 0; - return material; + material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap; + material.specular = materialParams.specular; - }, + material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap; + material.glossiness = materialParams.glossiness; - }; + material.alphaMap = null; + + material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap; + material.envMapIntensity = 1.0; + + return material; } - /** - * Mesh Quantization Extension - * - * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization - */ - function GLTFMeshQuantizationExtension() { +} + +/** + * Mesh Quantization Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization + */ +class GLTFMeshQuantizationExtension { + + constructor() { this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; } - /*********************************/ - /********** INTERPOLATION ********/ - /*********************************/ +} - // Spline Interpolation - // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation - function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { +/*********************************/ +/********** INTERPOLATION ********/ +/*********************************/ - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); +// Spline Interpolation +// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation +class GLTFCubicSplineInterpolant extends Interpolant { - } + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); - GLTFCubicSplineInterpolant.prototype = Object.create( Interpolant.prototype ); - GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant; + } - GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) { + copySampleValue_( index ) { // Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. - var result = this.resultBuffer, + const result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; - for ( var i = 0; i !== valueSize; i ++ ) { + for ( let i = 0; i !== valueSize; i ++ ) { result[ i ] = values[ offset + i ]; @@ -52033,43 +53198,39 @@ var GLTFLoader = ( function () { return result; - }; - - GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; - - GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; + } - GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) { + interpolate_( i1, t0, t, t1 ) { - var result = this.resultBuffer; - var values = this.sampleValues; - var stride = this.valueSize; + const result = this.resultBuffer; + const values = this.sampleValues; + const stride = this.valueSize; - var stride2 = stride * 2; - var stride3 = stride * 3; + const stride2 = stride * 2; + const stride3 = stride * 3; - var td = t1 - t0; + const td = t1 - t0; - var p = ( t - t0 ) / td; - var pp = p * p; - var ppp = pp * p; + const p = ( t - t0 ) / td; + const pp = p * p; + const ppp = pp * p; - var offset1 = i1 * stride3; - var offset0 = offset1 - stride3; + const offset1 = i1 * stride3; + const offset0 = offset1 - stride3; - var s2 = - 2 * ppp + 3 * pp; - var s3 = ppp - pp; - var s0 = 1 - s2; - var s1 = s3 - pp + p; + const s2 = - 2 * ppp + 3 * pp; + const s3 = ppp - pp; + const s0 = 1 - s2; + const s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] - for ( var i = 0; i !== stride; i ++ ) { + for ( let i = 0; i !== stride; i ++ ) { - var p0 = values[ offset0 + i + stride ]; // splineVertex_k - var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k) - var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1 - var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k) + const p0 = values[ offset0 + i + stride ]; // splineVertex_k + const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k) + const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1 + const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k) result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; @@ -52077,352 +53238,396 @@ var GLTFLoader = ( function () { return result; - }; + } - /*********************************/ - /********** INTERNALS ************/ - /*********************************/ - - /* CONSTANTS */ - - var WEBGL_CONSTANTS = { - FLOAT: 5126, - //FLOAT_MAT2: 35674, - FLOAT_MAT3: 35675, - FLOAT_MAT4: 35676, - FLOAT_VEC2: 35664, - FLOAT_VEC3: 35665, - FLOAT_VEC4: 35666, - LINEAR: 9729, - REPEAT: 10497, - SAMPLER_2D: 35678, - POINTS: 0, - LINES: 1, - LINE_LOOP: 2, - LINE_STRIP: 3, - TRIANGLES: 4, - TRIANGLE_STRIP: 5, - TRIANGLE_FAN: 6, - UNSIGNED_BYTE: 5121, - UNSIGNED_SHORT: 5123 - }; +} - var WEBGL_COMPONENT_TYPES = { - 5120: Int8Array, - 5121: Uint8Array, - 5122: Int16Array, - 5123: Uint16Array, - 5125: Uint32Array, - 5126: Float32Array - }; +const _q = new Quaternion(); - var WEBGL_FILTERS = { - 9728: NearestFilter, - 9729: LinearFilter, - 9984: NearestMipmapNearestFilter, - 9985: LinearMipmapNearestFilter, - 9986: NearestMipmapLinearFilter, - 9987: LinearMipmapLinearFilter - }; +class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { - var WEBGL_WRAPPINGS = { - 33071: ClampToEdgeWrapping, - 33648: MirroredRepeatWrapping, - 10497: RepeatWrapping - }; + interpolate_( i1, t0, t, t1 ) { - var WEBGL_TYPE_SIZES = { - 'SCALAR': 1, - 'VEC2': 2, - 'VEC3': 3, - 'VEC4': 4, - 'MAT2': 4, - 'MAT3': 9, - 'MAT4': 16 - }; + const result = super.interpolate_( i1, t0, t, t1 ); - var ATTRIBUTES = { - POSITION: 'position', - NORMAL: 'normal', - TANGENT: 'tangent', - TEXCOORD_0: 'uv', - TEXCOORD_1: 'uv2', - COLOR_0: 'color', - WEIGHTS_0: 'skinWeight', - JOINTS_0: 'skinIndex', - }; - - var PATH_PROPERTIES = { - scale: 'scale', - translation: 'position', - rotation: 'quaternion', - weights: 'morphTargetInfluences' - }; + _q.fromArray( result ).normalize().toArray( result ); - var INTERPOLATION = { - CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each - // keyframe track will be initialized with a default interpolation type, then modified. - LINEAR: InterpolateLinear, - STEP: InterpolateDiscrete - }; + return result; - var ALPHA_MODES = { - OPAQUE: 'OPAQUE', - MASK: 'MASK', - BLEND: 'BLEND' - }; + } - /* UTILITY FUNCTIONS */ +} - function resolveURL( url, path ) { - // Invalid URL - if ( typeof url !== 'string' || url === '' ) return ''; +/*********************************/ +/********** INTERNALS ************/ +/*********************************/ - // Host Relative URL - if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { +/* CONSTANTS */ - path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); +const WEBGL_CONSTANTS = { + FLOAT: 5126, + //FLOAT_MAT2: 35674, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + LINEAR: 9729, + REPEAT: 10497, + SAMPLER_2D: 35678, + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + UNSIGNED_BYTE: 5121, + UNSIGNED_SHORT: 5123 +}; - } +const WEBGL_COMPONENT_TYPES = { + 5120: Int8Array, + 5121: Uint8Array, + 5122: Int16Array, + 5123: Uint16Array, + 5125: Uint32Array, + 5126: Float32Array +}; - // Absolute URL http://,https://,// - if ( /^(https?:)?\/\//i.test( url ) ) return url; +const WEBGL_FILTERS = { + 9728: NearestFilter, + 9729: LinearFilter, + 9984: NearestMipmapNearestFilter, + 9985: LinearMipmapNearestFilter, + 9986: NearestMipmapLinearFilter, + 9987: LinearMipmapLinearFilter +}; - // Data URI - if ( /^data:.*,.*$/i.test( url ) ) return url; +const WEBGL_WRAPPINGS = { + 33071: ClampToEdgeWrapping, + 33648: MirroredRepeatWrapping, + 10497: RepeatWrapping +}; - // Blob URL - if ( /^blob:.*$/i.test( url ) ) return url; +const WEBGL_TYPE_SIZES = { + 'SCALAR': 1, + 'VEC2': 2, + 'VEC3': 3, + 'VEC4': 4, + 'MAT2': 4, + 'MAT3': 9, + 'MAT4': 16 +}; - // Relative URL - return path + url; +const ATTRIBUTES = { + POSITION: 'position', + NORMAL: 'normal', + TANGENT: 'tangent', + TEXCOORD_0: 'uv', + TEXCOORD_1: 'uv2', + COLOR_0: 'color', + WEIGHTS_0: 'skinWeight', + JOINTS_0: 'skinIndex', +}; - } +const PATH_PROPERTIES = { + scale: 'scale', + translation: 'position', + rotation: 'quaternion', + weights: 'morphTargetInfluences' +}; - /** - * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material - */ - function createDefaultMaterial( cache ) { - - if ( cache[ 'DefaultMaterial' ] === undefined ) { - - cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( { - color: 0xFFFFFF, - emissive: 0x000000, - metalness: 1, - roughness: 1, - transparent: false, - depthTest: true, - side: FrontSide - } ); +const INTERPOLATION = { + CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each + // keyframe track will be initialized with a default interpolation type, then modified. + LINEAR: InterpolateLinear, + STEP: InterpolateDiscrete +}; - } +const ALPHA_MODES = { + OPAQUE: 'OPAQUE', + MASK: 'MASK', + BLEND: 'BLEND' +}; - return cache[ 'DefaultMaterial' ]; +/** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material + */ +function createDefaultMaterial( cache ) { + + if ( cache[ 'DefaultMaterial' ] === undefined ) { + + cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( { + color: 0xFFFFFF, + emissive: 0x000000, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: FrontSide + } ); } - function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) { + return cache[ 'DefaultMaterial' ]; - // Add unknown glTF extensions to an object's userData. +} - for ( var name in objectDef.extensions ) { +function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) { - if ( knownExtensions[ name ] === undefined ) { + // Add unknown glTF extensions to an object's userData. - object.userData.gltfExtensions = object.userData.gltfExtensions || {}; - object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ]; + for ( const name in objectDef.extensions ) { - } + if ( knownExtensions[ name ] === undefined ) { + + object.userData.gltfExtensions = object.userData.gltfExtensions || {}; + object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ]; } } - /** - * @param {Object3D|Material|BufferGeometry} object - * @param {GLTF.definition} gltfDef - */ - function assignExtrasToUserData( object, gltfDef ) { +} - if ( gltfDef.extras !== undefined ) { +/** + * @param {Object3D|Material|BufferGeometry} object + * @param {GLTF.definition} gltfDef + */ +function assignExtrasToUserData( object, gltfDef ) { - if ( typeof gltfDef.extras === 'object' ) { + if ( gltfDef.extras !== undefined ) { - Object.assign( object.userData, gltfDef.extras ); + if ( typeof gltfDef.extras === 'object' ) { - } else { + Object.assign( object.userData, gltfDef.extras ); - console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras ); + } else { - } + console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras ); } } - /** - * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets - * - * @param {BufferGeometry} geometry - * @param {Array} targets - * @param {GLTFParser} parser - * @return {Promise} - */ - function addMorphTargets( geometry, targets, parser ) { +} - var hasMorphPosition = false; - var hasMorphNormal = false; +/** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets + * + * @param {BufferGeometry} geometry + * @param {Array} targets + * @param {GLTFParser} parser + * @return {Promise} + */ +function addMorphTargets( geometry, targets, parser ) { - for ( var i = 0, il = targets.length; i < il; i ++ ) { + let hasMorphPosition = false; + let hasMorphNormal = false; + let hasMorphColor = false; - var target = targets[ i ]; + for ( let i = 0, il = targets.length; i < il; i ++ ) { - if ( target.POSITION !== undefined ) hasMorphPosition = true; - if ( target.NORMAL !== undefined ) hasMorphNormal = true; + const target = targets[ i ]; - if ( hasMorphPosition && hasMorphNormal ) break; + if ( target.POSITION !== undefined ) hasMorphPosition = true; + if ( target.NORMAL !== undefined ) hasMorphNormal = true; + if ( target.COLOR_0 !== undefined ) hasMorphColor = true; - } + if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break; - if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry ); + } - var pendingPositionAccessors = []; - var pendingNormalAccessors = []; + if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry ); - for ( var i = 0, il = targets.length; i < il; i ++ ) { + const pendingPositionAccessors = []; + const pendingNormalAccessors = []; + const pendingColorAccessors = []; - var target = targets[ i ]; + for ( let i = 0, il = targets.length; i < il; i ++ ) { - if ( hasMorphPosition ) { + const target = targets[ i ]; - var pendingAccessor = target.POSITION !== undefined - ? parser.getDependency( 'accessor', target.POSITION ) - : geometry.attributes.position; + if ( hasMorphPosition ) { - pendingPositionAccessors.push( pendingAccessor ); + const pendingAccessor = target.POSITION !== undefined + ? parser.getDependency( 'accessor', target.POSITION ) + : geometry.attributes.position; - } + pendingPositionAccessors.push( pendingAccessor ); - if ( hasMorphNormal ) { + } - var pendingAccessor = target.NORMAL !== undefined - ? parser.getDependency( 'accessor', target.NORMAL ) - : geometry.attributes.normal; + if ( hasMorphNormal ) { - pendingNormalAccessors.push( pendingAccessor ); + const pendingAccessor = target.NORMAL !== undefined + ? parser.getDependency( 'accessor', target.NORMAL ) + : geometry.attributes.normal; - } + pendingNormalAccessors.push( pendingAccessor ); } - return Promise.all( [ - Promise.all( pendingPositionAccessors ), - Promise.all( pendingNormalAccessors ) - ] ).then( function ( accessors ) { + if ( hasMorphColor ) { - var morphPositions = accessors[ 0 ]; - var morphNormals = accessors[ 1 ]; + const pendingAccessor = target.COLOR_0 !== undefined + ? parser.getDependency( 'accessor', target.COLOR_0 ) + : geometry.attributes.color; - if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; - if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; - geometry.morphTargetsRelative = true; + pendingColorAccessors.push( pendingAccessor ); - return geometry; - - } ); + } } - /** - * @param {Mesh} mesh - * @param {GLTF.Mesh} meshDef - */ - function updateMorphTargets( mesh, meshDef ) { + return Promise.all( [ + Promise.all( pendingPositionAccessors ), + Promise.all( pendingNormalAccessors ), + Promise.all( pendingColorAccessors ) + ] ).then( function ( accessors ) { - mesh.updateMorphTargets(); + const morphPositions = accessors[ 0 ]; + const morphNormals = accessors[ 1 ]; + const morphColors = accessors[ 2 ]; - if ( meshDef.weights !== undefined ) { + if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; + if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; + if ( hasMorphColor ) geometry.morphAttributes.color = morphColors; + geometry.morphTargetsRelative = true; - for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) { + return geometry; - mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ]; + } ); - } +} - } +/** + * @param {Mesh} mesh + * @param {GLTF.Mesh} meshDef + */ +function updateMorphTargets( mesh, meshDef ) { - // .extras has user-defined data, so check that .extras.targetNames is an array. - if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) { + mesh.updateMorphTargets(); - var targetNames = meshDef.extras.targetNames; + if ( meshDef.weights !== undefined ) { - if ( mesh.morphTargetInfluences.length === targetNames.length ) { + for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) { - mesh.morphTargetDictionary = {}; + mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ]; - for ( var i = 0, il = targetNames.length; i < il; i ++ ) { + } - mesh.morphTargetDictionary[ targetNames[ i ] ] = i; + } - } + // .extras has user-defined data, so check that .extras.targetNames is an array. + if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) { - } else { + const targetNames = meshDef.extras.targetNames; - console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' ); + if ( mesh.morphTargetInfluences.length === targetNames.length ) { + + mesh.morphTargetDictionary = {}; + + for ( let i = 0, il = targetNames.length; i < il; i ++ ) { + + mesh.morphTargetDictionary[ targetNames[ i ] ] = i; } + } else { + + console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' ); + } } - function createPrimitiveKey( primitiveDef ) { +} + +function createPrimitiveKey( primitiveDef ) { - var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]; - var geometryKey; + const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]; + let geometryKey; - if ( dracoExtension ) { + if ( dracoExtension ) { - geometryKey = 'draco:' + dracoExtension.bufferView + geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey( dracoExtension.attributes ); - } else { + } else { - geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode; + geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode; - } + } + + return geometryKey; - return geometryKey; +} + +function createAttributesKey( attributes ) { + + let attributesKey = ''; + + const keys = Object.keys( attributes ).sort(); + + for ( let i = 0, il = keys.length; i < il; i ++ ) { + + attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';'; } - function createAttributesKey( attributes ) { + return attributesKey; - var attributesKey = ''; +} - var keys = Object.keys( attributes ).sort(); +function getNormalizedComponentScale( constructor ) { - for ( var i = 0, il = keys.length; i < il; i ++ ) { + // Reference: + // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data - attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';'; + switch ( constructor ) { - } + case Int8Array: + return 1 / 127; - return attributesKey; + case Uint8Array: + return 1 / 255; + + case Int16Array: + return 1 / 32767; + + case Uint16Array: + return 1 / 65535; + + default: + throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' ); } - /* GLTF PARSER */ +} + +function getImageURIMimeType( uri ) { - function GLTFParser( json, options ) { + if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg'; + if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp'; - this.json = json || {}; + return 'image/png'; + +} + +/* GLTF PARSER */ + +class GLTFParser { + + constructor( json = {}, options = {} ) { + + this.json = json; this.extensions = {}; this.plugins = {}; - this.options = options || {}; + this.options = options; // loader object cache this.cache = new GLTFRegistry(); @@ -52438,19 +53643,27 @@ var GLTFLoader = ( function () { this.cameraCache = { refs: {}, uses: {} }; this.lightCache = { refs: {}, uses: {} }; + this.sourceCache = {}; + this.textureCache = {}; + // Track node names, to ensure no duplicates this.nodeNamesUsed = {}; // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the // expensive work of uploading a texture to the GPU off the main thread. - if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) { - this.textureLoader = new ImageBitmapLoader( this.options.manager ); + const isSafari = /^((?!chrome|android).)*safari/i.test( navigator.userAgent ) === true; + const isFirefox = navigator.userAgent.indexOf( 'Firefox' ) > - 1; + const firefoxVersion = isFirefox ? navigator.userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1; - } else { + if ( typeof createImageBitmap === 'undefined' || isSafari || ( isFirefox && firefoxVersion < 98 ) ) { this.textureLoader = new TextureLoader( this.options.manager ); + } else { + + this.textureLoader = new ImageBitmapLoader( this.options.manager ); + } this.textureLoader.setCrossOrigin( this.options.crossOrigin ); @@ -52467,23 +53680,23 @@ var GLTFLoader = ( function () { } - GLTFParser.prototype.setExtensions = function ( extensions ) { + setExtensions( extensions ) { this.extensions = extensions; - }; + } - GLTFParser.prototype.setPlugins = function ( plugins ) { + setPlugins( plugins ) { this.plugins = plugins; - }; + } - GLTFParser.prototype.parse = function ( onLoad, onError ) { + parse( onLoad, onError ) { - var parser = this; - var json = this.json; - var extensions = this.extensions; + const parser = this; + const json = this.json; + const extensions = this.extensions; // Clear the loader cache this.cache.removeAll(); @@ -52511,7 +53724,7 @@ var GLTFLoader = ( function () { } ).then( function ( dependencies ) { - var result = { + const result = { scene: dependencies[ 0 ][ json.scene || 0 ], scenes: dependencies[ 0 ], animations: dependencies[ 1 ], @@ -52537,24 +53750,24 @@ var GLTFLoader = ( function () { } ).catch( onError ); - }; + } /** * Marks the special nodes/meshes in json for efficient parse. */ - GLTFParser.prototype._markDefs = function () { + _markDefs() { - var nodeDefs = this.json.nodes || []; - var skinDefs = this.json.skins || []; - var meshDefs = this.json.meshes || []; + const nodeDefs = this.json.nodes || []; + const skinDefs = this.json.skins || []; + const meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a Bone or an // Object3D. Use the skins' joint references to mark bones. - for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { + for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { - var joints = skinDefs[ skinIndex ].joints; + const joints = skinDefs[ skinIndex ].joints; - for ( var i = 0, il = joints.length; i < il; i ++ ) { + for ( let i = 0, il = joints.length; i < il; i ++ ) { nodeDefs[ joints[ i ] ].isBone = true; @@ -52564,9 +53777,9 @@ var GLTFLoader = ( function () { // Iterate over all nodes, marking references to shared resources, // as well as skeleton joints. - for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { + for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { - var nodeDef = nodeDefs[ nodeIndex ]; + const nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.mesh !== undefined ) { @@ -52591,7 +53804,7 @@ var GLTFLoader = ( function () { } - }; + } /** * Counts references to shared node / Object3D resources. These resources @@ -52602,7 +53815,7 @@ var GLTFLoader = ( function () { * * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. */ - GLTFParser.prototype._addNodeRef = function ( cache, index ) { + _addNodeRef( cache, index ) { if ( index === undefined ) return; @@ -52614,46 +53827,69 @@ var GLTFLoader = ( function () { cache.refs[ index ] ++; - }; + } /** Returns a reference to a shared resource, cloning it if necessary. */ - GLTFParser.prototype._getNodeRef = function ( cache, index, object ) { + _getNodeRef( cache, index, object ) { if ( cache.refs[ index ] <= 1 ) return object; - var ref = object.clone(); + const ref = object.clone(); + + // Propagates mappings to the cloned object, prevents mappings on the + // original object from being lost. + const updateMappings = ( original, clone ) => { + + const mappings = this.associations.get( original ); + if ( mappings != null ) { + + this.associations.set( clone, mappings ); + + } + + for ( const [ i, child ] of original.children.entries() ) { + + updateMappings( child, clone.children[ i ] ); + + } + + }; + + updateMappings( object, ref ); ref.name += '_instance_' + ( cache.uses[ index ] ++ ); return ref; - }; + } - GLTFParser.prototype._invokeOne = function ( func ) { + _invokeOne( func ) { - var extensions = Object.values( this.plugins ); + const extensions = Object.values( this.plugins ); extensions.push( this ); - for ( var i = 0; i < extensions.length; i ++ ) { + for ( let i = 0; i < extensions.length; i ++ ) { - var result = func( extensions[ i ] ); + const result = func( extensions[ i ] ); if ( result ) return result; } - }; + return null; - GLTFParser.prototype._invokeAll = function ( func ) { + } - var extensions = Object.values( this.plugins ); + _invokeAll( func ) { + + const extensions = Object.values( this.plugins ); extensions.unshift( this ); - var pending = []; + const pending = []; - for ( var i = 0; i < extensions.length; i ++ ) { + for ( let i = 0; i < extensions.length; i ++ ) { - var result = func( extensions[ i ] ); + const result = func( extensions[ i ] ); if ( result ) pending.push( result ); @@ -52661,7 +53897,7 @@ var GLTFLoader = ( function () { return pending; - }; + } /** * Requests the specified dependency asynchronously, with caching. @@ -52669,10 +53905,10 @@ var GLTFLoader = ( function () { * @param {number} index * @return {Promise} */ - GLTFParser.prototype.getDependency = function ( type, index ) { + getDependency( type, index ) { - var cacheKey = type + ':' + index; - var dependency = this.cache.get( cacheKey ); + const cacheKey = type + ':' + index; + let dependency = this.cache.get( cacheKey ); if ( ! dependency ) { @@ -52731,7 +53967,11 @@ var GLTFLoader = ( function () { break; case 'animation': - dependency = this.loadAnimation( index ); + dependency = this._invokeOne( function ( ext ) { + + return ext.loadAnimation && ext.loadAnimation( index ); + + } ); break; case 'camera': @@ -52749,21 +53989,21 @@ var GLTFLoader = ( function () { return dependency; - }; + } /** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise>} */ - GLTFParser.prototype.getDependencies = function ( type ) { + getDependencies( type ) { - var dependencies = this.cache.get( type ); + let dependencies = this.cache.get( type ); if ( ! dependencies ) { - var parser = this; - var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || []; + const parser = this; + const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || []; dependencies = Promise.all( defs.map( function ( def, index ) { @@ -52777,17 +54017,17 @@ var GLTFLoader = ( function () { return dependencies; - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise} */ - GLTFParser.prototype.loadBuffer = function ( bufferIndex ) { + loadBuffer( bufferIndex ) { - var bufferDef = this.json.buffers[ bufferIndex ]; - var loader = this.fileLoader; + const bufferDef = this.json.buffers[ bufferIndex ]; + const loader = this.fileLoader; if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) { @@ -52802,11 +54042,11 @@ var GLTFLoader = ( function () { } - var options = this.options; + const options = this.options; return new Promise( function ( resolve, reject ) { - loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () { + loader.load( LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () { reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) ); @@ -52814,38 +54054,38 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise} */ - GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) { + loadBufferView( bufferViewIndex ) { - var bufferViewDef = this.json.bufferViews[ bufferViewIndex ]; + const bufferViewDef = this.json.bufferViews[ bufferViewIndex ]; return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) { - var byteLength = bufferViewDef.byteLength || 0; - var byteOffset = bufferViewDef.byteOffset || 0; + const byteLength = bufferViewDef.byteLength || 0; + const byteOffset = bufferViewDef.byteOffset || 0; return buffer.slice( byteOffset, byteOffset + byteLength ); } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise} */ - GLTFParser.prototype.loadAccessor = function ( accessorIndex ) { + loadAccessor( accessorIndex ) { - var parser = this; - var json = this.json; + const parser = this; + const json = this.json; - var accessorDef = this.json.accessors[ accessorIndex ]; + const accessorDef = this.json.accessors[ accessorIndex ]; if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) { @@ -52856,7 +54096,7 @@ var GLTFLoader = ( function () { } - var pendingBufferViews = []; + const pendingBufferViews = []; if ( accessorDef.bufferView !== undefined ) { @@ -52877,27 +54117,27 @@ var GLTFLoader = ( function () { return Promise.all( pendingBufferViews ).then( function ( bufferViews ) { - var bufferView = bufferViews[ 0 ]; + const bufferView = bufferViews[ 0 ]; - var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; - var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; + const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; + const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. - var elementBytes = TypedArray.BYTES_PER_ELEMENT; - var itemBytes = elementBytes * itemSize; - var byteOffset = accessorDef.byteOffset || 0; - var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined; - var normalized = accessorDef.normalized === true; - var array, bufferAttribute; + const elementBytes = TypedArray.BYTES_PER_ELEMENT; + const itemBytes = elementBytes * itemSize; + const byteOffset = accessorDef.byteOffset || 0; + const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined; + const normalized = accessorDef.normalized === true; + let array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes. if ( byteStride && byteStride !== itemBytes ) { // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer // This makes sure that IBA.count reflects accessor.count properly - var ibSlice = Math.floor( byteOffset / byteStride ); - var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; - var ib = parser.cache.get( ibCacheKey ); + const ibSlice = Math.floor( byteOffset / byteStride ); + const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; + let ib = parser.cache.get( ibCacheKey ); if ( ! ib ) { @@ -52931,14 +54171,14 @@ var GLTFLoader = ( function () { // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors if ( accessorDef.sparse !== undefined ) { - var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; - var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ]; + const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; + const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ]; - var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; - var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; + const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; + const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; - var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices ); - var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize ); + const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices ); + const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize ); if ( bufferView !== null ) { @@ -52947,9 +54187,9 @@ var GLTFLoader = ( function () { } - for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) { + for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) { - var index = sparseIndices[ i ]; + const index = sparseIndices[ i ]; bufferAttribute.setX( index, sparseValues[ i * itemSize ] ); if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] ); @@ -52965,98 +54205,139 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise} */ - GLTFParser.prototype.loadTexture = function ( textureIndex ) { + loadTexture( textureIndex ) { - var json = this.json; - var options = this.options; - var textureDef = json.textures[ textureIndex ]; - var source = json.images[ textureDef.source ]; + const json = this.json; + const options = this.options; + const textureDef = json.textures[ textureIndex ]; + const sourceIndex = textureDef.source; + const sourceDef = json.images[ sourceIndex ]; - var loader = this.textureLoader; + let loader = this.textureLoader; - if ( source.uri ) { + if ( sourceDef.uri ) { - var handler = options.manager.getHandler( source.uri ); + const handler = options.manager.getHandler( sourceDef.uri ); if ( handler !== null ) loader = handler; } - return this.loadTextureImage( textureIndex, source, loader ); + return this.loadTextureImage( textureIndex, sourceIndex, loader ); - }; + } - GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) { + loadTextureImage( textureIndex, sourceIndex, loader ) { - var parser = this; - var json = this.json; - var options = this.options; + const parser = this; + const json = this.json; - var textureDef = json.textures[ textureIndex ]; + const textureDef = json.textures[ textureIndex ]; + const sourceDef = json.images[ sourceIndex ]; - var URL = self.URL || self.webkitURL; + const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler; - var sourceURI = source.uri; - var isObjectURL = false; - var hasAlpha = true; + if ( this.textureCache[ cacheKey ] ) { - if ( source.mimeType === 'image/jpeg' ) hasAlpha = false; + // See https://github.com/mrdoob/three.js/issues/21559. + return this.textureCache[ cacheKey ]; - if ( source.bufferView !== undefined ) { + } - // Load binary image data from bufferView, if provided. + const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) { - sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) { + texture.flipY = false; - if ( source.mimeType === 'image/png' ) { + if ( textureDef.name ) texture.name = textureDef.name; - // Inspect the PNG 'IHDR' chunk to determine whether the image could have an - // alpha channel. This check is conservative — the image could have an alpha - // channel with all values == 1, and the indexed type (colorType == 3) only - // sometimes contains alpha. - // - // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header - var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false ); - hasAlpha = colorType === 6 || colorType === 4 || colorType === 3; + const samplers = json.samplers || {}; + const sampler = samplers[ textureDef.sampler ] || {}; - } + texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter; + texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping; + + parser.associations.set( texture, { textures: textureIndex } ); + + return texture; + + } ).catch( function () { + + return null; + + } ); + + this.textureCache[ cacheKey ] = promise; + + return promise; + + } + + loadImageSource( sourceIndex, loader ) { + + const parser = this; + const json = this.json; + const options = this.options; + + if ( this.sourceCache[ sourceIndex ] !== undefined ) { + + return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() ); + + } + + const sourceDef = json.images[ sourceIndex ]; + + const URL = self.URL || self.webkitURL; + + let sourceURI = sourceDef.uri || ''; + let isObjectURL = false; + + if ( sourceDef.bufferView !== undefined ) { + + // Load binary image data from bufferView, if provided. + + sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) { isObjectURL = true; - var blob = new Blob( [ bufferView ], { type: source.mimeType } ); + const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } ); sourceURI = URL.createObjectURL( blob ); return sourceURI; } ); - } else if ( source.uri === undefined ) { + } else if ( sourceDef.uri === undefined ) { - throw new Error( 'THREE.GLTFLoader: Image ' + textureIndex + ' is missing URI and bufferView' ); + throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' ); } - return Promise.resolve( sourceURI ).then( function ( sourceURI ) { + const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) { return new Promise( function ( resolve, reject ) { - var onLoad = resolve; + let onLoad = resolve; if ( loader.isImageBitmapLoader === true ) { onLoad = function ( imageBitmap ) { - resolve( new CanvasTexture( imageBitmap ) ); + const texture = new Texture( imageBitmap ); + texture.needsUpdate = true; + + resolve( texture ); }; } - loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject ); + loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject ); } ); @@ -53070,42 +54351,32 @@ var GLTFLoader = ( function () { } - texture.flipY = false; - - if ( textureDef.name ) texture.name = textureDef.name; - - // When there is definitely no alpha channel in the texture, set RGBFormat to save space. - if ( ! hasAlpha ) texture.format = RGBFormat; + texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri ); - var samplers = json.samplers || {}; - var sampler = samplers[ textureDef.sampler ] || {}; - - texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter; - texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter; - texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping; - texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping; + return texture; - parser.associations.set( texture, { - type: 'textures', - index: textureIndex - } ); + } ).catch( function ( error ) { - return texture; + console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI ); + throw error; } ); - }; + this.sourceCache[ sourceIndex ] = promise; + return promise; + + } /** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef - * @return {Promise} + * @return {Promise} */ - GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) { + assignTexture( materialParams, mapName, mapDef, encoding ) { - var parser = this; + const parser = this; return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) { @@ -53119,11 +54390,11 @@ var GLTFLoader = ( function () { if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) { - var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; + const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; if ( transform ) { - var gltfReference = parser.associations.get( texture ); + const gltfReference = parser.associations.get( texture ); texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform ); parser.associations.set( texture, gltfReference ); @@ -53131,11 +54402,19 @@ var GLTFLoader = ( function () { } + if ( encoding !== undefined ) { + + texture.encoding = encoding; + + } + materialParams[ mapName ] = texture; + return texture; + } ); - }; + } /** * Assigns final material to a Mesh, Line, or Points instance. The instance @@ -53145,23 +54424,20 @@ var GLTFLoader = ( function () { * be created if necessary, and reused from a cache. * @param {Object3D} mesh Mesh, Line, or Points instance. */ - GLTFParser.prototype.assignFinalMaterial = function ( mesh ) { + assignFinalMaterial( mesh ) { - var geometry = mesh.geometry; - var material = mesh.material; + const geometry = mesh.geometry; + let material = mesh.material; - var useVertexTangents = geometry.attributes.tangent !== undefined; - var useVertexColors = geometry.attributes.color !== undefined; - var useFlatShading = geometry.attributes.normal === undefined; - var useSkinning = mesh.isSkinnedMesh === true; - var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0; - var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined; + const useDerivativeTangents = geometry.attributes.tangent === undefined; + const useVertexColors = geometry.attributes.color !== undefined; + const useFlatShading = geometry.attributes.normal === undefined; if ( mesh.isPoints ) { - var cacheKey = 'PointsMaterial:' + material.uuid; + const cacheKey = 'PointsMaterial:' + material.uuid; - var pointsMaterial = this.cache.get( cacheKey ); + let pointsMaterial = this.cache.get( cacheKey ); if ( ! pointsMaterial ) { @@ -53179,9 +54455,9 @@ var GLTFLoader = ( function () { } else if ( mesh.isLine ) { - var cacheKey = 'LineBasicMaterial:' + material.uuid; + const cacheKey = 'LineBasicMaterial:' + material.uuid; - var lineMaterial = this.cache.get( cacheKey ); + let lineMaterial = this.cache.get( cacheKey ); if ( ! lineMaterial ) { @@ -53198,33 +54474,25 @@ var GLTFLoader = ( function () { } // Clone the material if it will be modified - if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) { + if ( useDerivativeTangents || useVertexColors || useFlatShading ) { - var cacheKey = 'ClonedMaterial:' + material.uuid + ':'; + let cacheKey = 'ClonedMaterial:' + material.uuid + ':'; if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:'; - if ( useSkinning ) cacheKey += 'skinning:'; - if ( useVertexTangents ) cacheKey += 'vertex-tangents:'; + if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:'; if ( useVertexColors ) cacheKey += 'vertex-colors:'; if ( useFlatShading ) cacheKey += 'flat-shading:'; - if ( useMorphTargets ) cacheKey += 'morph-targets:'; - if ( useMorphNormals ) cacheKey += 'morph-normals:'; - var cachedMaterial = this.cache.get( cacheKey ); + let cachedMaterial = this.cache.get( cacheKey ); if ( ! cachedMaterial ) { cachedMaterial = material.clone(); - if ( useSkinning ) cachedMaterial.skinning = true; if ( useVertexColors ) cachedMaterial.vertexColors = true; if ( useFlatShading ) cachedMaterial.flatShading = true; - if ( useMorphTargets ) cachedMaterial.morphTargets = true; - if ( useMorphNormals ) cachedMaterial.morphNormals = true; - - if ( useVertexTangents ) { - cachedMaterial.vertexTangents = true; + if ( useDerivativeTangents ) { // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1; @@ -53252,41 +54520,41 @@ var GLTFLoader = ( function () { mesh.material = material; - }; + } - GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) { + getMaterialType( /* materialIndex */ ) { return MeshStandardMaterial; - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise} */ - GLTFParser.prototype.loadMaterial = function ( materialIndex ) { + loadMaterial( materialIndex ) { - var parser = this; - var json = this.json; - var extensions = this.extensions; - var materialDef = json.materials[ materialIndex ]; + const parser = this; + const json = this.json; + const extensions = this.extensions; + const materialDef = json.materials[ materialIndex ]; - var materialType; - var materialParams = {}; - var materialExtensions = materialDef.extensions || {}; + let materialType; + const materialParams = {}; + const materialExtensions = materialDef.extensions || {}; - var pending = []; + const pending = []; if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) { - var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ]; + const sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ]; materialType = sgExtension.getMaterialType(); pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) ); } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) { - var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ]; + const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ]; materialType = kmuExtension.getMaterialType(); pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) ); @@ -53295,14 +54563,14 @@ var GLTFLoader = ( function () { // Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material - var metallicRoughness = materialDef.pbrMetallicRoughness || {}; + const metallicRoughness = materialDef.pbrMetallicRoughness || {}; materialParams.color = new Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { - var array = metallicRoughness.baseColorFactor; + const array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; @@ -53311,7 +54579,7 @@ var GLTFLoader = ( function () { if ( metallicRoughness.baseColorTexture !== undefined ) { - pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); + pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding ) ); } @@ -53345,7 +54613,7 @@ var GLTFLoader = ( function () { } - var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; + const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; if ( alphaMode === ALPHA_MODES.BLEND ) { @@ -53370,12 +54638,13 @@ var GLTFLoader = ( function () { pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) ); - // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 - materialParams.normalScale = new Vector2( 1, - 1 ); + materialParams.normalScale = new Vector2( 1, 1 ); if ( materialDef.normalTexture.scale !== undefined ) { - materialParams.normalScale.set( materialDef.normalTexture.scale, - materialDef.normalTexture.scale ); + const scale = materialDef.normalTexture.scale; + + materialParams.normalScale.set( scale, scale ); } @@ -53401,13 +54670,13 @@ var GLTFLoader = ( function () { if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) { - pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) ); + pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, sRGBEncoding ) ); } return Promise.all( pending ).then( function () { - var material; + let material; if ( materialType === GLTFMeshStandardSGMaterial ) { @@ -53421,13 +54690,9 @@ var GLTFLoader = ( function () { if ( materialDef.name ) material.name = materialDef.name; - // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. - if ( material.map ) material.map.encoding = sRGBEncoding; - if ( material.emissiveMap ) material.emissiveMap.encoding = sRGBEncoding; - assignExtrasToUserData( material, materialDef ); - parser.associations.set( material, { type: 'materials', index: materialIndex } ); + parser.associations.set( material, { materials: materialIndex } ); if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef ); @@ -53435,16 +54700,16 @@ var GLTFLoader = ( function () { } ); - }; + } /** When Object3D instances are targeted by animation, they need unique names. */ - GLTFParser.prototype.createUniqueName = function ( originalName ) { + createUniqueName( originalName ) { - var sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' ); + const sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' ); - var name = sanitizedName; + let name = sanitizedName; - for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) { + for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) { name = sanitizedName + '_' + i; @@ -53454,258 +54719,6 @@ var GLTFLoader = ( function () { return name; - }; - - /** - * @param {BufferGeometry} geometry - * @param {GLTF.Primitive} primitiveDef - * @param {GLTFParser} parser - */ - function computeBounds( geometry, primitiveDef, parser ) { - - var attributes = primitiveDef.attributes; - - var box = new Box3(); - - if ( attributes.POSITION !== undefined ) { - - var accessor = parser.json.accessors[ attributes.POSITION ]; - - var min = accessor.min; - var max = accessor.max; - - // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. - - if ( min !== undefined && max !== undefined ) { - - box.set( - new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ), - new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) ); - - } else { - - console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); - - return; - - } - - } else { - - return; - - } - - var targets = primitiveDef.targets; - - if ( targets !== undefined ) { - - var maxDisplacement = new Vector3(); - var vector = new Vector3(); - - for ( var i = 0, il = targets.length; i < il; i ++ ) { - - var target = targets[ i ]; - - if ( target.POSITION !== undefined ) { - - var accessor = parser.json.accessors[ target.POSITION ]; - var min = accessor.min; - var max = accessor.max; - - // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. - - if ( min !== undefined && max !== undefined ) { - - // we need to get max of absolute components because target weight is [-1,1] - vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) ); - vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) ); - vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) ); - - // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative - // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets - // are used to implement key-frame animations and as such only two are active at a time - this results in very large - // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size. - maxDisplacement.max( vector ); - - } else { - - console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); - - } - - } - - } - - // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets. - box.expandByVector( maxDisplacement ); - - } - - geometry.boundingBox = box; - - var sphere = new Sphere(); - - box.getCenter( sphere.center ); - sphere.radius = box.min.distanceTo( box.max ) / 2; - - geometry.boundingSphere = sphere; - - } - - /** - * @param {BufferGeometry} geometry - * @param {GLTF.Primitive} primitiveDef - * @param {GLTFParser} parser - * @return {Promise} - */ - function addPrimitiveAttributes( geometry, primitiveDef, parser ) { - - var attributes = primitiveDef.attributes; - - var pending = []; - - function assignAttributeAccessor( accessorIndex, attributeName ) { - - return parser.getDependency( 'accessor', accessorIndex ) - .then( function ( accessor ) { - - geometry.setAttribute( attributeName, accessor ); - - } ); - - } - - for ( var gltfAttributeName in attributes ) { - - var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); - - // Skip attributes already provided by e.g. Draco extension. - if ( threeAttributeName in geometry.attributes ) continue; - - pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) ); - - } - - if ( primitiveDef.indices !== undefined && ! geometry.index ) { - - var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) { - - geometry.setIndex( accessor ); - - } ); - - pending.push( accessor ); - - } - - assignExtrasToUserData( geometry, primitiveDef ); - - computeBounds( geometry, primitiveDef, parser ); - - return Promise.all( pending ).then( function () { - - return primitiveDef.targets !== undefined - ? addMorphTargets( geometry, primitiveDef.targets, parser ) - : geometry; - - } ); - - } - - /** - * @param {BufferGeometry} geometry - * @param {Number} drawMode - * @return {BufferGeometry} - */ - function toTrianglesDrawMode( geometry, drawMode ) { - - var index = geometry.getIndex(); - - // generate index if not present - - if ( index === null ) { - - var indices = []; - - var position = geometry.getAttribute( 'position' ); - - if ( position !== undefined ) { - - for ( var i = 0; i < position.count; i ++ ) { - - indices.push( i ); - - } - - geometry.setIndex( indices ); - index = geometry.getIndex(); - - } else { - - console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); - return geometry; - - } - - } - - // - - var numberOfTriangles = index.count - 2; - var newIndices = []; - - if ( drawMode === TriangleFanDrawMode ) { - - // gl.TRIANGLE_FAN - - for ( var i = 1; i <= numberOfTriangles; i ++ ) { - - newIndices.push( index.getX( 0 ) ); - newIndices.push( index.getX( i ) ); - newIndices.push( index.getX( i + 1 ) ); - - } - - } else { - - // gl.TRIANGLE_STRIP - - for ( var i = 0; i < numberOfTriangles; i ++ ) { - - if ( i % 2 === 0 ) { - - newIndices.push( index.getX( i ) ); - newIndices.push( index.getX( i + 1 ) ); - newIndices.push( index.getX( i + 2 ) ); - - - } else { - - newIndices.push( index.getX( i + 2 ) ); - newIndices.push( index.getX( i + 1 ) ); - newIndices.push( index.getX( i ) ); - - } - - } - - } - - if ( ( newIndices.length / 3 ) !== numberOfTriangles ) { - - console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' ); - - } - - // build final geometry - - var newGeometry = geometry.clone(); - newGeometry.setIndex( newIndices ); - - return newGeometry; - } /** @@ -53716,11 +54729,11 @@ var GLTFLoader = ( function () { * @param {Array} primitives * @return {Promise>} */ - GLTFParser.prototype.loadGeometries = function ( primitives ) { + loadGeometries( primitives ) { - var parser = this; - var extensions = this.extensions; - var cache = this.primitiveCache; + const parser = this; + const extensions = this.extensions; + const cache = this.primitiveCache; function createDracoPrimitive( primitive ) { @@ -53734,15 +54747,15 @@ var GLTFLoader = ( function () { } - var pending = []; + const pending = []; - for ( var i = 0, il = primitives.length; i < il; i ++ ) { + for ( let i = 0, il = primitives.length; i < il; i ++ ) { - var primitive = primitives[ i ]; - var cacheKey = createPrimitiveKey( primitive ); + const primitive = primitives[ i ]; + const cacheKey = createPrimitiveKey( primitive ); // See if we've already created this geometry - var cached = cache[ cacheKey ]; + const cached = cache[ cacheKey ]; if ( cached ) { @@ -53751,7 +54764,7 @@ var GLTFLoader = ( function () { } else { - var geometryPromise; + let geometryPromise; if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) { @@ -53776,27 +54789,27 @@ var GLTFLoader = ( function () { return Promise.all( pending ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex * @return {Promise} */ - GLTFParser.prototype.loadMesh = function ( meshIndex ) { + loadMesh( meshIndex ) { - var parser = this; - var json = this.json; - var extensions = this.extensions; + const parser = this; + const json = this.json; + const extensions = this.extensions; - var meshDef = json.meshes[ meshIndex ]; - var primitives = meshDef.primitives; + const meshDef = json.meshes[ meshIndex ]; + const primitives = meshDef.primitives; - var pending = []; + const pending = []; - for ( var i = 0, il = primitives.length; i < il; i ++ ) { + for ( let i = 0, il = primitives.length; i < il; i ++ ) { - var material = primitives[ i ].material === undefined + const material = primitives[ i ].material === undefined ? createDefaultMaterial( this.cache ) : this.getDependency( 'material', primitives[ i ].material ); @@ -53808,26 +54821,26 @@ var GLTFLoader = ( function () { return Promise.all( pending ).then( function ( results ) { - var materials = results.slice( 0, results.length - 1 ); - var geometries = results[ results.length - 1 ]; + const materials = results.slice( 0, results.length - 1 ); + const geometries = results[ results.length - 1 ]; - var meshes = []; + const meshes = []; - for ( var i = 0, il = geometries.length; i < il; i ++ ) { + for ( let i = 0, il = geometries.length; i < il; i ++ ) { - var geometry = geometries[ i ]; - var primitive = primitives[ i ]; + const geometry = geometries[ i ]; + const primitive = primitives[ i ]; // 1. create Mesh - var mesh; + let mesh; - var material = materials[ i ]; + const material = materials[ i ]; if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || - primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || - primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || - primitive.mode === undefined ) { + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || + primitive.mode === undefined ) { // .isSkinnedMesh isn't in glTF spec. See ._markDefs() mesh = meshDef.isSkinnedMesh === true @@ -53892,15 +54905,26 @@ var GLTFLoader = ( function () { } + for ( let i = 0, il = meshes.length; i < il; i ++ ) { + + parser.associations.set( meshes[ i ], { + meshes: meshIndex, + primitives: i + } ); + + } + if ( meshes.length === 1 ) { return meshes[ 0 ]; } - var group = new Group(); + const group = new Group(); - for ( var i = 0, il = meshes.length; i < il; i ++ ) { + parser.associations.set( group, { meshes: meshIndex } ); + + for ( let i = 0, il = meshes.length; i < il; i ++ ) { group.add( meshes[ i ] ); @@ -53910,18 +54934,18 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @param {number} cameraIndex * @return {Promise} */ - GLTFParser.prototype.loadCamera = function ( cameraIndex ) { + loadCamera( cameraIndex ) { - var camera; - var cameraDef = this.json.cameras[ cameraIndex ]; - var params = cameraDef[ cameraDef.type ]; + let camera; + const cameraDef = this.json.cameras[ cameraIndex ]; + const params = cameraDef[ cameraDef.type ]; if ( ! params ) { @@ -53946,18 +54970,18 @@ var GLTFLoader = ( function () { return Promise.resolve( camera ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise} */ - GLTFParser.prototype.loadSkin = function ( skinIndex ) { + loadSkin( skinIndex ) { - var skinDef = this.json.skins[ skinIndex ]; + const skinDef = this.json.skins[ skinIndex ]; - var skinEntry = { joints: skinDef.joints }; + const skinEntry = { joints: skinDef.joints }; if ( skinDef.inverseBindMatrices === undefined ) { @@ -53973,33 +54997,33 @@ var GLTFLoader = ( function () { } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise} */ - GLTFParser.prototype.loadAnimation = function ( animationIndex ) { + loadAnimation( animationIndex ) { - var json = this.json; + const json = this.json; - var animationDef = json.animations[ animationIndex ]; + const animationDef = json.animations[ animationIndex ]; - var pendingNodes = []; - var pendingInputAccessors = []; - var pendingOutputAccessors = []; - var pendingSamplers = []; - var pendingTargets = []; + const pendingNodes = []; + const pendingInputAccessors = []; + const pendingOutputAccessors = []; + const pendingSamplers = []; + const pendingTargets = []; - for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) { + for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) { - var channel = animationDef.channels[ i ]; - var sampler = animationDef.samplers[ channel.sampler ]; - var target = channel.target; - var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated. - var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input; - var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output; + const channel = animationDef.channels[ i ]; + const sampler = animationDef.samplers[ channel.sampler ]; + const target = channel.target; + const name = target.node; + const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input; + const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output; pendingNodes.push( this.getDependency( 'node', name ) ); pendingInputAccessors.push( this.getDependency( 'accessor', input ) ); @@ -54019,28 +55043,27 @@ var GLTFLoader = ( function () { ] ).then( function ( dependencies ) { - var nodes = dependencies[ 0 ]; - var inputAccessors = dependencies[ 1 ]; - var outputAccessors = dependencies[ 2 ]; - var samplers = dependencies[ 3 ]; - var targets = dependencies[ 4 ]; + const nodes = dependencies[ 0 ]; + const inputAccessors = dependencies[ 1 ]; + const outputAccessors = dependencies[ 2 ]; + const samplers = dependencies[ 3 ]; + const targets = dependencies[ 4 ]; - var tracks = []; + const tracks = []; - for ( var i = 0, il = nodes.length; i < il; i ++ ) { + for ( let i = 0, il = nodes.length; i < il; i ++ ) { - var node = nodes[ i ]; - var inputAccessor = inputAccessors[ i ]; - var outputAccessor = outputAccessors[ i ]; - var sampler = samplers[ i ]; - var target = targets[ i ]; + const node = nodes[ i ]; + const inputAccessor = inputAccessors[ i ]; + const outputAccessor = outputAccessors[ i ]; + const sampler = samplers[ i ]; + const target = targets[ i ]; if ( node === undefined ) continue; node.updateMatrix(); - node.matrixAutoUpdate = true; - var TypedKeyframeTrack; + let TypedKeyframeTrack; switch ( PATH_PROPERTIES[ target.path ] ) { @@ -54063,18 +55086,17 @@ var GLTFLoader = ( function () { } - var targetName = node.name ? node.name : node.uuid; + const targetName = node.name ? node.name : node.uuid; - var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear; + const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear; - var targetNames = []; + const targetNames = []; if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) { - // Node may be a Group (glTF mesh with several primitives) or a Mesh. node.traverse( function ( object ) { - if ( object.isMesh === true && object.morphTargetInfluences ) { + if ( object.morphTargetInfluences ) { targetNames.push( object.name ? object.name : object.uuid ); @@ -54088,37 +55110,14 @@ var GLTFLoader = ( function () { } - var outputArray = outputAccessor.array; + let outputArray = outputAccessor.array; if ( outputAccessor.normalized ) { - var scale; - - if ( outputArray.constructor === Int8Array ) { - - scale = 1 / 127; - - } else if ( outputArray.constructor === Uint8Array ) { + const scale = getNormalizedComponentScale( outputArray.constructor ); + const scaled = new Float32Array( outputArray.length ); - scale = 1 / 255; - - } else if ( outputArray.constructor == Int16Array ) { - - scale = 1 / 32767; - - } else if ( outputArray.constructor === Uint16Array ) { - - scale = 1 / 65535; - - } else { - - throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' ); - - } - - var scaled = new Float32Array( outputArray.length ); - - for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) { + for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) { scaled[ j ] = outputArray[ j ] * scale; @@ -54128,9 +55127,9 @@ var GLTFLoader = ( function () { } - for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) { + for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) { - var track = new TypedKeyframeTrack( + const track = new TypedKeyframeTrack( targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ], inputAccessor.array, outputArray, @@ -54146,7 +55145,9 @@ var GLTFLoader = ( function () { // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize() // must be divided by three to get the interpolant's sampleSize argument. - return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result ); + const interpolantType = ( this instanceof QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; + + return new interpolantType( this.times, this.values, this.getValueSize() / 3, result ); }; @@ -54161,60 +55162,78 @@ var GLTFLoader = ( function () { } - var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex; + const name = animationDef.name ? animationDef.name : 'animation_' + animationIndex; return new AnimationClip( name, undefined, tracks ); } ); - }; + } - /** - * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy - * @param {number} nodeIndex - * @return {Promise} - */ - GLTFParser.prototype.loadNode = function ( nodeIndex ) { + createNodeMesh( nodeIndex ) { - var json = this.json; - var extensions = this.extensions; - var parser = this; + const json = this.json; + const parser = this; + const nodeDef = json.nodes[ nodeIndex ]; - var nodeDef = json.nodes[ nodeIndex ]; + if ( nodeDef.mesh === undefined ) return null; - // reserve node's name before its dependencies, so the root has the intended name. - var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : ''; + return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) { - return ( function () { + const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh ); - var pending = []; + // if weights are provided on the node, override weights on the mesh. + if ( nodeDef.weights !== undefined ) { - if ( nodeDef.mesh !== undefined ) { + node.traverse( function ( o ) { - pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) { + if ( ! o.isMesh ) return; - var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh ); + for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) { - // if weights are provided on the node, override weights on the mesh. - if ( nodeDef.weights !== undefined ) { + o.morphTargetInfluences[ i ] = nodeDef.weights[ i ]; - node.traverse( function ( o ) { + } - if ( ! o.isMesh ) return; + } ); - for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) { + } - o.morphTargetInfluences[ i ] = nodeDef.weights[ i ]; + return node; - } + } ); - } ); + } - } + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy + * @param {number} nodeIndex + * @return {Promise} + */ + loadNode( nodeIndex ) { - return node; + const json = this.json; + const extensions = this.extensions; + const parser = this; - } ) ); + const nodeDef = json.nodes[ nodeIndex ]; + + // reserve node's name before its dependencies, so the root has the intended name. + const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : ''; + + return ( function () { + + const pending = []; + + const meshPromise = parser._invokeOne( function ( ext ) { + + return ext.createNodeMesh && ext.createNodeMesh( nodeIndex ); + + } ); + + if ( meshPromise ) { + + pending.push( meshPromise ); } @@ -54242,7 +55261,7 @@ var GLTFLoader = ( function () { }() ).then( function ( objects ) { - var node; + let node; // .isBone isn't in glTF spec. See ._markDefs if ( nodeDef.isBone === true ) { @@ -54265,7 +55284,7 @@ var GLTFLoader = ( function () { if ( node !== objects[ 0 ] ) { - for ( var i = 0, il = objects.length; i < il; i ++ ) { + for ( let i = 0, il = objects.length; i < il; i ++ ) { node.add( objects[ i ] ); @@ -54286,7 +55305,7 @@ var GLTFLoader = ( function () { if ( nodeDef.matrix !== undefined ) { - var matrix = new Matrix4(); + const matrix = new Matrix4(); matrix.fromArray( nodeDef.matrix ); node.applyMatrix4( matrix ); @@ -54312,158 +55331,459 @@ var GLTFLoader = ( function () { } - parser.associations.set( node, { type: 'nodes', index: nodeIndex } ); + if ( ! parser.associations.has( node ) ) { + + parser.associations.set( node, {} ); + + } + + parser.associations.get( node ).nodes = nodeIndex; return node; } ); - }; + } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex * @return {Promise} */ - GLTFParser.prototype.loadScene = function () { + loadScene( sceneIndex ) { + + const json = this.json; + const extensions = this.extensions; + const sceneDef = this.json.scenes[ sceneIndex ]; + const parser = this; - // scene node hierachy builder + // Loader returns Group, not Scene. + // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172 + const scene = new Group(); + if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name ); - function buildNodeHierachy( nodeId, parentObject, json, parser ) { + assignExtrasToUserData( scene, sceneDef ); - var nodeDef = json.nodes[ nodeId ]; + if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef ); - return parser.getDependency( 'node', nodeId ).then( function ( node ) { + const nodeIds = sceneDef.nodes || []; - if ( nodeDef.skin === undefined ) return node; + const pending = []; - // build skeleton here as well + for ( let i = 0, il = nodeIds.length; i < il; i ++ ) { - var skinEntry; + pending.push( buildNodeHierarchy( nodeIds[ i ], scene, json, parser ) ); + + } + + return Promise.all( pending ).then( function () { - return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) { + // Removes dangling associations, associations that reference a node that + // didn't make it into the scene. + const reduceAssociations = ( node ) => { - skinEntry = skin; + const reducedAssociations = new Map(); - var pendingJoints = []; + for ( const [ key, value ] of parser.associations ) { - for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) { + if ( key instanceof Material || key instanceof Texture ) { - pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) ); + reducedAssociations.set( key, value ); } - return Promise.all( pendingJoints ); + } - } ).then( function ( jointNodes ) { + node.traverse( ( node ) => { - node.traverse( function ( mesh ) { + const mappings = parser.associations.get( node ); - if ( ! mesh.isMesh ) return; + if ( mappings != null ) { - var bones = []; - var boneInverses = []; + reducedAssociations.set( node, mappings ); - for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) { + } - var jointNode = jointNodes[ j ]; + } ); - if ( jointNode ) { + return reducedAssociations; - bones.push( jointNode ); + }; - var mat = new Matrix4(); + parser.associations = reduceAssociations( scene ); - if ( skinEntry.inverseBindMatrices !== undefined ) { + return scene; - mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 ); + } ); - } + } - boneInverses.push( mat ); +} - } else { +function buildNodeHierarchy( nodeId, parentObject, json, parser ) { - console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] ); + const nodeDef = json.nodes[ nodeId ]; - } + return parser.getDependency( 'node', nodeId ).then( function ( node ) { - } + if ( nodeDef.skin === undefined ) return node; - mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld ); + // build skeleton here as well - } ); + let skinEntry; - return node; + return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) { - } ); + skinEntry = skin; + + const pendingJoints = []; + + for ( let i = 0, il = skinEntry.joints.length; i < il; i ++ ) { + + pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) ); + + } + + return Promise.all( pendingJoints ); + + } ).then( function ( jointNodes ) { + + node.traverse( function ( mesh ) { + + if ( ! mesh.isMesh ) return; + + const bones = []; + const boneInverses = []; + + for ( let j = 0, jl = jointNodes.length; j < jl; j ++ ) { - } ).then( function ( node ) { + const jointNode = jointNodes[ j ]; - // build node hierachy + if ( jointNode ) { - parentObject.add( node ); + bones.push( jointNode ); - var pending = []; + const mat = new Matrix4(); - if ( nodeDef.children ) { + if ( skinEntry.inverseBindMatrices !== undefined ) { - var children = nodeDef.children; + mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 ); - for ( var i = 0, il = children.length; i < il; i ++ ) { + } + + boneInverses.push( mat ); - var child = children[ i ]; - pending.push( buildNodeHierachy( child, node, json, parser ) ); + } else { + + console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] ); } } - return Promise.all( pending ); + mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld ); } ); + return node; + + } ); + + } ).then( function ( node ) { + + // build node hierachy + + parentObject.add( node ); + + const pending = []; + + if ( nodeDef.children ) { + + const children = nodeDef.children; + + for ( let i = 0, il = children.length; i < il; i ++ ) { + + const child = children[ i ]; + pending.push( buildNodeHierarchy( child, node, json, parser ) ); + + } + + } + + return Promise.all( pending ); + + } ); + +} + +/** + * @param {BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + */ +function computeBounds( geometry, primitiveDef, parser ) { + + const attributes = primitiveDef.attributes; + + const box = new Box3(); + + if ( attributes.POSITION !== undefined ) { + + const accessor = parser.json.accessors[ attributes.POSITION ]; + + const min = accessor.min; + const max = accessor.max; + + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. + + if ( min !== undefined && max !== undefined ) { + + box.set( + new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ), + new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) + ); + + if ( accessor.normalized ) { + + const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] ); + box.min.multiplyScalar( boxScale ); + box.max.multiplyScalar( boxScale ); + + } + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + return; + } - return function loadScene( sceneIndex ) { + } else { + + return; + + } + + const targets = primitiveDef.targets; + + if ( targets !== undefined ) { + + const maxDisplacement = new Vector3(); + const vector = new Vector3(); - var json = this.json; - var extensions = this.extensions; - var sceneDef = this.json.scenes[ sceneIndex ]; - var parser = this; + for ( let i = 0, il = targets.length; i < il; i ++ ) { - // Loader returns Group, not Scene. - // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172 - var scene = new Group(); - if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name ); + const target = targets[ i ]; - assignExtrasToUserData( scene, sceneDef ); + if ( target.POSITION !== undefined ) { - if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef ); + const accessor = parser.json.accessors[ target.POSITION ]; + const min = accessor.min; + const max = accessor.max; - var nodeIds = sceneDef.nodes || []; + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. - var pending = []; + if ( min !== undefined && max !== undefined ) { - for ( var i = 0, il = nodeIds.length; i < il; i ++ ) { + // we need to get max of absolute components because target weight is [-1,1] + vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) ); + vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) ); + vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) ); - pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) ); + + if ( accessor.normalized ) { + + const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] ); + vector.multiplyScalar( boxScale ); + + } + + // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative + // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets + // are used to implement key-frame animations and as such only two are active at a time - this results in very large + // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size. + maxDisplacement.max( vector ); + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + } } - return Promise.all( pending ).then( function () { + } - return scene; + // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets. + box.expandByVector( maxDisplacement ); + + } + + geometry.boundingBox = box; + + const sphere = new Sphere(); + + box.getCenter( sphere.center ); + sphere.radius = box.min.distanceTo( box.max ) / 2; + + geometry.boundingSphere = sphere; + +} + +/** + * @param {BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + * @return {Promise} + */ +function addPrimitiveAttributes( geometry, primitiveDef, parser ) { + + const attributes = primitiveDef.attributes; + + const pending = []; + + function assignAttributeAccessor( accessorIndex, attributeName ) { + + return parser.getDependency( 'accessor', accessorIndex ) + .then( function ( accessor ) { + + geometry.setAttribute( attributeName, accessor ); } ); - }; + } + + for ( const gltfAttributeName in attributes ) { + + const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); + + // Skip attributes already provided by e.g. Draco extension. + if ( threeAttributeName in geometry.attributes ) continue; + + pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) ); + + } + + if ( primitiveDef.indices !== undefined && ! geometry.index ) { + + const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) { + + geometry.setIndex( accessor ); + + } ); + + pending.push( accessor ); + + } + + assignExtrasToUserData( geometry, primitiveDef ); + + computeBounds( geometry, primitiveDef, parser ); - }(); + return Promise.all( pending ).then( function () { - return GLTFLoader; + return primitiveDef.targets !== undefined + ? addMorphTargets( geometry, primitiveDef.targets, parser ) + : geometry; -} )(); + } ); + +} + +/** + * @param {BufferGeometry} geometry + * @param {Number} drawMode + * @return {BufferGeometry} + */ +function toTrianglesDrawMode( geometry, drawMode ) { + + let index = geometry.getIndex(); + + // generate index if not present + + if ( index === null ) { + + const indices = []; + + const position = geometry.getAttribute( 'position' ); + + if ( position !== undefined ) { + + for ( let i = 0; i < position.count; i ++ ) { + + indices.push( i ); + + } + + geometry.setIndex( indices ); + index = geometry.getIndex(); + + } else { + + console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); + return geometry; + + } + + } + + // + + const numberOfTriangles = index.count - 2; + const newIndices = []; + + if ( drawMode === TriangleFanDrawMode ) { + + // gl.TRIANGLE_FAN + + for ( let i = 1; i <= numberOfTriangles; i ++ ) { + + newIndices.push( index.getX( 0 ) ); + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + + } + + } else { + + // gl.TRIANGLE_STRIP + + for ( let i = 0; i < numberOfTriangles; i ++ ) { + + if ( i % 2 === 0 ) { + + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i + 2 ) ); + + + } else { + + newIndices.push( index.getX( i + 2 ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i ) ); + + } + + } + + } + + if ( ( newIndices.length / 3 ) !== numberOfTriangles ) { + + console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' ); + + } + + // build final geometry + + const newGeometry = geometry.clone(); + newGeometry.setIndex( newIndices ); + + return newGeometry; + +} class ThreeJSWrapper { constructor(canvas) { From 54785cb36cb5a9eac0cc12cea989dfc5503cfed4 Mon Sep 17 00:00:00 2001 From: lostways Date: Sun, 11 Sep 2022 18:26:04 -0700 Subject: [PATCH 2/2] fixed teapot geometry --- examples/entities/UtahTeapot.js | 136 +-- examples/geometries/TeapotGeometry.js | 1152 ++++++++++++------------- 2 files changed, 634 insertions(+), 654 deletions(-) mode change 100644 => 100755 examples/geometries/TeapotGeometry.js diff --git a/examples/entities/UtahTeapot.js b/examples/entities/UtahTeapot.js index 057f253..fea38cf 100644 --- a/examples/entities/UtahTeapot.js +++ b/examples/entities/UtahTeapot.js @@ -4,71 +4,71 @@ import { TeapotGeometry } from '../geometries/TeapotGeometry.js'; //Utah Teapot export default class UtahTeapot extends ThreeJSEntity { - create() { - const { - x = 0, - y = 0, - z = 0, - size = 25, - segments = -1, - bottom = true, - lid = true, - body = true, - fitLid = false, - blinn = true, - shading = "smooth", - } = this.params; - - - const diffuseColor = new this.THREE.Color(); - const specularColor = new this.THREE.Color(); - const materialColor = new this.THREE.Color(); - - materialColor.setRGB( 1.0, 1.0, 1.0 ); - - let wireMaterial = new this.THREE.MeshBasicMaterial( { wireframe: true, color: 0xCC0000 } ); - let flatMaterial = new this.THREE.MeshPhongMaterial( { color: materialColor, specular: 0x000000, flatShading: true, side: this.THREE.DoubleSide } ); - let phongMaterial = new this.THREE.MeshPhongMaterial( { color: materialColor, side: this.THREE.DoubleSide } ); - let gouraudMaterial = new this.THREE.MeshLambertMaterial( { color: materialColor, side: this.THREE.DoubleSide } ); - - diffuseColor.setHSL(0.121,0.73,0.66); - specularColor.setRGB( 1, 1, 1); - - phongMaterial.shininess = 40; - phongMaterial.specular.copy(diffuseColor); - - phongMaterial.color.copy(diffuseColor); - flatMaterial.color.copy(diffuseColor); - gouraudMaterial.color.copy(diffuseColor); - - let shadingMap = { - wireframe: wireMaterial, - flat: flatMaterial, - smooth: gouraudMaterial, - glossy: phongMaterial, - }; - - - let geo = new TeapotGeometry( - size, - segments, - bottom, - lid, - body, - fitLid, - blinn); - - - let obj3d = new this.THREE.Mesh(geo,shadingMap[shading]); - - obj3d.position.z = z; - obj3d.position.y = y; - obj3d.position.x = x; - - return obj3d; - } - - update (event) { - event.target.rotation.y -= .005; - } - }; + create() { + const { + x = 0, + y = 0, + z = 0, + size = 25, + segments = -1, + bottom = true, + lid = true, + body = true, + fitLid = false, + blinn = true, + shading = "smooth", + } = this.params; + + + const diffuseColor = new this.THREE.Color(); + const specularColor = new this.THREE.Color(); + const materialColor = new this.THREE.Color(); + + materialColor.setRGB(1.0, 1.0, 1.0); + + let wireMaterial = new this.THREE.MeshBasicMaterial({ wireframe: true, color: 0xCC0000 }); + let flatMaterial = new this.THREE.MeshPhongMaterial({ color: materialColor, specular: 0x000000, flatShading: true, side: this.THREE.DoubleSide }); + let phongMaterial = new this.THREE.MeshPhongMaterial({ color: materialColor, side: this.THREE.DoubleSide }); + let gouraudMaterial = new this.THREE.MeshLambertMaterial({ color: materialColor, side: this.THREE.DoubleSide }); + + diffuseColor.setHSL(0.121, 0.73, 0.66); + specularColor.setRGB(1, 1, 1); + + phongMaterial.shininess = 40; + phongMaterial.specular.copy(diffuseColor); + + phongMaterial.color.copy(diffuseColor); + flatMaterial.color.copy(diffuseColor); + gouraudMaterial.color.copy(diffuseColor); + + let shadingMap = { + wireframe: wireMaterial, + flat: flatMaterial, + smooth: gouraudMaterial, + glossy: phongMaterial, + }; + + + let geo = new TeapotGeometry( + size, + segments, + bottom, + lid, + body, + fitLid, + blinn); + + + let obj3d = new this.THREE.Mesh(geo, shadingMap[shading]); + + obj3d.position.z = z; + obj3d.position.y = y; + obj3d.position.x = x; + + return obj3d; + } + + update(event) { + event.target.rotation.y -= .005; + } +}; diff --git a/examples/geometries/TeapotGeometry.js b/examples/geometries/TeapotGeometry.js old mode 100644 new mode 100755 index 69d1161..f2e109f --- a/examples/geometries/TeapotGeometry.js +++ b/examples/geometries/TeapotGeometry.js @@ -48,677 +48,657 @@ const Vector4 = ThreeJSWrapper.THREE.Vector4; * * Code converted from my ancient SPD software, http://tog.acm.org/resources/SPD/ * Created for the Udacity course "Interactive Rendering", http://bit.ly/ericity - * Lesson: https://www.udacity.com/course/viewer#!/c-cs291/l-68866048/m-106482448 * YouTube video on teapot history: https://www.youtube.com/watch?v=DxMfblPzFNc * * See https://en.wikipedia.org/wiki/Utah_teapot for the history of the teapot * */ -var TeapotGeometry = function ( size, segments, bottom, lid, body, fitLid, blinn ) { - - // 32 * 4 * 4 Bezier spline patches - var teapotPatches = [ - /*rim*/ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 3, 16, 17, 18, 7, 19, 20, 21, 11, 22, 23, 24, 15, 25, 26, 27, - 18, 28, 29, 30, 21, 31, 32, 33, 24, 34, 35, 36, 27, 37, 38, 39, - 30, 40, 41, 0, 33, 42, 43, 4, 36, 44, 45, 8, 39, 46, 47, 12, - /*body*/ - 12, 13, 14, 15, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, - 15, 25, 26, 27, 51, 60, 61, 62, 55, 63, 64, 65, 59, 66, 67, 68, - 27, 37, 38, 39, 62, 69, 70, 71, 65, 72, 73, 74, 68, 75, 76, 77, - 39, 46, 47, 12, 71, 78, 79, 48, 74, 80, 81, 52, 77, 82, 83, 56, - 56, 57, 58, 59, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 59, 66, 67, 68, 87, 96, 97, 98, 91, 99, 100, 101, 95, 102, 103, 104, - 68, 75, 76, 77, 98, 105, 106, 107, 101, 108, 109, 110, 104, 111, 112, 113, - 77, 82, 83, 56, 107, 114, 115, 84, 110, 116, 117, 88, 113, 118, 119, 92, - /*handle*/ - 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, - 123, 136, 137, 120, 127, 138, 139, 124, 131, 140, 141, 128, 135, 142, 143, 132, - 132, 133, 134, 135, 144, 145, 146, 147, 148, 149, 150, 151, 68, 152, 153, 154, - 135, 142, 143, 132, 147, 155, 156, 144, 151, 157, 158, 148, 154, 159, 160, 68, - /*spout*/ - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, - 164, 177, 178, 161, 168, 179, 180, 165, 172, 181, 182, 169, 176, 183, 184, 173, - 173, 174, 175, 176, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, - 176, 183, 184, 173, 188, 197, 198, 185, 192, 199, 200, 189, 196, 201, 202, 193, - /*lid*/ - 203, 203, 203, 203, 204, 205, 206, 207, 208, 208, 208, 208, 209, 210, 211, 212, - 203, 203, 203, 203, 207, 213, 214, 215, 208, 208, 208, 208, 212, 216, 217, 218, - 203, 203, 203, 203, 215, 219, 220, 221, 208, 208, 208, 208, 218, 222, 223, 224, - 203, 203, 203, 203, 221, 225, 226, 204, 208, 208, 208, 208, 224, 227, 228, 209, - 209, 210, 211, 212, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, - 212, 216, 217, 218, 232, 241, 242, 243, 236, 244, 245, 246, 240, 247, 248, 249, - 218, 222, 223, 224, 243, 250, 251, 252, 246, 253, 254, 255, 249, 256, 257, 258, - 224, 227, 228, 209, 252, 259, 260, 229, 255, 261, 262, 233, 258, 263, 264, 237, - /*bottom*/ - 265, 265, 265, 265, 266, 267, 268, 269, 270, 271, 272, 273, 92, 119, 118, 113, - 265, 265, 265, 265, 269, 274, 275, 276, 273, 277, 278, 279, 113, 112, 111, 104, - 265, 265, 265, 265, 276, 280, 281, 282, 279, 283, 284, 285, 104, 103, 102, 95, - 265, 265, 265, 265, 282, 286, 287, 266, 285, 288, 289, 270, 95, 94, 93, 92 - ]; - - var teapotVertices = [ - 1.4, 0, 2.4, - 1.4, - 0.784, 2.4, - 0.784, - 1.4, 2.4, - 0, - 1.4, 2.4, - 1.3375, 0, 2.53125, - 1.3375, - 0.749, 2.53125, - 0.749, - 1.3375, 2.53125, - 0, - 1.3375, 2.53125, - 1.4375, 0, 2.53125, - 1.4375, - 0.805, 2.53125, - 0.805, - 1.4375, 2.53125, - 0, - 1.4375, 2.53125, - 1.5, 0, 2.4, - 1.5, - 0.84, 2.4, - 0.84, - 1.5, 2.4, - 0, - 1.5, 2.4, - - 0.784, - 1.4, 2.4, - - 1.4, - 0.784, 2.4, - - 1.4, 0, 2.4, - - 0.749, - 1.3375, 2.53125, - - 1.3375, - 0.749, 2.53125, - - 1.3375, 0, 2.53125, - - 0.805, - 1.4375, 2.53125, - - 1.4375, - 0.805, 2.53125, - - 1.4375, 0, 2.53125, - - 0.84, - 1.5, 2.4, - - 1.5, - 0.84, 2.4, - - 1.5, 0, 2.4, - - 1.4, 0.784, 2.4, - - 0.784, 1.4, 2.4, - 0, 1.4, 2.4, - - 1.3375, 0.749, 2.53125, - - 0.749, 1.3375, 2.53125, - 0, 1.3375, 2.53125, - - 1.4375, 0.805, 2.53125, - - 0.805, 1.4375, 2.53125, - 0, 1.4375, 2.53125, - - 1.5, 0.84, 2.4, - - 0.84, 1.5, 2.4, - 0, 1.5, 2.4, - 0.784, 1.4, 2.4, - 1.4, 0.784, 2.4, - 0.749, 1.3375, 2.53125, - 1.3375, 0.749, 2.53125, - 0.805, 1.4375, 2.53125, - 1.4375, 0.805, 2.53125, - 0.84, 1.5, 2.4, - 1.5, 0.84, 2.4, - 1.75, 0, 1.875, - 1.75, - 0.98, 1.875, - 0.98, - 1.75, 1.875, - 0, - 1.75, 1.875, - 2, 0, 1.35, - 2, - 1.12, 1.35, - 1.12, - 2, 1.35, - 0, - 2, 1.35, - 2, 0, 0.9, - 2, - 1.12, 0.9, - 1.12, - 2, 0.9, - 0, - 2, 0.9, - - 0.98, - 1.75, 1.875, - - 1.75, - 0.98, 1.875, - - 1.75, 0, 1.875, - - 1.12, - 2, 1.35, - - 2, - 1.12, 1.35, - - 2, 0, 1.35, - - 1.12, - 2, 0.9, - - 2, - 1.12, 0.9, - - 2, 0, 0.9, - - 1.75, 0.98, 1.875, - - 0.98, 1.75, 1.875, - 0, 1.75, 1.875, - - 2, 1.12, 1.35, - - 1.12, 2, 1.35, - 0, 2, 1.35, - - 2, 1.12, 0.9, - - 1.12, 2, 0.9, - 0, 2, 0.9, - 0.98, 1.75, 1.875, - 1.75, 0.98, 1.875, - 1.12, 2, 1.35, - 2, 1.12, 1.35, - 1.12, 2, 0.9, - 2, 1.12, 0.9, - 2, 0, 0.45, - 2, - 1.12, 0.45, - 1.12, - 2, 0.45, - 0, - 2, 0.45, - 1.5, 0, 0.225, - 1.5, - 0.84, 0.225, - 0.84, - 1.5, 0.225, - 0, - 1.5, 0.225, - 1.5, 0, 0.15, - 1.5, - 0.84, 0.15, - 0.84, - 1.5, 0.15, - 0, - 1.5, 0.15, - - 1.12, - 2, 0.45, - - 2, - 1.12, 0.45, - - 2, 0, 0.45, - - 0.84, - 1.5, 0.225, - - 1.5, - 0.84, 0.225, - - 1.5, 0, 0.225, - - 0.84, - 1.5, 0.15, - - 1.5, - 0.84, 0.15, - - 1.5, 0, 0.15, - - 2, 1.12, 0.45, - - 1.12, 2, 0.45, - 0, 2, 0.45, - - 1.5, 0.84, 0.225, - - 0.84, 1.5, 0.225, - 0, 1.5, 0.225, - - 1.5, 0.84, 0.15, - - 0.84, 1.5, 0.15, - 0, 1.5, 0.15, - 1.12, 2, 0.45, - 2, 1.12, 0.45, - 0.84, 1.5, 0.225, - 1.5, 0.84, 0.225, - 0.84, 1.5, 0.15, - 1.5, 0.84, 0.15, - - 1.6, 0, 2.025, - - 1.6, - 0.3, 2.025, - - 1.5, - 0.3, 2.25, - - 1.5, 0, 2.25, - - 2.3, 0, 2.025, - - 2.3, - 0.3, 2.025, - - 2.5, - 0.3, 2.25, - - 2.5, 0, 2.25, - - 2.7, 0, 2.025, - - 2.7, - 0.3, 2.025, - - 3, - 0.3, 2.25, - - 3, 0, 2.25, - - 2.7, 0, 1.8, - - 2.7, - 0.3, 1.8, - - 3, - 0.3, 1.8, - - 3, 0, 1.8, - - 1.5, 0.3, 2.25, - - 1.6, 0.3, 2.025, - - 2.5, 0.3, 2.25, - - 2.3, 0.3, 2.025, - - 3, 0.3, 2.25, - - 2.7, 0.3, 2.025, - - 3, 0.3, 1.8, - - 2.7, 0.3, 1.8, - - 2.7, 0, 1.575, - - 2.7, - 0.3, 1.575, - - 3, - 0.3, 1.35, - - 3, 0, 1.35, - - 2.5, 0, 1.125, - - 2.5, - 0.3, 1.125, - - 2.65, - 0.3, 0.9375, - - 2.65, 0, 0.9375, - - 2, - 0.3, 0.9, - - 1.9, - 0.3, 0.6, - - 1.9, 0, 0.6, - - 3, 0.3, 1.35, - - 2.7, 0.3, 1.575, - - 2.65, 0.3, 0.9375, - - 2.5, 0.3, 1.125, - - 1.9, 0.3, 0.6, - - 2, 0.3, 0.9, - 1.7, 0, 1.425, - 1.7, - 0.66, 1.425, - 1.7, - 0.66, 0.6, - 1.7, 0, 0.6, - 2.6, 0, 1.425, - 2.6, - 0.66, 1.425, - 3.1, - 0.66, 0.825, - 3.1, 0, 0.825, - 2.3, 0, 2.1, - 2.3, - 0.25, 2.1, - 2.4, - 0.25, 2.025, - 2.4, 0, 2.025, - 2.7, 0, 2.4, - 2.7, - 0.25, 2.4, - 3.3, - 0.25, 2.4, - 3.3, 0, 2.4, - 1.7, 0.66, 0.6, - 1.7, 0.66, 1.425, - 3.1, 0.66, 0.825, - 2.6, 0.66, 1.425, - 2.4, 0.25, 2.025, - 2.3, 0.25, 2.1, - 3.3, 0.25, 2.4, - 2.7, 0.25, 2.4, - 2.8, 0, 2.475, - 2.8, - 0.25, 2.475, - 3.525, - 0.25, 2.49375, - 3.525, 0, 2.49375, - 2.9, 0, 2.475, - 2.9, - 0.15, 2.475, - 3.45, - 0.15, 2.5125, - 3.45, 0, 2.5125, - 2.8, 0, 2.4, - 2.8, - 0.15, 2.4, - 3.2, - 0.15, 2.4, - 3.2, 0, 2.4, - 3.525, 0.25, 2.49375, - 2.8, 0.25, 2.475, - 3.45, 0.15, 2.5125, - 2.9, 0.15, 2.475, - 3.2, 0.15, 2.4, - 2.8, 0.15, 2.4, - 0, 0, 3.15, - 0.8, 0, 3.15, - 0.8, - 0.45, 3.15, - 0.45, - 0.8, 3.15, - 0, - 0.8, 3.15, - 0, 0, 2.85, - 0.2, 0, 2.7, - 0.2, - 0.112, 2.7, - 0.112, - 0.2, 2.7, - 0, - 0.2, 2.7, - - 0.45, - 0.8, 3.15, - - 0.8, - 0.45, 3.15, - - 0.8, 0, 3.15, - - 0.112, - 0.2, 2.7, - - 0.2, - 0.112, 2.7, - - 0.2, 0, 2.7, - - 0.8, 0.45, 3.15, - - 0.45, 0.8, 3.15, - 0, 0.8, 3.15, - - 0.2, 0.112, 2.7, - - 0.112, 0.2, 2.7, - 0, 0.2, 2.7, - 0.45, 0.8, 3.15, - 0.8, 0.45, 3.15, - 0.112, 0.2, 2.7, - 0.2, 0.112, 2.7, - 0.4, 0, 2.55, - 0.4, - 0.224, 2.55, - 0.224, - 0.4, 2.55, - 0, - 0.4, 2.55, - 1.3, 0, 2.55, - 1.3, - 0.728, 2.55, - 0.728, - 1.3, 2.55, - 0, - 1.3, 2.55, - 1.3, 0, 2.4, - 1.3, - 0.728, 2.4, - 0.728, - 1.3, 2.4, - 0, - 1.3, 2.4, - - 0.224, - 0.4, 2.55, - - 0.4, - 0.224, 2.55, - - 0.4, 0, 2.55, - - 0.728, - 1.3, 2.55, - - 1.3, - 0.728, 2.55, - - 1.3, 0, 2.55, - - 0.728, - 1.3, 2.4, - - 1.3, - 0.728, 2.4, - - 1.3, 0, 2.4, - - 0.4, 0.224, 2.55, - - 0.224, 0.4, 2.55, - 0, 0.4, 2.55, - - 1.3, 0.728, 2.55, - - 0.728, 1.3, 2.55, - 0, 1.3, 2.55, - - 1.3, 0.728, 2.4, - - 0.728, 1.3, 2.4, - 0, 1.3, 2.4, - 0.224, 0.4, 2.55, - 0.4, 0.224, 2.55, - 0.728, 1.3, 2.55, - 1.3, 0.728, 2.55, - 0.728, 1.3, 2.4, - 1.3, 0.728, 2.4, - 0, 0, 0, - 1.425, 0, 0, - 1.425, 0.798, 0, - 0.798, 1.425, 0, - 0, 1.425, 0, - 1.5, 0, 0.075, - 1.5, 0.84, 0.075, - 0.84, 1.5, 0.075, - 0, 1.5, 0.075, - - 0.798, 1.425, 0, - - 1.425, 0.798, 0, - - 1.425, 0, 0, - - 0.84, 1.5, 0.075, - - 1.5, 0.84, 0.075, - - 1.5, 0, 0.075, - - 1.425, - 0.798, 0, - - 0.798, - 1.425, 0, - 0, - 1.425, 0, - - 1.5, - 0.84, 0.075, - - 0.84, - 1.5, 0.075, - 0, - 1.5, 0.075, - 0.798, - 1.425, 0, - 1.425, - 0.798, 0, - 0.84, - 1.5, 0.075, - 1.5, - 0.84, 0.075 - ]; - - BufferGeometry.call( this ); - - size = size || 50; - - // number of segments per patch - segments = segments !== undefined ? Math.max( 2, Math.floor( segments ) || 10 ) : 10; - - // which parts should be visible - bottom = bottom === undefined ? true : bottom; - lid = lid === undefined ? true : lid; - body = body === undefined ? true : body; - - // Should the lid be snug? It's not traditional, but we make it snug by default - fitLid = fitLid === undefined ? true : fitLid; - - // Jim Blinn scaled the teapot down in size by about 1.3 for - // some rendering tests. He liked the new proportions that he kept - // the data in this form. The model was distributed with these new - // proportions and became the norm. Trivia: comparing images of the - // real teapot and the computer model, the ratio for the bowl of the - // real teapot is more like 1.25, but since 1.3 is the traditional - // value given, we use it here. - var blinnScale = 1.3; - blinn = blinn === undefined ? true : blinn; - - // scale the size to be the real scaling factor - var maxHeight = 3.15 * ( blinn ? 1 : blinnScale ); - - var maxHeight2 = maxHeight / 2; - var trueSize = size / maxHeight2; - - // Number of elements depends on what is needed. Subtract degenerate - // triangles at tip of bottom and lid out in advance. - var numTriangles = bottom ? ( 8 * segments - 4 ) * segments : 0; - numTriangles += lid ? ( 16 * segments - 4 ) * segments : 0; - numTriangles += body ? 40 * segments * segments : 0; - - var indices = new Uint32Array( numTriangles * 3 ); - - var numVertices = bottom ? 4 : 0; - numVertices += lid ? 8 : 0; - numVertices += body ? 20 : 0; - numVertices *= ( segments + 1 ) * ( segments + 1 ); - - var vertices = new Float32Array( numVertices * 3 ); - var normals = new Float32Array( numVertices * 3 ); - var uvs = new Float32Array( numVertices * 2 ); - - // Bezier form - var ms = new Matrix4(); - ms.set( - - 1.0, 3.0, - 3.0, 1.0, - 3.0, - 6.0, 3.0, 0.0, - - 3.0, 3.0, 0.0, 0.0, - 1.0, 0.0, 0.0, 0.0 ); - - var g = []; - var i, r, c; - - var sp = []; - var tp = []; - var dsp = []; - var dtp = []; - - // M * G * M matrix, sort of see - // http://www.cs.helsinki.fi/group/goa/mallinnus/curves/surfaces.html - var mgm = []; - - var vert = []; - var sdir = []; - var tdir = []; - - var norm = new Vector3(); - - var tcoord; - - var sstep, tstep; - var vertPerRow; - - var s, t, sval, tval, p; - var dsval = 0; - var dtval = 0; - - var normOut = new Vector3(); - var v1, v2, v3, v4; - - var gmx = new Matrix4(); - var tmtx = new Matrix4(); +class TeapotGeometry extends BufferGeometry { + + constructor(size = 50, segments = 10, bottom = true, lid = true, body = true, fitLid = true, blinn = true) { + + // 32 * 4 * 4 Bezier spline patches + const teapotPatches = [ + /*rim*/ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 3, 16, 17, 18, 7, 19, 20, 21, 11, 22, 23, 24, 15, 25, 26, 27, + 18, 28, 29, 30, 21, 31, 32, 33, 24, 34, 35, 36, 27, 37, 38, 39, + 30, 40, 41, 0, 33, 42, 43, 4, 36, 44, 45, 8, 39, 46, 47, 12, + /*body*/ + 12, 13, 14, 15, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 15, 25, 26, 27, 51, 60, 61, 62, 55, 63, 64, 65, 59, 66, 67, 68, + 27, 37, 38, 39, 62, 69, 70, 71, 65, 72, 73, 74, 68, 75, 76, 77, + 39, 46, 47, 12, 71, 78, 79, 48, 74, 80, 81, 52, 77, 82, 83, 56, + 56, 57, 58, 59, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 59, 66, 67, 68, 87, 96, 97, 98, 91, 99, 100, 101, 95, 102, 103, 104, + 68, 75, 76, 77, 98, 105, 106, 107, 101, 108, 109, 110, 104, 111, 112, 113, + 77, 82, 83, 56, 107, 114, 115, 84, 110, 116, 117, 88, 113, 118, 119, 92, + /*handle*/ + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, + 123, 136, 137, 120, 127, 138, 139, 124, 131, 140, 141, 128, 135, 142, 143, 132, + 132, 133, 134, 135, 144, 145, 146, 147, 148, 149, 150, 151, 68, 152, 153, 154, + 135, 142, 143, 132, 147, 155, 156, 144, 151, 157, 158, 148, 154, 159, 160, 68, + /*spout*/ + 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 164, 177, 178, 161, 168, 179, 180, 165, 172, 181, 182, 169, 176, 183, 184, 173, + 173, 174, 175, 176, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, + 176, 183, 184, 173, 188, 197, 198, 185, 192, 199, 200, 189, 196, 201, 202, 193, + /*lid*/ + 203, 203, 203, 203, 204, 205, 206, 207, 208, 208, 208, 208, 209, 210, 211, 212, + 203, 203, 203, 203, 207, 213, 214, 215, 208, 208, 208, 208, 212, 216, 217, 218, + 203, 203, 203, 203, 215, 219, 220, 221, 208, 208, 208, 208, 218, 222, 223, 224, + 203, 203, 203, 203, 221, 225, 226, 204, 208, 208, 208, 208, 224, 227, 228, 209, + 209, 210, 211, 212, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, + 212, 216, 217, 218, 232, 241, 242, 243, 236, 244, 245, 246, 240, 247, 248, 249, + 218, 222, 223, 224, 243, 250, 251, 252, 246, 253, 254, 255, 249, 256, 257, 258, + 224, 227, 228, 209, 252, 259, 260, 229, 255, 261, 262, 233, 258, 263, 264, 237, + /*bottom*/ + 265, 265, 265, 265, 266, 267, 268, 269, 270, 271, 272, 273, 92, 119, 118, 113, + 265, 265, 265, 265, 269, 274, 275, 276, 273, 277, 278, 279, 113, 112, 111, 104, + 265, 265, 265, 265, 276, 280, 281, 282, 279, 283, 284, 285, 104, 103, 102, 95, + 265, 265, 265, 265, 282, 286, 287, 266, 285, 288, 289, 270, 95, 94, 93, 92 + ]; + + const teapotVertices = [ + 1.4, 0, 2.4, + 1.4, - 0.784, 2.4, + 0.784, - 1.4, 2.4, + 0, - 1.4, 2.4, + 1.3375, 0, 2.53125, + 1.3375, - 0.749, 2.53125, + 0.749, - 1.3375, 2.53125, + 0, - 1.3375, 2.53125, + 1.4375, 0, 2.53125, + 1.4375, - 0.805, 2.53125, + 0.805, - 1.4375, 2.53125, + 0, - 1.4375, 2.53125, + 1.5, 0, 2.4, + 1.5, - 0.84, 2.4, + 0.84, - 1.5, 2.4, + 0, - 1.5, 2.4, + - 0.784, - 1.4, 2.4, + - 1.4, - 0.784, 2.4, + - 1.4, 0, 2.4, + - 0.749, - 1.3375, 2.53125, + - 1.3375, - 0.749, 2.53125, + - 1.3375, 0, 2.53125, + - 0.805, - 1.4375, 2.53125, + - 1.4375, - 0.805, 2.53125, + - 1.4375, 0, 2.53125, + - 0.84, - 1.5, 2.4, + - 1.5, - 0.84, 2.4, + - 1.5, 0, 2.4, + - 1.4, 0.784, 2.4, + - 0.784, 1.4, 2.4, + 0, 1.4, 2.4, + - 1.3375, 0.749, 2.53125, + - 0.749, 1.3375, 2.53125, + 0, 1.3375, 2.53125, + - 1.4375, 0.805, 2.53125, + - 0.805, 1.4375, 2.53125, + 0, 1.4375, 2.53125, + - 1.5, 0.84, 2.4, + - 0.84, 1.5, 2.4, + 0, 1.5, 2.4, + 0.784, 1.4, 2.4, + 1.4, 0.784, 2.4, + 0.749, 1.3375, 2.53125, + 1.3375, 0.749, 2.53125, + 0.805, 1.4375, 2.53125, + 1.4375, 0.805, 2.53125, + 0.84, 1.5, 2.4, + 1.5, 0.84, 2.4, + 1.75, 0, 1.875, + 1.75, - 0.98, 1.875, + 0.98, - 1.75, 1.875, + 0, - 1.75, 1.875, + 2, 0, 1.35, + 2, - 1.12, 1.35, + 1.12, - 2, 1.35, + 0, - 2, 1.35, + 2, 0, 0.9, + 2, - 1.12, 0.9, + 1.12, - 2, 0.9, + 0, - 2, 0.9, + - 0.98, - 1.75, 1.875, + - 1.75, - 0.98, 1.875, + - 1.75, 0, 1.875, + - 1.12, - 2, 1.35, + - 2, - 1.12, 1.35, + - 2, 0, 1.35, + - 1.12, - 2, 0.9, + - 2, - 1.12, 0.9, + - 2, 0, 0.9, + - 1.75, 0.98, 1.875, + - 0.98, 1.75, 1.875, + 0, 1.75, 1.875, + - 2, 1.12, 1.35, + - 1.12, 2, 1.35, + 0, 2, 1.35, + - 2, 1.12, 0.9, + - 1.12, 2, 0.9, + 0, 2, 0.9, + 0.98, 1.75, 1.875, + 1.75, 0.98, 1.875, + 1.12, 2, 1.35, + 2, 1.12, 1.35, + 1.12, 2, 0.9, + 2, 1.12, 0.9, + 2, 0, 0.45, + 2, - 1.12, 0.45, + 1.12, - 2, 0.45, + 0, - 2, 0.45, + 1.5, 0, 0.225, + 1.5, - 0.84, 0.225, + 0.84, - 1.5, 0.225, + 0, - 1.5, 0.225, + 1.5, 0, 0.15, + 1.5, - 0.84, 0.15, + 0.84, - 1.5, 0.15, + 0, - 1.5, 0.15, + - 1.12, - 2, 0.45, + - 2, - 1.12, 0.45, + - 2, 0, 0.45, + - 0.84, - 1.5, 0.225, + - 1.5, - 0.84, 0.225, + - 1.5, 0, 0.225, + - 0.84, - 1.5, 0.15, + - 1.5, - 0.84, 0.15, + - 1.5, 0, 0.15, + - 2, 1.12, 0.45, + - 1.12, 2, 0.45, + 0, 2, 0.45, + - 1.5, 0.84, 0.225, + - 0.84, 1.5, 0.225, + 0, 1.5, 0.225, + - 1.5, 0.84, 0.15, + - 0.84, 1.5, 0.15, + 0, 1.5, 0.15, + 1.12, 2, 0.45, + 2, 1.12, 0.45, + 0.84, 1.5, 0.225, + 1.5, 0.84, 0.225, + 0.84, 1.5, 0.15, + 1.5, 0.84, 0.15, + - 1.6, 0, 2.025, + - 1.6, - 0.3, 2.025, + - 1.5, - 0.3, 2.25, + - 1.5, 0, 2.25, + - 2.3, 0, 2.025, + - 2.3, - 0.3, 2.025, + - 2.5, - 0.3, 2.25, + - 2.5, 0, 2.25, + - 2.7, 0, 2.025, + - 2.7, - 0.3, 2.025, + - 3, - 0.3, 2.25, + - 3, 0, 2.25, + - 2.7, 0, 1.8, + - 2.7, - 0.3, 1.8, + - 3, - 0.3, 1.8, + - 3, 0, 1.8, + - 1.5, 0.3, 2.25, + - 1.6, 0.3, 2.025, + - 2.5, 0.3, 2.25, + - 2.3, 0.3, 2.025, + - 3, 0.3, 2.25, + - 2.7, 0.3, 2.025, + - 3, 0.3, 1.8, + - 2.7, 0.3, 1.8, + - 2.7, 0, 1.575, + - 2.7, - 0.3, 1.575, + - 3, - 0.3, 1.35, + - 3, 0, 1.35, + - 2.5, 0, 1.125, + - 2.5, - 0.3, 1.125, + - 2.65, - 0.3, 0.9375, + - 2.65, 0, 0.9375, + - 2, - 0.3, 0.9, + - 1.9, - 0.3, 0.6, + - 1.9, 0, 0.6, + - 3, 0.3, 1.35, + - 2.7, 0.3, 1.575, + - 2.65, 0.3, 0.9375, + - 2.5, 0.3, 1.125, + - 1.9, 0.3, 0.6, + - 2, 0.3, 0.9, + 1.7, 0, 1.425, + 1.7, - 0.66, 1.425, + 1.7, - 0.66, 0.6, + 1.7, 0, 0.6, + 2.6, 0, 1.425, + 2.6, - 0.66, 1.425, + 3.1, - 0.66, 0.825, + 3.1, 0, 0.825, + 2.3, 0, 2.1, + 2.3, - 0.25, 2.1, + 2.4, - 0.25, 2.025, + 2.4, 0, 2.025, + 2.7, 0, 2.4, + 2.7, - 0.25, 2.4, + 3.3, - 0.25, 2.4, + 3.3, 0, 2.4, + 1.7, 0.66, 0.6, + 1.7, 0.66, 1.425, + 3.1, 0.66, 0.825, + 2.6, 0.66, 1.425, + 2.4, 0.25, 2.025, + 2.3, 0.25, 2.1, + 3.3, 0.25, 2.4, + 2.7, 0.25, 2.4, + 2.8, 0, 2.475, + 2.8, - 0.25, 2.475, + 3.525, - 0.25, 2.49375, + 3.525, 0, 2.49375, + 2.9, 0, 2.475, + 2.9, - 0.15, 2.475, + 3.45, - 0.15, 2.5125, + 3.45, 0, 2.5125, + 2.8, 0, 2.4, + 2.8, - 0.15, 2.4, + 3.2, - 0.15, 2.4, + 3.2, 0, 2.4, + 3.525, 0.25, 2.49375, + 2.8, 0.25, 2.475, + 3.45, 0.15, 2.5125, + 2.9, 0.15, 2.475, + 3.2, 0.15, 2.4, + 2.8, 0.15, 2.4, + 0, 0, 3.15, + 0.8, 0, 3.15, + 0.8, - 0.45, 3.15, + 0.45, - 0.8, 3.15, + 0, - 0.8, 3.15, + 0, 0, 2.85, + 0.2, 0, 2.7, + 0.2, - 0.112, 2.7, + 0.112, - 0.2, 2.7, + 0, - 0.2, 2.7, + - 0.45, - 0.8, 3.15, + - 0.8, - 0.45, 3.15, + - 0.8, 0, 3.15, + - 0.112, - 0.2, 2.7, + - 0.2, - 0.112, 2.7, + - 0.2, 0, 2.7, + - 0.8, 0.45, 3.15, + - 0.45, 0.8, 3.15, + 0, 0.8, 3.15, + - 0.2, 0.112, 2.7, + - 0.112, 0.2, 2.7, + 0, 0.2, 2.7, + 0.45, 0.8, 3.15, + 0.8, 0.45, 3.15, + 0.112, 0.2, 2.7, + 0.2, 0.112, 2.7, + 0.4, 0, 2.55, + 0.4, - 0.224, 2.55, + 0.224, - 0.4, 2.55, + 0, - 0.4, 2.55, + 1.3, 0, 2.55, + 1.3, - 0.728, 2.55, + 0.728, - 1.3, 2.55, + 0, - 1.3, 2.55, + 1.3, 0, 2.4, + 1.3, - 0.728, 2.4, + 0.728, - 1.3, 2.4, + 0, - 1.3, 2.4, + - 0.224, - 0.4, 2.55, + - 0.4, - 0.224, 2.55, + - 0.4, 0, 2.55, + - 0.728, - 1.3, 2.55, + - 1.3, - 0.728, 2.55, + - 1.3, 0, 2.55, + - 0.728, - 1.3, 2.4, + - 1.3, - 0.728, 2.4, + - 1.3, 0, 2.4, + - 0.4, 0.224, 2.55, + - 0.224, 0.4, 2.55, + 0, 0.4, 2.55, + - 1.3, 0.728, 2.55, + - 0.728, 1.3, 2.55, + 0, 1.3, 2.55, + - 1.3, 0.728, 2.4, + - 0.728, 1.3, 2.4, + 0, 1.3, 2.4, + 0.224, 0.4, 2.55, + 0.4, 0.224, 2.55, + 0.728, 1.3, 2.55, + 1.3, 0.728, 2.55, + 0.728, 1.3, 2.4, + 1.3, 0.728, 2.4, + 0, 0, 0, + 1.425, 0, 0, + 1.425, 0.798, 0, + 0.798, 1.425, 0, + 0, 1.425, 0, + 1.5, 0, 0.075, + 1.5, 0.84, 0.075, + 0.84, 1.5, 0.075, + 0, 1.5, 0.075, + - 0.798, 1.425, 0, + - 1.425, 0.798, 0, + - 1.425, 0, 0, + - 0.84, 1.5, 0.075, + - 1.5, 0.84, 0.075, + - 1.5, 0, 0.075, + - 1.425, - 0.798, 0, + - 0.798, - 1.425, 0, + 0, - 1.425, 0, + - 1.5, - 0.84, 0.075, + - 0.84, - 1.5, 0.075, + 0, - 1.5, 0.075, + 0.798, - 1.425, 0, + 1.425, - 0.798, 0, + 0.84, - 1.5, 0.075, + 1.5, - 0.84, 0.075 + ]; + + super(); + + // number of segments per patch + segments = Math.max(2, Math.floor(segments)); + + // Jim Blinn scaled the teapot down in size by about 1.3 for + // some rendering tests. He liked the new proportions that he kept + // the data in this form. The model was distributed with these new + // proportions and became the norm. Trivia: comparing images of the + // real teapot and the computer model, the ratio for the bowl of the + // real teapot is more like 1.25, but since 1.3 is the traditional + // value given, we use it here. + const blinnScale = 1.3; + + // scale the size to be the real scaling factor + const maxHeight = 3.15 * (blinn ? 1 : blinnScale); + + const maxHeight2 = maxHeight / 2; + const trueSize = size / maxHeight2; + + // Number of elements depends on what is needed. Subtract degenerate + // triangles at tip of bottom and lid out in advance. + let numTriangles = bottom ? (8 * segments - 4) * segments : 0; + numTriangles += lid ? (16 * segments - 4) * segments : 0; + numTriangles += body ? 40 * segments * segments : 0; + + const indices = new Uint32Array(numTriangles * 3); + + let numVertices = bottom ? 4 : 0; + numVertices += lid ? 8 : 0; + numVertices += body ? 20 : 0; + numVertices *= (segments + 1) * (segments + 1); + + const vertices = new Float32Array(numVertices * 3); + const normals = new Float32Array(numVertices * 3); + const uvs = new Float32Array(numVertices * 2); + + // Bezier form + const ms = new Matrix4(); + ms.set( + - 1.0, 3.0, - 3.0, 1.0, + 3.0, - 6.0, 3.0, 0.0, + - 3.0, 3.0, 0.0, 0.0, + 1.0, 0.0, 0.0, 0.0); + + const g = []; + + const sp = []; + const tp = []; + const dsp = []; + const dtp = []; + + // M * G * M matrix, sort of see + // http://www.cs.helsinki.fi/group/goa/mallinnus/curves/surfaces.html + const mgm = []; + + const vert = []; + const sdir = []; + const tdir = []; + + const norm = new Vector3(); + + let tcoord; + + let sval; + let tval; + let p; + let dsval = 0; + let dtval = 0; + + const normOut = new Vector3(); + + const gmx = new Matrix4(); + const tmtx = new Matrix4(); + + const vsp = new Vector4(); + const vtp = new Vector4(); + const vdsp = new Vector4(); + const vdtp = new Vector4(); + + const vsdir = new Vector3(); + const vtdir = new Vector3(); + + const mst = ms.clone(); + mst.transpose(); + + // internal function: test if triangle has any matching vertices; + // if so, don't save triangle, since it won't display anything. + const notDegenerate = (vtx1, vtx2, vtx3) => // if any vertex matches, return false + !(((vertices[vtx1 * 3] === vertices[vtx2 * 3]) && + (vertices[vtx1 * 3 + 1] === vertices[vtx2 * 3 + 1]) && + (vertices[vtx1 * 3 + 2] === vertices[vtx2 * 3 + 2])) || + ((vertices[vtx1 * 3] === vertices[vtx3 * 3]) && + (vertices[vtx1 * 3 + 1] === vertices[vtx3 * 3 + 1]) && + (vertices[vtx1 * 3 + 2] === vertices[vtx3 * 3 + 2])) || (vertices[vtx2 * 3] === vertices[vtx3 * 3]) && + (vertices[vtx2 * 3 + 1] === vertices[vtx3 * 3 + 1]) && + (vertices[vtx2 * 3 + 2] === vertices[vtx3 * 3 + 2])); - var vsp = new Vector4(); - var vtp = new Vector4(); - var vdsp = new Vector4(); - var vdtp = new Vector4(); - var vsdir = new Vector3(); - var vtdir = new Vector3(); + for (let i = 0; i < 3; i++) { - var mst = ms.clone(); - mst.transpose(); + mgm[i] = new Matrix4(); - // internal function: test if triangle has any matching vertices; - // if so, don't save triangle, since it won't display anything. - var notDegenerate = function ( vtx1, vtx2, vtx3 ) { - - // if any vertex matches, return false - return ! ( ( ( vertices[ vtx1 * 3 ] === vertices[ vtx2 * 3 ] ) && - ( vertices[ vtx1 * 3 + 1 ] === vertices[ vtx2 * 3 + 1 ] ) && - ( vertices[ vtx1 * 3 + 2 ] === vertices[ vtx2 * 3 + 2 ] ) ) || - ( ( vertices[ vtx1 * 3 ] === vertices[ vtx3 * 3 ] ) && - ( vertices[ vtx1 * 3 + 1 ] === vertices[ vtx3 * 3 + 1 ] ) && - ( vertices[ vtx1 * 3 + 2 ] === vertices[ vtx3 * 3 + 2 ] ) ) || - ( ( vertices[ vtx2 * 3 ] === vertices[ vtx3 * 3 ] ) && - ( vertices[ vtx2 * 3 + 1 ] === vertices[ vtx3 * 3 + 1 ] ) && - ( vertices[ vtx2 * 3 + 2 ] === vertices[ vtx3 * 3 + 2 ] ) ) ); - - }; - - - for ( i = 0; i < 3; i ++ ) { - - mgm[ i ] = new Matrix4(); + } - } + const minPatches = body ? 0 : 20; + const maxPatches = bottom ? 32 : 28; - var minPatches = body ? 0 : 20; - var maxPatches = bottom ? 32 : 28; + const vertPerRow = segments + 1; - vertPerRow = segments + 1; + let surfCount = 0; - var surfCount = 0; + let vertCount = 0; + let normCount = 0; + let uvCount = 0; - var vertCount = 0; - var normCount = 0; - var uvCount = 0; + let indexCount = 0; - var indexCount = 0; + for (let surf = minPatches; surf < maxPatches; surf++) { - for ( var surf = minPatches; surf < maxPatches; surf ++ ) { + // lid is in the middle of the data, patches 20-27, + // so ignore it for this part of the loop if the lid is not desired + if (lid || (surf < 20 || surf >= 28)) { - // lid is in the middle of the data, patches 20-27, - // so ignore it for this part of the loop if the lid is not desired - if ( lid || ( surf < 20 || surf >= 28 ) ) { + // get M * G * M matrix for x,y,z + for (let i = 0; i < 3; i++) { - // get M * G * M matrix for x,y,z - for ( i = 0; i < 3; i ++ ) { + // get control patches + for (let r = 0; r < 4; r++) { - // get control patches - for ( r = 0; r < 4; r ++ ) { + for (let c = 0; c < 4; c++) { - for ( c = 0; c < 4; c ++ ) { + // transposed + g[c * 4 + r] = teapotVertices[teapotPatches[surf * 16 + r * 4 + c] * 3 + i]; - // transposed - g[ c * 4 + r ] = teapotVertices[ teapotPatches[ surf * 16 + r * 4 + c ] * 3 + i ]; + // is the lid to be made larger, and is this a point on the lid + // that is X or Y? + if (fitLid && (surf >= 20 && surf < 28) && (i !== 2)) { - // is the lid to be made larger, and is this a point on the lid - // that is X or Y? - if ( fitLid && ( surf >= 20 && surf < 28 ) && ( i !== 2 ) ) { + // increase XY size by 7.7%, found empirically. I don't + // increase Z so that the teapot will continue to fit in the + // space -1 to 1 for Y (Y is up for the final model). + g[c * 4 + r] *= 1.077; - // increase XY size by 7.7%, found empirically. I don't - // increase Z so that the teapot will continue to fit in the - // space -1 to 1 for Y (Y is up for the final model). - g[ c * 4 + r ] *= 1.077; + } - } + // Blinn "fixed" the teapot by dividing Z by blinnScale, and that's the + // data we now use. The original teapot is taller. Fix it: + if (!blinn && (i === 2)) { - // Blinn "fixed" the teapot by dividing Z by blinnScale, and that's the - // data we now use. The original teapot is taller. Fix it: - if ( ! blinn && ( i === 2 ) ) { + g[c * 4 + r] *= blinnScale; - g[ c * 4 + r ] *= blinnScale; + } } } - } + gmx.set(g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7], g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]); - gmx.set( g[ 0 ], g[ 1 ], g[ 2 ], g[ 3 ], g[ 4 ], g[ 5 ], g[ 6 ], g[ 7 ], g[ 8 ], g[ 9 ], g[ 10 ], g[ 11 ], g[ 12 ], g[ 13 ], g[ 14 ], g[ 15 ] ); + tmtx.multiplyMatrices(gmx, ms); + mgm[i].multiplyMatrices(mst, tmtx); - tmtx.multiplyMatrices( gmx, ms ); - mgm[ i ].multiplyMatrices( mst, tmtx ); + } - } + // step along, get points, and output + for (let sstep = 0; sstep <= segments; sstep++) { - // step along, get points, and output - for ( sstep = 0; sstep <= segments; sstep ++ ) { + const s = sstep / segments; - s = sstep / segments; + for (let tstep = 0; tstep <= segments; tstep++) { - for ( tstep = 0; tstep <= segments; tstep ++ ) { + const t = tstep / segments; - t = tstep / segments; + // point from basis + // get power vectors and their derivatives + for (p = 4, sval = tval = 1.0; p--;) { - // point from basis - // get power vectors and their derivatives - for ( p = 4, sval = tval = 1.0; p --; ) { + sp[p] = sval; + tp[p] = tval; + sval *= s; + tval *= t; - sp[ p ] = sval; - tp[ p ] = tval; - sval *= s; - tval *= t; + if (p === 3) { - if ( p === 3 ) { + dsp[p] = dtp[p] = 0.0; + dsval = dtval = 1.0; - dsp[ p ] = dtp[ p ] = 0.0; - dsval = dtval = 1.0; + } else { - } else { + dsp[p] = dsval * (3 - p); + dtp[p] = dtval * (3 - p); + dsval *= s; + dtval *= t; - dsp[ p ] = dsval * ( 3 - p ); - dtp[ p ] = dtval * ( 3 - p ); - dsval *= s; - dtval *= t; + } } - } + vsp.fromArray(sp); + vtp.fromArray(tp); + vdsp.fromArray(dsp); + vdtp.fromArray(dtp); - vsp.fromArray( sp ); - vtp.fromArray( tp ); - vdsp.fromArray( dsp ); - vdtp.fromArray( dtp ); + // do for x,y,z + for (let i = 0; i < 3; i++) { - // do for x,y,z - for ( i = 0; i < 3; i ++ ) { + // multiply power vectors times matrix to get value + tcoord = vsp.clone(); + tcoord.applyMatrix4(mgm[i]); + vert[i] = tcoord.dot(vtp); - // multiply power vectors times matrix to get value - tcoord = vsp.clone(); - tcoord.applyMatrix4( mgm[ i ] ); - vert[ i ] = tcoord.dot( vtp ); + // get s and t tangent vectors + tcoord = vdsp.clone(); + tcoord.applyMatrix4(mgm[i]); + sdir[i] = tcoord.dot(vtp); - // get s and t tangent vectors - tcoord = vdsp.clone(); - tcoord.applyMatrix4( mgm[ i ] ); - sdir[ i ] = tcoord.dot( vtp ); + tcoord = vsp.clone(); + tcoord.applyMatrix4(mgm[i]); + tdir[i] = tcoord.dot(vdtp); - tcoord = vsp.clone(); - tcoord.applyMatrix4( mgm[ i ] ); - tdir[ i ] = tcoord.dot( vdtp ); + } - } + // find normal + vsdir.fromArray(sdir); + vtdir.fromArray(tdir); + norm.crossVectors(vtdir, vsdir); + norm.normalize(); - // find normal - vsdir.fromArray( sdir ); - vtdir.fromArray( tdir ); - norm.crossVectors( vtdir, vsdir ); - norm.normalize(); + // if X and Z length is 0, at the cusp, so point the normal up or down, depending on patch number + if (vert[0] === 0 && vert[1] === 0) { - // if X and Z length is 0, at the cusp, so point the normal up or down, depending on patch number - if ( vert[ 0 ] === 0 && vert[ 1 ] === 0 ) { + // if above the middle of the teapot, normal points up, else down + normOut.set(0, vert[2] > maxHeight2 ? 1 : - 1, 0); - // if above the middle of the teapot, normal points up, else down - normOut.set( 0, vert[ 2 ] > maxHeight2 ? 1 : - 1, 0 ); + } else { - } else { + // standard output: rotate on X axis + normOut.set(norm.x, norm.z, - norm.y); - // standard output: rotate on X axis - normOut.set( norm.x, norm.z, - norm.y ); + } - } + // store it all + vertices[vertCount++] = trueSize * vert[0]; + vertices[vertCount++] = trueSize * (vert[2] - maxHeight2); + vertices[vertCount++] = - trueSize * vert[1]; - // store it all - vertices[ vertCount ++ ] = trueSize * vert[ 0 ]; - vertices[ vertCount ++ ] = trueSize * ( vert[ 2 ] - maxHeight2 ); - vertices[ vertCount ++ ] = - trueSize * vert[ 1 ]; + normals[normCount++] = normOut.x; + normals[normCount++] = normOut.y; + normals[normCount++] = normOut.z; - normals[ normCount ++ ] = normOut.x; - normals[ normCount ++ ] = normOut.y; - normals[ normCount ++ ] = normOut.z; + uvs[uvCount++] = 1 - t; + uvs[uvCount++] = 1 - s; - uvs[ uvCount ++ ] = 1 - t; - uvs[ uvCount ++ ] = 1 - s; + } } - } + // save the faces + for (let sstep = 0; sstep < segments; sstep++) { - // save the faces - for ( sstep = 0; sstep < segments; sstep ++ ) { + for (let tstep = 0; tstep < segments; tstep++) { - for ( tstep = 0; tstep < segments; tstep ++ ) { + const v1 = surfCount * vertPerRow * vertPerRow + sstep * vertPerRow + tstep; + const v2 = v1 + 1; + const v3 = v2 + vertPerRow; + const v4 = v1 + vertPerRow; - v1 = surfCount * vertPerRow * vertPerRow + sstep * vertPerRow + tstep; - v2 = v1 + 1; - v3 = v2 + vertPerRow; - v4 = v1 + vertPerRow; + // Normals and UVs cannot be shared. Without clone(), you can see the consequences + // of sharing if you call geometry.applyMatrix4( matrix ). + if (notDegenerate(v1, v2, v3)) { - // Normals and UVs cannot be shared. Without clone(), you can see the consequences - // of sharing if you call geometry.applyMatrix4( matrix ). - if ( notDegenerate( v1, v2, v3 ) ) { + indices[indexCount++] = v1; + indices[indexCount++] = v2; + indices[indexCount++] = v3; - indices[ indexCount ++ ] = v1; - indices[ indexCount ++ ] = v2; - indices[ indexCount ++ ] = v3; + } - } + if (notDegenerate(v1, v3, v4)) { - if ( notDegenerate( v1, v3, v4 ) ) { + indices[indexCount++] = v1; + indices[indexCount++] = v3; + indices[indexCount++] = v4; - indices[ indexCount ++ ] = v1; - indices[ indexCount ++ ] = v3; - indices[ indexCount ++ ] = v4; + } } } - } + // increment only if a surface was used + surfCount++; - // increment only if a surface was used - surfCount ++; + } } - } + this.setIndex(new BufferAttribute(indices, 1)); + this.setAttribute('position', new BufferAttribute(vertices, 3)); + this.setAttribute('normal', new BufferAttribute(normals, 3)); + this.setAttribute('uv', new BufferAttribute(uvs, 2)); - this.setIndex( new BufferAttribute( indices, 1 ) ); - this.setAttribute( 'position', new BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - - this.computeBoundingSphere(); - -}; + this.computeBoundingSphere(); + } -TeapotGeometry.prototype = Object.create( BufferGeometry.prototype ); -TeapotGeometry.prototype.constructor = TeapotGeometry; +} export { TeapotGeometry };