{“ast”:null,“code”:“function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }nn// Polyfillsnif (Number
.EPSILON === undefined) {n Number
.EPSILON = Math.pow(2, -52);n}nnif (Number.isInteger === undefined) {n // Missing in IEn // developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isIntegern Number.isInteger = function (value) {n return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;n };n} //nnnif (Math.sign === undefined) {n // developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/signn Math.sign = function (x) {n return x < 0 ? -1 : x > 0 ? 1 : +x;n };n}nnif ('name' in Function.prototype === false) {n // Missing in IEn // developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/namen Object.defineProperty(Function.prototype, 'name', {n get: function get() {n return this.toString().match(/^\s*function\s*(*)/)[1];n }n });n}nnif (Object.assign === undefined) {n // Missing in IEn // developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assignn Object.assign = function (target) {n if (target === undefined || target === null) {n throw new TypeError('Cannot convert undefined or null to object');n }nn var output = Object(target);nn for (var index = 1; index < arguments.length; index++) {n var source = arguments;nn if (source !== undefined && source !== null) {n for (var nextKey in source) {n if (Object.prototype.hasOwnProperty.call(source, nextKey)) {n output = source;n }n }n }n }nn return output;n };n}n/**n * github.com/mrdoob/eventdispatcher.js/n */nnnfunction EventDispatcher() {}nnObject.assign(EventDispatcher.prototype, {n addEventListener: function addEventListener(type, listener) {n if (this._listeners === undefined) this._listeners = {};n var listeners = this._listeners;nn if (listeners === undefined) {n listeners = [];n }nn if (listeners.indexOf(listener) === -1) {n listeners.push(listener);n }n },n hasEventListener: function hasEventListener(type, listener) {n if (this._listeners === undefined) return false;n var listeners = this._listeners;n return listeners !== undefined && listeners.indexOf(listener) !== -1;n },n removeEventListener: function removeEventListener(type, listener) {n if (this._listeners === undefined) return;n var listeners = this._listeners;n var listenerArray = listeners;nn if (listenerArray !== undefined) {n var index = listenerArray.indexOf(listener);nn if (index !== -1) {n listenerArray.splice(index, 1);n }n }n },n dispatchEvent: function dispatchEvent(event) {n if (this._listeners === undefined) return;n var listeners = this._listeners;n var listenerArray = listeners;nn if (listenerArray !== undefined) {n event.target = this;n var array = listenerArray.slice(0);nn for (var i = 0, l = array.length; i < l; i++) {n array.call(this, event);n }n }n }n});nvar REVISION = '108';nvar MOUSE = {n LEFT: 0,n MIDDLE: 1,n RIGHT: 2,n ROTATE: 0,n DOLLY: 1,n PAN: 2n};nvar TOUCH = {n ROTATE: 0,n PAN: 1,n DOLLY_PAN: 2,n DOLLY_ROTATE: 3n};nvar CullFaceNone = 0;nvar CullFaceBack = 1;nvar CullFaceFront = 2;nvar CullFaceFrontBack = 3;nvar FrontFaceDirectionCW = 0;nvar FrontFaceDirectionCCW = 1;nvar BasicShadowMap = 0;nvar PCFShadowMap = 1;nvar PCFSoftShadowMap = 2;nvar VSMShadowMap = 3;nvar FrontSide = 0;nvar BackSide = 1;nvar DoubleSide = 2;nvar FlatShading = 1;nvar SmoothShading = 2;nvar NoColors = 0;nvar FaceColors = 1;nvar VertexColors = 2;nvar NoBlending = 0;nvar NormalBlending = 1;nvar AdditiveBlending = 2;nvar SubtractiveBlending = 3;nvar MultiplyBlending = 4;nvar CustomBlending = 5;nvar AddEquation = 100;nvar SubtractEquation = 101;nvar ReverseSubtractEquation = 102;nvar MinEquation = 103;nvar MaxEquation = 104;nvar ZeroFactor = 200;nvar OneFactor = 201;nvar SrcColorFactor = 202;nvar OneMinusSrcColorFactor = 203;nvar SrcAlphaFactor = 204;nvar OneMinusSrcAlphaFactor = 205;nvar DstAlphaFactor = 206;nvar OneMinusDstAlphaFactor = 207;nvar DstColorFactor = 208;nvar OneMinusDstColorFactor = 209;nvar SrcAlphaSaturateFactor = 210;nvar NeverDepth = 0;nvar AlwaysDepth = 1;nvar LessDepth = 2;nvar LessEqualDepth = 3;nvar EqualDepth = 4;nvar GreaterEqualDepth = 5;nvar GreaterDepth = 6;nvar NotEqualDepth = 7;nvar MultiplyOperation = 0;nvar MixOperation = 1;nvar AddOperation = 2;nvar NoToneMapping = 0;nvar LinearToneMapping = 1;nvar ReinhardToneMapping = 2;nvar Uncharted2ToneMapping = 3;nvar CineonToneMapping = 4;nvar ACESFilmicToneMapping = 5;nvar UVMapping = 300;nvar CubeReflectionMapping = 301;nvar CubeRefractionMapping = 302;nvar EquirectangularReflectionMapping = 303;nvar EquirectangularRefractionMapping = 304;nvar SphericalReflectionMapping = 305;nvar CubeUVReflectionMapping = 306;nvar CubeUVRefractionMapping = 307;nvar RepeatWrapping = 1000;nvar ClampToEdgeWrapping = 1001;nvar MirroredRepeatWrapping = 1002;nvar NearestFilter = 1003;nvar NearestMipmapNearestFilter = 1004;nvar NearestMipMapNearestFilter = 1004;nvar NearestMipmapLinearFilter = 1005;nvar NearestMipMapLinearFilter = 1005;nvar LinearFilter = 1006;nvar LinearMipmapNearestFilter = 1007;nvar LinearMipMapNearestFilter = 1007;nvar LinearMipmapLinearFilter = 1008;nvar LinearMipMapLinearFilter = 1008;nvar UnsignedByteType = 1009;nvar ByteType = 1010;nvar ShortType = 1011;nvar UnsignedShortType = 1012;nvar IntType = 1013;nvar UnsignedIntType = 1014;nvar FloatType = 1015;nvar HalfFloatType = 1016;nvar UnsignedShort4444Type = 1017;nvar UnsignedShort5551Type = 1018;nvar UnsignedShort565Type = 1019;nvar UnsignedInt248Type = 1020;nvar AlphaFormat = 1021;nvar RGBFormat = 1022;nvar RGBAFormat = 1023;nvar LuminanceFormat = 1024;nvar LuminanceAlphaFormat = 1025;nvar RGBEFormat = RGBAFormat;nvar DepthFormat = 1026;nvar DepthStencilFormat = 1027;nvar RedFormat = 1028;nvar RGB_S3TC_DXT1_Format = 33776;nvar RGBA_S3TC_DXT1_Format = 33777;nvar RGBA_S3TC_DXT3_Format = 33778;nvar RGBA_S3TC_DXT5_Format = 33779;nvar RGB_PVRTC_4BPPV1_Format = 35840;nvar RGB_PVRTC_2BPPV1_Format = 35841;nvar RGBA_PVRTC_4BPPV1_Format = 35842;nvar RGBA_PVRTC_2BPPV1_Format = 35843;nvar RGB_ETC1_Format = 36196;nvar RGBA_ASTC_4x4_Format = 37808;nvar RGBA_ASTC_5x4_Format = 37809;nvar RGBA_ASTC_5x5_Format = 37810;nvar RGBA_ASTC_6x5_Format = 37811;nvar RGBA_ASTC_6x6_Format = 37812;nvar RGBA_ASTC_8x5_Format = 37813;nvar RGBA_ASTC_8x6_Format = 37814;nvar RGBA_ASTC_8x8_Format = 37815;nvar RGBA_ASTC_10x5_Format = 37816;nvar RGBA_ASTC_10x6_Format = 37817;nvar RGBA_ASTC_10x8_Format = 37818;nvar RGBA_ASTC_10x10_Format = 37819;nvar RGBA_ASTC_12x10_Format = 37820;nvar RGBA_ASTC_12x12_Format = 37821;nvar LoopOnce = 2200;nvar LoopRepeat = 2201;nvar LoopPingPong = 2202;nvar InterpolateDiscrete = 2300;nvar InterpolateLinear = 2301;nvar InterpolateSmooth = 2302;nvar ZeroCurvatureEnding = 2400;nvar ZeroSlopeEnding = 2401;nvar WrapAroundEnding = 2402;nvar TrianglesDrawMode = 0;nvar TriangleStripDrawMode = 1;nvar TriangleFanDrawMode = 2;nvar LinearEncoding = 3000;nvar sRGBEncoding = 3001;nvar GammaEncoding = 3007;nvar RGBEEncoding = 3002;nvar LogLuvEncoding = 3003;nvar RGBM7Encoding = 3004;nvar RGBM16Encoding = 3005;nvar RGBDEncoding = 3006;nvar BasicDepthPacking = 3200;nvar RGBADepthPacking = 3201;nvar TangentSpaceNormalMap = 0;nvar ObjectSpaceNormalMap = 1;nvar ZeroStencilOp = 0;nvar KeepStencilOp = 7680;nvar ReplaceStencilOp = 7681;nvar IncrementStencilOp = 7682;nvar DecrementStencilOp = 7683;nvar IncrementWrapStencilOp = 34055;nvar DecrementWrapStencilOp = 34056;nvar InvertStencilOp = 5386;nvar NeverStencilFunc = 512;nvar LessStencilFunc = 513;nvar EqualStencilFunc = 514;nvar LessEqualStencilFunc = 515;nvar GreaterStencilFunc = 516;nvar NotEqualStencilFunc = 517;nvar GreaterEqualStencilFunc = 518;nvar AlwaysStencilFunc = 519;n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n */nnvar _lut = [];nnfor (var i = 0; i < 256; i++) {n _lut = (i < 16 ? '0' : '') + i.toString(16);n}nnvar _Math = {n DEG2RAD: Math.PI / 180,n RAD2DEG: 180 / Math.PI,n generateUUID: function generateUUID() {n // stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136n var d0 = Math.random() * 0xffffffff | 0;n var d1 = Math.random() * 0xffffffff | 0;n var d2 = Math.random() * 0xffffffff | 0;n var d3 = Math.random() * 0xffffffff | 0;n var 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.nn return uuid.toUpperCase();n },n clamp: function clamp(value, min, max) {n return Math.max(min, Math.min(max, value));n },n // compute euclidian modulo of m % nn // en.wikipedia.org/wiki/Modulo_operationn euclideanModulo: function euclideanModulo(n, m) {n return (n % m + m) % m;n },n // Linear mapping from range <a1, a2> to range <b1, b2>n mapLinear: function mapLinear(x, a1, a2, b1, b2) {n return b1 + (x - a1) * (b2 - b1) / (a2 - a1);n },n // en.wikipedia.org/wiki/Linear_interpolationn lerp: function lerp(x, y, t) {n return (1 - t) * x + t * y;n },n // en.wikipedia.org/wiki/Smoothstepn smoothstep: function smoothstep(x, min, max) {n if (x <= min) return 0;n if (x >= max) return 1;n x = (x - min) / (max - min);n return x * x * (3 - 2 * x);n },n smootherstep: function smootherstep(x, min, max) {n if (x <= min) return 0;n if (x >= max) return 1;n x = (x - min) / (max - min);n return x * x * x * (x * (x * 6 - 15) + 10);n },n // Random integer from <low, high> intervaln randInt: function randInt(low, high) {n return low + Math.floor(Math.random() * (high - low + 1));n },n // Random float from <low, high> intervaln randFloat: function randFloat(low, high) {n return low + Math.random() * (high - low);n },n // Random float from <-range/2, range/2> intervaln randFloatSpread: function randFloatSpread(range) {n return range * (0.5 - Math.random());n },n degToRad: function degToRad(degrees) {n return degrees * _Math.DEG2RAD;n },n radToDeg: function radToDeg(radians) {n return radians * _Math.RAD2DEG;n },n isPowerOfTwo: function isPowerOfTwo(value) {n return (value & value - 1) === 0 && value !== 0;n },n ceilPowerOfTwo: function ceilPowerOfTwo(value) {n return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));n },n floorPowerOfTwo: function floorPowerOfTwo(value) {n return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));n }n};n/**n * @author mrdoob / mrdoob.com/n * @author philogb / blog.thejit.org/n * @author egraether / egraether.com/n * @author zz85 / www.lab4games.net/zz85/blogn */nnfunction Vector2(x, y) {n this.x = x || 0;n this.y = y || 0;n}nnObject.defineProperties(Vector2.prototype, {n "width": {n get: function get() {n return this.x;n },n set: function set(value) {n this.x = value;n }n },n "height": {n get: function get() {n return this.y;n },n set: function set(value) {n this.y = value;n }n }n});nObject.assign(Vector2.prototype, {n isVector2: true,n set: function set(x, y) {n this.x = x;n this.y = y;n return this;n },n setScalar: function setScalar(scalar) {n this.x = scalar;n this.y = scalar;n return this;n },n setX: function setX(x) {n this.x = x;n return this;n },n setY: function setY(y) {n this.y = y;n return this;n },n setComponent: function setComponent(index, value) {n switch (index) {n case 0:n this.x = value;n break;nn case 1:n this.y = value;n break;nn default:n throw new Error('index is out of range: ' + index);n }nn return this;n },n getComponent: function getComponent(index) {n switch (index) {n case 0:n return this.x;nn case 1:n return this.y;nn default:n throw new Error('index is out of range: ' + index);n }n },n clone: function clone() {n return new this.constructor(this.x, this.y);n },n copy: function copy(v) {n this.x = v.x;n this.y = v.y;n return this;n },n add: function add(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');n return this.addVectors(v, w);n }nn this.x += v.x;n this.y += v.y;n return this;n },n addScalar: function addScalar(s) {n this.x += s;n this.y += s;n return this;n },n addVectors: function addVectors(a, b) {n this.x = a.x + b.x;n this.y = a.y + b.y;n return this;n },n addScaledVector: function addScaledVector(v, s) {n this.x += v.x * s;n this.y += v.y * s;n return this;n },n sub: function sub(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');n return this.subVectors(v, w);n }nn this.x -= v.x;n this.y -= v.y;n return this;n },n subScalar: function subScalar(s) {n this.x -= s;n this.y -= s;n return this;n },n subVectors: function subVectors(a, b) {n this.x = a.x - b.x;n this.y = a.y - b.y;n return this;n },n multiply: function multiply(v) {n this.x *= v.x;n this.y *= v.y;n return this;n },n multiplyScalar: function multiplyScalar(scalar) {n this.x *= scalar;n this.y *= scalar;n return this;n },n divide: function divide(v) {n this.x /= v.x;n this.y /= v.y;n return this;n },n divideScalar: function divideScalar(scalar) {n return this.multiplyScalar(1 / scalar);n },n applyMatrix3: function applyMatrix3(m) {n var x = this.x,n y = this.y;n var e = m.elements;n this.x = e * x + e * y + e;n this.y = e * x + e * y + e;n return this;n },n min: function min(v) {n this.x = Math.min(this.x, v.x);n this.y = Math.min(this.y, v.y);n return this;n },n max: function max(v) {n this.x = Math.max(this.x, v.x);n this.y = Math.max(this.y, v.y);n return this;n },n clamp: function clamp(min, max) {n // assumes min < max, componentwisen this.x = Math.max(min.x, Math.min(max.x, this.x));n this.y = Math.max(min.y, Math.min(max.y, this.y));n return this;n },n clampScalar: function clampScalar(minVal, maxVal) {n this.x = Math.max(minVal, Math.min(maxVal, this.x));n this.y = Math.max(minVal, Math.min(maxVal, this.y));n return this;n },n clampLength: function clampLength(min, max) {n var length = this.length();n return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));n },n floor: function floor() {n this.x = Math.floor(this.x);n this.y = Math.floor(this.y);n return this;n },n ceil: function ceil() {n this.x = Math.ceil(this.x);n this.y = Math.ceil(this.y);n return this;n },n round: function round() {n this.x = Math.round(this.x);n this.y = Math.round(this.y);n return this;n },n roundToZero: function roundToZero() {n this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);n this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);n return this;n },n negate: function negate() {n this.x = -this.x;n this.y = -this.y;n return this;n },n dot: function dot(v) {n return this.x * v.x + this.y * v.y;n },n cross: function cross(v) {n return this.x * v.y - this.y * v.x;n },n lengthSq: function lengthSq() {n return this.x * this.x + this.y * this.y;n },n length: function length() {n return Math.sqrt(this.x * this.x + this.y * this.y);n },n manhattanLength: function manhattanLength() {n return Math.abs(this.x) + Math.abs(this.y);n },n normalize: function normalize() {n return this.divideScalar(this.length() || 1);n },n angle: function angle() {n // computes the angle in radians with respect to the positive x-axisn var angle = Math.atan2(this.y, this.x);n if (angle < 0) angle += 2 * Math.PI;n return angle;n },n distanceTo: function distanceTo(v) {n return Math.sqrt(this.distanceToSquared(v));n },n distanceToSquared: function distanceToSquared(v) {n var dx = this.x - v.x,n dy = this.y - v.y;n return dx * dx + dy * dy;n },n manhattanDistanceTo: function manhattanDistanceTo(v) {n return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);n },n setLength: function setLength(length) {n return this.normalize().multiplyScalar(length);n },n lerp: function lerp(v, alpha) {n this.x += (v.x - this.x) * alpha;n this.y += (v.y - this.y) * alpha;n return this;n },n lerpVectors: function lerpVectors(v1, v2, alpha) {n return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);n },n equals: function equals(v) {n return v.x === this.x && v.y === this.y;n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;n this.x = array;n this.y = array[offset + 1];n return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n array = this.x;n array[offset + 1] = this.y;n return array;n },n fromBufferAttribute: function fromBufferAttribute(attribute, index, offset) {n if (offset !== undefined) {n console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');n }nn this.x = attribute.getX(index);n this.y = attribute.getY(index);n return this;n },n rotateAround: function rotateAround(center, angle) {n var c = Math.cos(angle),n s = Math.sin(angle);n var x = this.x - center.x;n var y = this.y - center.y;n this.x = x * c - y * s + center.x;n this.y = x * s + y * c + center.y;n return this;n }n});n/**n * @author mikael emtinger / gomo.se/n * @author alteredq / alteredqualia.com/n * @author WestLangley / github.com/WestLangleyn * @author bhouston / clara.ion */nnfunction Quaternion(x, y, z, w) {n this._x = x || 0;n this._y = y || 0;n this._z = z || 0;n this._w = w !== undefined ? w : 1;n}nnObject.assign(Quaternion, {n slerp: function slerp(qa, qb, qm, t) {n return qm.copy(qa).slerp(qb, t);n },n slerpFlat: function slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {n // fuzz-free, array-based Quaternion SLERP operationn var x0 = src0[srcOffset0 + 0],n y0 = src0[srcOffset0 + 1],n z0 = src0[srcOffset0 + 2],n w0 = src0[srcOffset0 + 3],n x1 = src1[srcOffset1 + 0],n y1 = src1[srcOffset1 + 1],n z1 = src1[srcOffset1 + 2],n w1 = src1[srcOffset1 + 3];nn if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {n var s = 1 - t,n cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,n dir = cos >= 0 ? 1 : -1,n sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:nn if (sqrSin > Number
.EPSILON) {n var sin = Math.sqrt(sqrSin),n len = Math.atan2(sin, cos * dir);n s = Math.sin(s * len) / sin;n t = Math.sin(t * len) / sin;n }nn var tDir = t * dir;n x0 = x0 * s + x1 * tDir;n y0 = y0 * s + y1 * tDir;n z0 = z0 * s + z1 * tDir;n w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:nn if (s === 1 - t) {n var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);n x0 *= f;n y0 *= f;n z0 *= f;n w0 *= f;n }n }nn dst = x0;n dst[dstOffset + 1] = y0;n dst[dstOffset + 2] = z0;n dst[dstOffset + 3] = w0;n }n});nObject.defineProperties(Quaternion.prototype, {n x: {n get: function get() {n return this._x;n },n set: function set(value) {n this._x = value;nn this._onChangeCallback();n }n },n y: {n get: function get() {n return this._y;n },n set: function set(value) {n this._y = value;nn this._onChangeCallback();n }n },n z: {n get: function get() {n return this._z;n },n set: function set(value) {n this._z = value;nn this._onChangeCallback();n }n },n w: {n get: function get() {n return this._w;n },n set: function set(value) {n this._w = value;nn this._onChangeCallback();n }n }n});nObject.assign(Quaternion.prototype, {n isQuaternion: true,n set: function set(x, y, z, w) {n this._x = x;n this._y = y;n this._z = z;n this._w = w;nn this._onChangeCallback();nn return this;n },n clone: function clone() {n return new this.constructor(this._x, this._y, this._z, this._w);n },n copy: function copy(quaternion) {n this._x = quaternion.x;n this._y = quaternion.y;n this._z = quaternion.z;n this._w = quaternion.w;nn this._onChangeCallback();nn return this;n },n setFromEuler: function setFromEuler(euler, update) {n if (!(euler && euler.isEuler)) {n throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');n }nn var x = euler._x,n y = euler._y,n z = euler._z,n order = euler.order; // www.mathworks.com/matlabcentral/fileexchange/n // t20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/n //tcontent/SpinCalc.mnn var cos = Math.cos;n var sin = Math.sin;n var c1 = cos(x / 2);n var c2 = cos(y / 2);n var c3 = cos(z / 2);n var s1 = sin(x / 2);n var s2 = sin(y / 2);n var s3 = sin(z / 2);nn if (order === 'XYZ') {n this._x = s1 * c2 * c3 + c1 * s2 * s3;n this._y = c1 * s2 * c3 - s1 * c2 * s3;n this._z = c1 * c2 * s3 + s1 * s2 * c3;n this._w = c1 * c2 * c3 - s1 * s2 * s3;n } else if (order === 'YXZ') {n this._x = s1 * c2 * c3 + c1 * s2 * s3;n this._y = c1 * s2 * c3 - s1 * c2 * s3;n this._z = c1 * c2 * s3 - s1 * s2 * c3;n this._w = c1 * c2 * c3 + s1 * s2 * s3;n } else if (order === 'ZXY') {n this._x = s1 * c2 * c3 - c1 * s2 * s3;n this._y = c1 * s2 * c3 + s1 * c2 * s3;n this._z = c1 * c2 * s3 + s1 * s2 * c3;n this._w = c1 * c2 * c3 - s1 * s2 * s3;n } else if (order === 'ZYX') {n this._x = s1 * c2 * c3 - c1 * s2 * s3;n this._y = c1 * s2 * c3 + s1 * c2 * s3;n this._z = c1 * c2 * s3 - s1 * s2 * c3;n this._w = c1 * c2 * c3 + s1 * s2 * s3;n } else if (order === 'YZX') {n this._x = s1 * c2 * c3 + c1 * s2 * s3;n this._y = c1 * s2 * c3 + s1 * c2 * s3;n this._z = c1 * c2 * s3 - s1 * s2 * c3;n this._w = c1 * c2 * c3 - s1 * s2 * s3;n } else if (order === 'XZY') {n this._x = s1 * c2 * c3 - c1 * s2 * s3;n this._y = c1 * s2 * c3 - s1 * c2 * s3;n this._z = c1 * c2 * s3 + s1 * s2 * c3;n this._w = c1 * c2 * c3 + s1 * s2 * s3;n }nn if (update !== false) this._onChangeCallback();n return this;n },n setFromAxisAngle: function setFromAxisAngle(axis, angle) {n // www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htmn // assumes axis is normalizedn var halfAngle = angle / 2,n s = Math.sin(halfAngle);n this._x = axis.x * s;n this._y = axis.y * s;n this._z = axis.z * s;n this._w = Math.cos(halfAngle);nn this._onChangeCallback();nn return this;n },n setFromRotationMatrix: function setFromRotationMatrix(m) {n // www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htmn // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)n var te = m.elements,n m11 = te,n m12 = te,n m13 = te,n m21 = te,n m22 = te,n m23 = te,n m31 = te,n m32 = te,n m33 = te,n trace = m11 + m22 + m33,n s;nn if (trace > 0) {n s = 0.5 / Math.sqrt(trace + 1.0);n this._w = 0.25 / s;n this._x = (m32 - m23) * s;n this._y = (m13 - m31) * s;n this._z = (m21 - m12) * s;n } else if (m11 > m22 && m11 > m33) {n s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);n this._w = (m32 - m23) / s;n this._x = 0.25 * s;n this._y = (m12 + m21) / s;n this._z = (m13 + m31) / s;n } else if (m22 > m33) {n s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);n this._w = (m13 - m31) / s;n this._x = (m12 + m21) / s;n this._y = 0.25 * s;n this._z = (m23 + m32) / s;n } else {n s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);n this._w = (m21 - m12) / s;n this._x = (m13 + m31) / s;n this._y = (m23 + m32) / s;n this._z = 0.25 * s;n }nn this._onChangeCallback();nn return this;n },n setFromUnitVectors: function setFromUnitVectors(vFrom, vTo) {n // assumes direction vectors vFrom and vTo are normalizedn var EPS = 0.000001;n var r = vFrom.dot(vTo) + 1;nn if (r < EPS) {n r = 0;nn if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {n this._x = -vFrom.y;n this._y = vFrom.x;n this._z = 0;n this._w = r;n } else {n this._x = 0;n this._y = -vFrom.z;n this._z = vFrom.y;n this._w = r;n }n } else {n // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3n this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;n this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;n this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;n this._w = r;n }nn return this.normalize();n },n angleTo: function angleTo(q) {n return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));n },n rotateTowards: function rotateTowards(q, step) {n var angle = this.angleTo(q);n if (angle === 0) return this;n var t = Math.min(1, step / angle);n this.slerp(q, t);n return this;n },n inverse: function inverse() {n // quaternion is assumed to have unit lengthn return this.conjugate();n },n conjugate: function conjugate() {n this._x *= -1;n this._y *= -1;n this._z *= -1;nn this._onChangeCallback();nn return this;n },n dot: function dot(v) {n return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;n },n lengthSq: function lengthSq() {n return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;n },n length: function length() {n return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);n },n normalize: function normalize() {n var l = this.length();nn if (l === 0) {n this._x = 0;n this._y = 0;n this._z = 0;n this._w = 1;n } else {n l = 1 / l;n this._x = this._x * l;n this._y = this._y * l;n this._z = this._z * l;n this._w = this._w * l;n }nn this._onChangeCallback();nn return this;n },n multiply: function multiply(q, p) {n if (p !== undefined) {n console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');n return this.multiplyQuaternions(q, p);n }nn return this.multiplyQuaternions(this, q);n },n premultiply: function premultiply(q) {n return this.multiplyQuaternions(q, this);n },n multiplyQuaternions: function multiplyQuaternions(a, b) {n // from www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htmn var qax = a._x,n qay = a._y,n qaz = a._z,n qaw = a._w;n var qbx = b._x,n qby = b._y,n qbz = b._z,n qbw = b._w;n this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;n this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;n this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;n this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;nn this._onChangeCallback();nn return this;n },n slerp: function slerp(qb, t) {n if (t === 0) return this;n if (t === 1) return this.copy(qb);n var x = this._x,n y = this._y,n z = this._z,n w = this._w; // www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/nn var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;nn if (cosHalfTheta < 0) {n this._w = -qb._w;n this._x = -qb._x;n this._y = -qb._y;n this._z = -qb._z;n cosHalfTheta = -cosHalfTheta;n } else {n this.copy(qb);n }nn if (cosHalfTheta >= 1.0) {n this._w = w;n this._x = x;n this._y = y;n this._z = z;n return this;n }nn var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;nn if (sqrSinHalfTheta <= Number
.EPSILON) {n var s = 1 - t;n this._w = s * w + t * this._w;n this._x = s * x + t * this._x;n this._y = s * y + t * this._y;n this._z = s * z + t * this._z;n this.normalize();nn this._onChangeCallback();nn return this;n }nn var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);n var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);n var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,n ratioB = Math.sin(t * halfTheta) / sinHalfTheta;n this._w = w * ratioA + this._w * ratioB;n this._x = x * ratioA + this._x * ratioB;n this._y = y * ratioA + this._y * ratioB;n this._z = z * ratioA + this._z * ratioB;nn this._onChangeCallback();nn return this;n },n equals: function equals(quaternion) {n return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;n this._x = array;n this._y = array[offset + 1];n this._z = array[offset + 2];n this._w = array[offset + 3];nn this._onChangeCallback();nn return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n array = this._x;n array[offset + 1] = this._y;n array[offset + 2] = this._z;n array[offset + 3] = this._w;n return array;n },n _onChange: function _onChange(callback) {n this._onChangeCallback = callback;n return this;n },n _onChangeCallback: function _onChangeCallback() {}n});n/**n * @author mrdoob / mrdoob.com/n * @author kile / kile.stravaganza.org/n * @author philogb / blog.thejit.org/n * @author mikael emtinger / gomo.se/n * @author egraether / egraether.com/n * @author WestLangley / github.com/WestLangleyn */nnvar _vector = new Vector3();nnvar _quaternion = new Quaternion();nnfunction Vector3(x, y, z) {n this.x = x || 0;n this.y = y || 0;n this.z = z || 0;n}nnObject.assign(Vector3.prototype, {n isVector3: true,n set: function set(x, y, z) {n this.x = x;n this.y = y;n this.z = z;n return this;n },n setScalar: function setScalar(scalar) {n this.x = scalar;n this.y = scalar;n this.z = scalar;n return this;n },n setX: function setX(x) {n this.x = x;n return this;n },n setY: function setY(y) {n this.y = y;n return this;n },n setZ: function setZ(z) {n this.z = z;n return this;n },n setComponent: function setComponent(index, value) {n switch (index) {n case 0:n this.x = value;n break;nn case 1:n this.y = value;n break;nn case 2:n this.z = value;n break;nn default:n throw new Error('index is out of range: ' + index);n }nn return this;n },n getComponent: function getComponent(index) {n switch (index) {n case 0:n return this.x;nn case 1:n return this.y;nn case 2:n return this.z;nn default:n throw new Error('index is out of range: ' + index);n }n },n clone: function clone() {n return new this.constructor(this.x, this.y, this.z);n },n copy: function copy(v) {n this.x = v.x;n this.y = v.y;n this.z = v.z;n return this;n },n add: function add(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');n return this.addVectors(v, w);n }nn this.x += v.x;n this.y += v.y;n this.z += v.z;n return this;n },n addScalar: function addScalar(s) {n this.x += s;n this.y += s;n this.z += s;n return this;n },n addVectors: function addVectors(a, b) {n this.x = a.x + b.x;n this.y = a.y + b.y;n this.z = a.z + b.z;n return this;n },n addScaledVector: function addScaledVector(v, s) {n this.x += v.x * s;n this.y += v.y * s;n this.z += v.z * s;n return this;n },n sub: function sub(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');n return this.subVectors(v, w);n }nn this.x -= v.x;n this.y -= v.y;n this.z -= v.z;n return this;n },n subScalar: function subScalar(s) {n this.x -= s;n this.y -= s;n this.z -= s;n return this;n },n subVectors: function subVectors(a, b) {n this.x = a.x - b.x;n this.y = a.y - b.y;n this.z = a.z - b.z;n return this;n },n multiply: function multiply(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');n return this.multiplyVectors(v, w);n }nn this.x *= v.x;n this.y *= v.y;n this.z *= v.z;n return this;n },n multiplyScalar: function multiplyScalar(scalar) {n this.x *= scalar;n this.y *= scalar;n this.z *= scalar;n return this;n },n multiplyVectors: function multiplyVectors(a, b) {n this.x = a.x * b.x;n this.y = a.y * b.y;n this.z = a.z * b.z;n return this;n },n applyEuler: function applyEuler(euler) {n if (!(euler && euler.isEuler)) {n console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');n }nn return this.applyQuaternion(_quaternion.setFromEuler(euler));n },n applyAxisAngle: function applyAxisAngle(axis, angle) {n return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));n },n applyMatrix3: function applyMatrix3(m) {n var x = this.x,n y = this.y,n z = this.z;n var e = m.elements;n this.x = e * x + e * y + e * z;n this.y = e * x + e * y + e * z;n this.z = e * x + e * y + e * z;n return this;n },n applyMatrix4: function applyMatrix4(m) {n var x = this.x,n y = this.y,n z = this.z;n var e = m.elements;n var w = 1 / (e * x + e * y + e * z + e);n this.x = (e * x + e * y + e * z + e) * w;n this.y = (e * x + e * y + e * z + e) * w;n this.z = (e * x + e * y + e * z + e) * w;n return this;n },n applyQuaternion: function applyQuaternion(q) {n var x = this.x,n y = this.y,n z = this.z;n var qx = q.x,n qy = q.y,n qz = q.z,n qw = q.w; // calculate quat * vectornn var ix = qw * x + qy * z - qz * y;n var iy = qw * y + qz * x - qx * z;n var iz = qw * z + qx * y - qy * x;n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quatnn this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;n this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;n this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;n return this;n },n project: function project(camera) {n return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);n },n unproject: function unproject(camera) {n return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);n },n transformDirection: function transformDirection(m) {n // input: THREE.Matrix4 affine matrixn // vector interpreted as a directionn var x = this.x,n y = this.y,n z = this.z;n var e = m.elements;n this.x = e * x + e * y + e * z;n this.y = e * x + e * y + e * z;n this.z = e * x + e * y + e * z;n return this.normalize();n },n divide: function divide(v) {n this.x /= v.x;n this.y /= v.y;n this.z /= v.z;n return this;n },n divideScalar: function divideScalar(scalar) {n return this.multiplyScalar(1 / scalar);n },n min: function min(v) {n this.x = Math.min(this.x, v.x);n this.y = Math.min(this.y, v.y);n this.z = Math.min(this.z, v.z);n return this;n },n max: function max(v) {n this.x = Math.max(this.x, v.x);n this.y = Math.max(this.y, v.y);n this.z = Math.max(this.z, v.z);n return this;n },n clamp: function clamp(min, max) {n // assumes min < max, componentwisen this.x = Math.max(min.x, Math.min(max.x, this.x));n this.y = Math.max(min.y, Math.min(max.y, this.y));n this.z = Math.max(min.z, Math.min(max.z, this.z));n return this;n },n clampScalar: function clampScalar(minVal, maxVal) {n this.x = Math.max(minVal, Math.min(maxVal, this.x));n this.y = Math.max(minVal, Math.min(maxVal, this.y));n this.z = Math.max(minVal, Math.min(maxVal, this.z));n return this;n },n clampLength: function clampLength(min, max) {n var length = this.length();n return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));n },n floor: function floor() {n this.x = Math.floor(this.x);n this.y = Math.floor(this.y);n this.z = Math.floor(this.z);n return this;n },n ceil: function ceil() {n this.x = Math.ceil(this.x);n this.y = Math.ceil(this.y);n this.z = Math.ceil(this.z);n return this;n },n round: function round() {n this.x = Math.round(this.x);n this.y = Math.round(this.y);n this.z = Math.round(this.z);n return this;n },n roundToZero: function roundToZero() {n this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);n this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);n this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);n return this;n },n negate: function negate() {n this.x = -this.x;n this.y = -this.y;n this.z = -this.z;n return this;n },n dot: function dot(v) {n return this.x * v.x + this.y * v.y + this.z * v.z;n },n // TODO lengthSquared?n lengthSq: function lengthSq() {n return this.x * this.x + this.y * this.y + this.z * this.z;n },n length: function length() {n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);n },n manhattanLength: function manhattanLength() {n return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);n },n normalize: function normalize() {n return this.divideScalar(this.length() || 1);n },n setLength: function setLength(length) {n return this.normalize().multiplyScalar(length);n },n lerp: function lerp(v, alpha) {n this.x += (v.x - this.x) * alpha;n this.y += (v.y - this.y) * alpha;n this.z += (v.z - this.z) * alpha;n return this;n },n lerpVectors: function lerpVectors(v1, v2, alpha) {n return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);n },n cross: function cross(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');n return this.crossVectors(v, w);n }nn return this.crossVectors(this, v);n },n crossVectors: function crossVectors(a, b) {n var ax = a.x,n ay = a.y,n az = a.z;n var bx = b.x,n by = b.y,n bz = b.z;n this.x = ay * bz - az * by;n this.y = az * bx - ax * bz;n this.z = ax * by - ay * bx;n return this;n },n projectOnVector: function projectOnVector(vector) {n var scalar = vector.dot(this) / vector.lengthSq();n return this.copy(vector).multiplyScalar(scalar);n },n projectOnPlane: function projectOnPlane(planeNormal) {n _vector.copy(this).projectOnVector(planeNormal);nn return this.sub(_vector);n },n reflect: function reflect(normal) {n // reflect incident vector off plane orthogonal to normaln // normal is assumed to have unit lengthn return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));n },n angleTo: function angleTo(v) {n var theta = this.dot(v) / Math.sqrt(this.lengthSq() * v.lengthSq()); // clamp, to handle numerical problemsnn return Math.acos(_Math.clamp(theta, -1, 1));n },n distanceTo: function distanceTo(v) {n return Math.sqrt(this.distanceToSquared(v));n },n distanceToSquared: function distanceToSquared(v) {n var dx = this.x - v.x,n dy = this.y - v.y,n dz = this.z - v.z;n return dx * dx + dy * dy + dz * dz;n },n manhattanDistanceTo: function manhattanDistanceTo(v) {n return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);n },n setFromSpherical: function setFromSpherical(s) {n return this.setFromSphericalCoords(s.radius, s.phi, s.theta);n },n setFromSphericalCoords: function setFromSphericalCoords(radius, phi, theta) {n var sinPhiRadius = Math.sin(phi) * radius;n this.x = sinPhiRadius * Math.sin(theta);n this.y = Math.cos(phi) * radius;n this.z = sinPhiRadius * Math.cos(theta);n return this;n },n setFromCylindrical: function setFromCylindrical© {n return this.setFromCylindricalCoords(c.radius, c.theta, c.y);n },n setFromCylindricalCoords: function setFromCylindricalCoords(radius, theta, y) {n this.x = radius * Math.sin(theta);n this.y = y;n this.z = radius * Math.cos(theta);n return this;n },n setFromMatrixPosition: function setFromMatrixPosition(m) {n var e = m.elements;n this.x = e;n this.y = e;n this.z = e;n return this;n },n setFromMatrixScale: function setFromMatrixScale(m) {n var sx = this.setFromMatrixColumn(m, 0).length();n var sy = this.setFromMatrixColumn(m, 1).length();n var sz = this.setFromMatrixColumn(m, 2).length();n this.x = sx;n this.y = sy;n this.z = sz;n return this;n },n setFromMatrixColumn: function setFromMatrixColumn(m, index) {n return this.fromArray(m.elements, index * 4);n },n equals: function equals(v) {n return v.x === this.x && v.y === this.y && v.z === this.z;n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;n this.x = array;n this.y = array[offset + 1];n this.z = array[offset + 2];n return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n array = this.x;n array[offset + 1] = this.y;n array[offset + 2] = this.z;n return array;n },n fromBufferAttribute: function fromBufferAttribute(attribute, index, offset) {n if (offset !== undefined) {n console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');n }nn this.x = attribute.getX(index);n this.y = attribute.getY(index);n this.z = attribute.getZ(index);n return this;n }n});n/**n * @author alteredq / alteredqualia.com/n * @author WestLangley / github.com/WestLangleyn * @author bhouston / clara.ion * @author tschwn */nnvar _vector$1 = new Vector3();nnfunction Matrix3() {n this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];nn if (arguments.length > 0) {n console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');n }n}nnObject.assign(Matrix3.prototype, {n isMatrix3: true,n set: function set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {n var te = this.elements;n te = n11;n te = n21;n te = n31;n te = n12;n te = n22;n te = n32;n te = n13;n te = n23;n te = n33;n return this;n },n identity: function identity() {n this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);n return this;n },n clone: function clone() {n return new this.constructor().fromArray(this.elements);n },n copy: function copy(m) {n var te = this.elements;n var me = m.elements;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n return this;n },n setFromMatrix4: function setFromMatrix4(m) {n var me = m.elements;n this.set(me, me, me, me, me, me, me, me, me);n return this;n },n applyToBufferAttribute: function applyToBufferAttribute(attribute) {n for (var i = 0, l = attribute.count; i < l; i++) {n _vector$1.x = attribute.getX(i);n _vector$1.y = attribute.getY(i);n _vector$1.z = attribute.getZ(i);nn _vector$1.applyMatrix3(this);nn attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);n }nn return attribute;n },n multiply: function multiply(m) {n return this.multiplyMatrices(this, m);n },n premultiply: function premultiply(m) {n return this.multiplyMatrices(m, this);n },n multiplyMatrices: function multiplyMatrices(a, b) {n var ae = a.elements;n var be = b.elements;n var te = this.elements;n var a11 = ae,n a12 = ae,n a13 = ae;n var a21 = ae,n a22 = ae,n a23 = ae;n var a31 = ae,n a32 = ae,n a33 = ae;n var b11 = be,n b12 = be,n b13 = be;n var b21 = be,n b22 = be,n b23 = be;n var b31 = be,n b32 = be,n b33 = be;n te = a11 * b11 + a12 * b21 + a13 * b31;n te = a11 * b12 + a12 * b22 + a13 * b32;n te = a11 * b13 + a12 * b23 + a13 * b33;n te = a21 * b11 + a22 * b21 + a23 * b31;n te = a21 * b12 + a22 * b22 + a23 * b32;n te = a21 * b13 + a22 * b23 + a23 * b33;n te = a31 * b11 + a32 * b21 + a33 * b31;n te = a31 * b12 + a32 * b22 + a33 * b32;n te = a31 * b13 + a32 * b23 + a33 * b33;n return this;n },n multiplyScalar: function multiplyScalar(s) {n var te = this.elements;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n return this;n },n determinant: function determinant() {n var te = this.elements;n var a = te,n b = te,n c = te,n d = te,n e = te,n f = te,n g = te,n h = te,n i = te;n return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;n },n getInverse: function getInverse(matrix, throwOnDegenerate) {n if (matrix && matrix.isMatrix4) {n console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");n }nn var me = matrix.elements,n te = this.elements,n n11 = me,n n21 = me,n n31 = me,n n12 = me,n n22 = me,n n32 = me,n n13 = me,n n23 = me,n n33 = me,n t11 = n33 * n22 - n32 * n23,n t12 = n32 * n13 - n33 * n12,n t13 = n23 * n12 - n22 * n13,n det = n11 * t11 + n21 * t12 + n31 * t13;nn if (det === 0) {n var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";nn if (throwOnDegenerate === true) {n throw new Error(msg);n } else {n console.warn(msg);n }nn return this.identity();n }nn var detInv = 1 / det;n te = t11 * detInv;n te = (n31 * n23 - n33 * n21) * detInv;n te = (n32 * n21 - n31 * n22) * detInv;n te = t12 * detInv;n te = (n33 * n11 - n31 * n13) * detInv;n te = (n31 * n12 - n32 * n11) * detInv;n te = t13 * detInv;n te = (n21 * n13 - n23 * n11) * detInv;n te = (n22 * n11 - n21 * n12) * detInv;n return this;n },n transpose: function transpose() {n var tmp,n m = this.elements;n tmp = m;n m = m;n m = tmp;n tmp = m;n m = m;n m = tmp;n tmp = m;n m = m;n m = tmp;n return this;n },n getNormalMatrix: function getNormalMatrix(matrix4) {n return this.setFromMatrix4(matrix4).getInverse(this).transpose();n },n transposeIntoArray: function transposeIntoArray® {n var m = this.elements;n r = m;n r = m;n r = m;n r = m;n r = m;n r = m;n r = m;n r = m;n r = m;n return this;n },n setUvTransform: function setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {n var c = Math.cos(rotation);n var s = Math.sin(rotation);n this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);n },n scale: function scale(sx, sy) {n var te = this.elements;n te *= sx;n te *= sx;n te *= sx;n te *= sy;n te *= sy;n te *= sy;n return this;n },n rotate: function rotate(theta) {n var c = Math.cos(theta);n var s = Math.sin(theta);n var te = this.elements;n var a11 = te,n a12 = te,n a13 = te;n var a21 = te,n a22 = te,n a23 = te;n te = c * a11 + s * a21;n te = c * a12 + s * a22;n te = c * a13 + s * a23;n te = -s * a11 + c * a21;n te = -s * a12 + c * a22;n te = -s * a13 + c * a23;n return this;n },n translate: function translate(tx, ty) {n var te = this.elements;n te += tx * te;n te += tx * te;n te += tx * te;n te += ty * te;n te += ty * te;n te += ty * te;n return this;n },n equals: function equals(matrix) {n var te = this.elements;n var me = matrix.elements;nn for (var i = 0; i < 9; i++) {n if (te !== me) return false;n }nn return true;n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;nn for (var i = 0; i < 9; i++) {n this.elements = array[i + offset];n }nn return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n var te = this.elements;n array = te;n array[offset + 1] = te;n array[offset + 2] = te;n array[offset + 3] = te;n array[offset + 4] = te;n array[offset + 5] = te;n array[offset + 6] = te;n array[offset + 7] = te;n array[offset + 8] = te;n return array;n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n * @author szimek / github.com/szimek/n */nnvar _canvas;nnvar ImageUtils = {n getDataURL: function getDataURL(image) {n var canvas;nn if (typeof HTMLCanvasElement == 'undefined') {n return image.src;n } else if (image instanceof HTMLCanvasElement) {n canvas = image;n } else {n if (_canvas === undefined) _canvas = document.createElementNS('www.w3.org/1999/xhtml', 'canvas');n _canvas.width = image.width;n _canvas.height = image.height;nn var context = _canvas.getContext('2d');nn if (image instanceof ImageData) {n context.putImageData(image, 0, 0);n } else {n context.drawImage(image, 0, 0, image.width, image.height);n }nn canvas = _canvas;n }nn if (canvas.width > 2048 || canvas.height > 2048) {n return canvas.toDataURL('image/jpeg', 0.6);n } else {n return canvas.toDataURL('image/png');n }n }n};n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n * @author szimek / github.com/szimek/n */nnvar textureId = 0;nnfunction Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {n Object.defineProperty(this, 'id', {n value: textureId++n });n this.uuid = _Math.generateUUID();n this.name = '';n this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;n this.mipmaps = [];n this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;n this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;n this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;n this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;n this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;n this.anisotropy = anisotropy !== undefined ? anisotropy : 1;n this.format = format !== undefined ? format : RGBAFormat;n this.type = type !== undefined ? type : UnsignedByteType;n this.offset = new Vector2(0, 0);n this.repeat = new Vector2(1, 1);n this.center = new Vector2(0, 0);n this.rotation = 0;n this.matrixAutoUpdate = true;n this.matrix = new Matrix3();n this.generateMipmaps = true;n this.premultiplyAlpha = false;n this.flipY = true;n this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)n // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.n //n // Also changing the encoding after already used by a Material will not automatically make the Materialn // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.nn this.encoding = encoding !== undefined ? encoding : LinearEncoding;n this.version = 0;n this.onUpdate = null;n}nnTexture.DEFAULT_IMAGE = undefined;nTexture.DEFAULT_MAPPING = UVMapping;nTexture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {n constructor: Texture,n isTexture: true,n updateMatrix: function updateMatrix() {n this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(source) {n this.name = source.name;n this.image = source.image;n this.mipmaps = source.mipmaps.slice(0);n this.mapping = source.mapping;n this.wrapS = source.wrapS;n this.wrapT = source.wrapT;n this.magFilter = source.magFilter;n this.minFilter = source.minFilter;n this.anisotropy = source.anisotropy;n this.format = source.format;n this.type = source.type;n this.offset.copy(source.offset);n this.repeat.copy(source.repeat);n this.center.copy(source.center);n this.rotation = source.rotation;n this.matrixAutoUpdate = source.matrixAutoUpdate;n this.matrix.copy(source.matrix);n this.generateMipmaps = source.generateMipmaps;n this.premultiplyAlpha = source.premultiplyAlpha;n this.flipY = source.flipY;n this.unpackAlignment = source.unpackAlignment;n this.encoding = source.encoding;n return this;n },n toJSON: function toJSON(meta) {n var isRootObject = meta === undefined || typeof meta === 'string';nn if (!isRootObject && meta.textures !== undefined) {n return meta.textures;n }nn var output = {n metadata: {n version: 4.5,n type: 'Texture',n generator: 'Texture.toJSON'n },n uuid: this.uuid,n name: this.name,n mapping: this.mapping,n repeat: [this.repeat.x, this.repeat.y],n offset: [this.offset.x, this.offset.y],n center: [this.center.x, this.center.y],n rotation: this.rotation,n wrap: [this.wrapS, this.wrapT],n format: this.format,n type: this.type,n encoding: this.encoding,n minFilter: this.minFilter,n magFilter: this.magFilter,n anisotropy: this.anisotropy,n flipY: this.flipY,n premultiplyAlpha: this.premultiplyAlpha,n unpackAlignment: this.unpackAlignmentn };nn if (this.image !== undefined) {n // TODO: Move to THREE.Imagen var image = this.image;nn if (image.uuid === undefined) {n image.uuid = _Math.generateUUID(); // UGHn }nn if (!isRootObject && meta.images === undefined) {n var url;nn if (Array.isArray(image)) {n // process array of images e.g. CubeTexturen url = [];nn for (var i = 0, l = image.length; i < l; i++) {n url.push(ImageUtils.getDataURL(image));n }n } else {n // process single imagen url = ImageUtils.getDataURL(image);n }nn meta.images = {n uuid: image.uuid,n url: urln };n }nn output.image = image.uuid;n }nn if (!isRootObject) {n meta.textures = output;n }nn return output;n },n dispose: function dispose() {n this.dispatchEvent({n type: 'dispose'n });n },n transformUv: function transformUv(uv) {n if (this.mapping !== UVMapping) return uv;n uv.applyMatrix3(this.matrix);nn if (uv.x < 0 || uv.x > 1) {n switch (this.wrapS) {n case RepeatWrapping:n uv.x = uv.x - Math.floor(uv.x);n break;nn case ClampToEdgeWrapping:n uv.x = uv.x < 0 ? 0 : 1;n break;nn case MirroredRepeatWrapping:n if (Math.abs(Math.floor(uv.x) % 2) === 1) {n uv.x = Math.ceil(uv.x) - uv.x;n } else {n uv.x = uv.x - Math.floor(uv.x);n }nn break;n }n }nn if (uv.y < 0 || uv.y > 1) {n switch (this.wrapT) {n case RepeatWrapping:n uv.y = uv.y - Math.floor(uv.y);n break;nn case ClampToEdgeWrapping:n uv.y = uv.y < 0 ? 0 : 1;n break;nn case MirroredRepeatWrapping:n if (Math.abs(Math.floor(uv.y) % 2) === 1) {n uv.y = Math.ceil(uv.y) - uv.y;n } else {n uv.y = uv.y - Math.floor(uv.y);n }nn break;n }n }nn if (this.flipY) {n uv.y = 1 - uv.y;n }nn return uv;n }n});nObject.defineProperty(Texture.prototype, "needsUpdate", {n set: function set(value) {n if (value === true) this.version++;n }n});n/**n * @author supereggbert / www.paulbrunt.co.uk/n * @author philogb / blog.thejit.org/n * @author mikael emtinger / gomo.se/n * @author egraether / egraether.com/n * @author WestLangley / github.com/WestLangleyn */nnfunction Vector4(x, y, z, w) {n this.x = x || 0;n this.y = y || 0;n this.z = z || 0;n this.w = w !== undefined ? w : 1;n}nnObject.defineProperties(Vector4.prototype, {n "width": {n get: function get() {n return this.z;n },n set: function set(value) {n this.z = value;n }n },n "height": {n get: function get() {n return this.w;n },n set: function set(value) {n this.w = value;n }n }n});nObject.assign(Vector4.prototype, {n isVector4: true,n set: function set(x, y, z, w) {n this.x = x;n this.y = y;n this.z = z;n this.w = w;n return this;n },n setScalar: function setScalar(scalar) {n this.x = scalar;n this.y = scalar;n this.z = scalar;n this.w = scalar;n return this;n },n setX: function setX(x) {n this.x = x;n return this;n },n setY: function setY(y) {n this.y = y;n return this;n },n setZ: function setZ(z) {n this.z = z;n return this;n },n setW: function setW(w) {n this.w = w;n return this;n },n setComponent: function setComponent(index, value) {n switch (index) {n case 0:n this.x = value;n break;nn case 1:n this.y = value;n break;nn case 2:n this.z = value;n break;nn case 3:n this.w = value;n break;nn default:n throw new Error('index is out of range: ' + index);n }nn return this;n },n getComponent: function getComponent(index) {n switch (index) {n case 0:n return this.x;nn case 1:n return this.y;nn case 2:n return this.z;nn case 3:n return this.w;nn default:n throw new Error('index is out of range: ' + index);n }n },n clone: function clone() {n return new this.constructor(this.x, this.y, this.z, this.w);n },n copy: function copy(v) {n this.x = v.x;n this.y = v.y;n this.z = v.z;n this.w = v.w !== undefined ? v.w : 1;n return this;n },n add: function add(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');n return this.addVectors(v, w);n }nn this.x += v.x;n this.y += v.y;n this.z += v.z;n this.w += v.w;n return this;n },n addScalar: function addScalar(s) {n this.x += s;n this.y += s;n this.z += s;n this.w += s;n return this;n },n addVectors: function addVectors(a, b) {n this.x = a.x + b.x;n this.y = a.y + b.y;n this.z = a.z + b.z;n this.w = a.w + b.w;n return this;n },n addScaledVector: function addScaledVector(v, s) {n this.x += v.x * s;n this.y += v.y * s;n this.z += v.z * s;n this.w += v.w * s;n return this;n },n sub: function sub(v, w) {n if (w !== undefined) {n console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');n return this.subVectors(v, w);n }nn this.x -= v.x;n this.y -= v.y;n this.z -= v.z;n this.w -= v.w;n return this;n },n subScalar: function subScalar(s) {n this.x -= s;n this.y -= s;n this.z -= s;n this.w -= s;n return this;n },n subVectors: function subVectors(a, b) {n this.x = a.x - b.x;n this.y = a.y - b.y;n this.z = a.z - b.z;n this.w = a.w - b.w;n return this;n },n multiplyScalar: function multiplyScalar(scalar) {n this.x *= scalar;n this.y *= scalar;n this.z *= scalar;n this.w *= scalar;n return this;n },n applyMatrix4: function applyMatrix4(m) {n var x = this.x,n y = this.y,n z = this.z,n w = this.w;n var e = m.elements;n this.x = e * x + e * y + e * z + e * w;n this.y = e * x + e * y + e * z + e * w;n this.z = e * x + e * y + e * z + e * w;n this.w = e * x + e * y + e * z + e * w;n return this;n },n divideScalar: function divideScalar(scalar) {n return this.multiplyScalar(1 / scalar);n },n setAxisAngleFromQuaternion: function setAxisAngleFromQuaternion(q) {n // www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htmn // q is assumed to be normalizedn this.w = 2 * Math.acos(q.w);n var s = Math.sqrt(1 - q.w * q.w);nn if (s < 0.0001) {n this.x = 1;n this.y = 0;n this.z = 0;n } else {n this.x = q.x / s;n this.y = q.y / s;n this.z = q.z / s;n }nn return this;n },n setAxisAngleFromRotationMatrix: function setAxisAngleFromRotationMatrix(m) {n // www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htmn // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)n var angle,n x,n y,n z,n // variables for resultn epsilon = 0.01,n // margin to allow for rounding errorsn epsilon2 = 0.1,n // margin to distinguish between 0 and 180 degreesn te = m.elements,n m11 = te,n m12 = te,n m13 = te,n m21 = te,n m22 = te,n m23 = te,n m31 = te,n m32 = te,n m33 = te;nn if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {n // singularity foundn // first check for identity matrix which must have +1 for all termsn // in leading diagonal and zero in other termsn if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {n // this singularity is identity matrix so angle = 0n this.set(1, 0, 0, 0);n return this; // zero angle, arbitrary axisn } // otherwise this singularity is angle = 180nnn angle = Math.PI;n var xx = (m11 + 1) / 2;n var yy = (m22 + 1) / 2;n var zz = (m33 + 1) / 2;n var xy = (m12 + m21) / 4;n var xz = (m13 + m31) / 4;n var yz = (m23 + m32) / 4;nn if (xx > yy && xx > zz) {n // m11 is the largest diagonal termn if (xx < epsilon) {n x = 0;n y = 0.707106781;n z = 0.707106781;n } else {n x = Math.sqrt(xx);n y = xy / x;n z = xz / x;n }n } else if (yy > zz) {n // m22 is the largest diagonal termn if (yy < epsilon) {n x = 0.707106781;n y = 0;n z = 0.707106781;n } else {n y = Math.sqrt(yy);n x = xy / y;n z = yz / y;n }n } else {n // m33 is the largest diagonal term so base result on thisn if (zz < epsilon) {n x = 0.707106781;n y = 0.707106781;n z = 0;n } else {n z = Math.sqrt(zz);n x = xz / z;n y = yz / z;n }n }nn this.set(x, y, z, angle);n return this; // return 180 deg rotationn } // as we have reached here there are no singularities so we can handle normallynnn var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalizenn if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should ben // caught by singularity test above, but I've left it in just in casenn this.x = (m32 - m23) / s;n this.y = (m13 - m31) / s;n this.z = (m21 - m12) / s;n this.w = Math.acos((m11 + m22 + m33 - 1) / 2);n return this;n },n min: function min(v) {n this.x = Math.min(this.x, v.x);n this.y = Math.min(this.y, v.y);n this.z = Math.min(this.z, v.z);n this.w = Math.min(this.w, v.w);n return this;n },n max: function max(v) {n this.x = Math.max(this.x, v.x);n this.y = Math.max(this.y, v.y);n this.z = Math.max(this.z, v.z);n this.w = Math.max(this.w, v.w);n return this;n },n clamp: function clamp(min, max) {n // assumes min < max, componentwisen this.x = Math.max(min.x, Math.min(max.x, this.x));n this.y = Math.max(min.y, Math.min(max.y, this.y));n this.z = Math.max(min.z, Math.min(max.z, this.z));n this.w = Math.max(min.w, Math.min(max.w, this.w));n return this;n },n clampScalar: function clampScalar(minVal, maxVal) {n this.x = Math.max(minVal, Math.min(maxVal, this.x));n this.y = Math.max(minVal, Math.min(maxVal, this.y));n this.z = Math.max(minVal, Math.min(maxVal, this.z));n this.w = Math.max(minVal, Math.min(maxVal, this.w));n return this;n },n clampLength: function clampLength(min, max) {n var length = this.length();n return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));n },n floor: function floor() {n this.x = Math.floor(this.x);n this.y = Math.floor(this.y);n this.z = Math.floor(this.z);n this.w = Math.floor(this.w);n return this;n },n ceil: function ceil() {n this.x = Math.ceil(this.x);n this.y = Math.ceil(this.y);n this.z = Math.ceil(this.z);n this.w = Math.ceil(this.w);n return this;n },n round: function round() {n this.x = Math.round(this.x);n this.y = Math.round(this.y);n this.z = Math.round(this.z);n this.w = Math.round(this.w);n return this;n },n roundToZero: function roundToZero() {n this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);n this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);n this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);n this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);n return this;n },n negate: function negate() {n this.x = -this.x;n this.y = -this.y;n this.z = -this.z;n this.w = -this.w;n return this;n },n dot: function dot(v) {n return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;n },n lengthSq: function lengthSq() {n return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;n },n length: function length() {n return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);n },n manhattanLength: function manhattanLength() {n return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);n },n normalize: function normalize() {n return this.divideScalar(this.length() || 1);n },n setLength: function setLength(length) {n return this.normalize().multiplyScalar(length);n },n lerp: function lerp(v, alpha) {n this.x += (v.x - this.x) * alpha;n this.y += (v.y - this.y) * alpha;n this.z += (v.z - this.z) * alpha;n this.w += (v.w - this.w) * alpha;n return this;n },n lerpVectors: function lerpVectors(v1, v2, alpha) {n return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);n },n equals: function equals(v) {n return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;n this.x = array;n this.y = array[offset + 1];n this.z = array[offset + 2];n this.w = array[offset + 3];n return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n array = this.x;n array[offset + 1] = this.y;n array[offset + 2] = this.z;n array[offset + 3] = this.w;n return array;n },n fromBufferAttribute: function fromBufferAttribute(attribute, index, offset) {n if (offset !== undefined) {n console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');n }nn this.x = attribute.getX(index);n this.y = attribute.getY(index);n this.z = attribute.getZ(index);n this.w = attribute.getW(index);n return this;n }n});n/**n * @author szimek / github.com/szimek/n * @author alteredq / alteredqualia.com/n * @author Marius Kintel / github.com/kinteln */nn/*n In options, we can specify:n * Texture parameters for an auto-generated target texturen * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffersn*/nnfunction WebGLRenderTarget(width, height, options) {n this.width = width;n this.height = height;n this.scissor = new Vector4(0, 0, width, height);n this.scissorTest = false;n this.viewport = new Vector4(0, 0, width, height);n options = options || {};n this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);n this.texture.image = {};n this.texture.image.width = width;n this.texture.image.height = height;n this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;n this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;n this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;n this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;n this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;n}nnWebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {n constructor: WebGLRenderTarget,n isWebGLRenderTarget: true,n setSize: function setSize(width, height) {n if (this.width !== width || this.height !== height) {n this.width = width;n this.height = height;n this.texture.image.width = width;n this.texture.image.height = height;n this.dispose();n }nn this.viewport.set(0, 0, width, height);n this.scissor.set(0, 0, width, height);n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(source) {n this.width = source.width;n this.height = source.height;n this.viewport.copy(source.viewport);n this.texture = source.texture.clone();n this.depthBuffer = source.depthBuffer;n this.stencilBuffer = source.stencilBuffer;n this.depthTexture = source.depthTexture;n return this;n },n dispose: function dispose() {n this.dispatchEvent({n type: 'dispose'n });n }n});n/**n * @author Mugen87 / github.com/Mugen87n * @author Matt DesLauriers / @mattdesln */nnfunction WebGLMultisampleRenderTarget(width, height, options) {n WebGLRenderTarget.call(this, width, height, options);n this.samples = 4;n}nnWebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {n constructor: WebGLMultisampleRenderTarget,n isWebGLMultisampleRenderTarget: true,n copy: function copy(source) {n WebGLRenderTarget.prototype.copy.call(this, source);n this.samples = source.samples;n return this;n }n});nnvar _v1 = new Vector3();nnvar _m1 = new Matrix4();nnvar _zero = new Vector3(0, 0, 0);nnvar _one = new Vector3(1, 1, 1);nnvar _x = new Vector3();nnvar _y = new Vector3();nnvar _z = new Vector3();n/**n * @author mrdoob / mrdoob.com/n * @author supereggbert / www.paulbrunt.co.uk/n * @author philogb / blog.thejit.org/n * @author jordi_ros / plattsoft.comn * @author D1plo1d / github.com/D1plo1dn * @author alteredq / alteredqualia.com/n * @author mikael emtinger / gomo.se/n * @author timknip / www.floorplanner.com/n * @author bhouston / clara.ion * @author WestLangley / github.com/WestLangleyn */nnnfunction Matrix4() {n this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];nn if (arguments.length > 0) {n console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');n }n}nnObject.assign(Matrix4.prototype, {n isMatrix4: true,n set: function set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {n var te = this.elements;n te = n11;n te = n12;n te = n13;n te = n14;n te = n21;n te = n22;n te = n23;n te = n24;n te = n31;n te = n32;n te = n33;n te = n34;n te = n41;n te = n42;n te = n43;n te = n44;n return this;n },n identity: function identity() {n this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);n return this;n },n clone: function clone() {n return new Matrix4().fromArray(this.elements);n },n copy: function copy(m) {n var te = this.elements;n var me = m.elements;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n te = me;n return this;n },n copyPosition: function copyPosition(m) {n var te = this.elements,n me = m.elements;n te = me;n te = me;n te = me;n return this;n },n extractBasis: function extractBasis(xAxis, yAxis, zAxis) {n xAxis.setFromMatrixColumn(this, 0);n yAxis.setFromMatrixColumn(this, 1);n zAxis.setFromMatrixColumn(this, 2);n return this;n },n makeBasis: function makeBasis(xAxis, yAxis, zAxis) {n 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);n return this;n },n extractRotation: function extractRotation(m) {n // this method does not support reflection matricesn var te = this.elements;n var me = m.elements;nn var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();nn var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();nn var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();nn te = me * scaleX;n te = me * scaleX;n te = me * scaleX;n te = 0;n te = me * scaleY;n te = me * scaleY;n te = me * scaleY;n te = 0;n te = me * scaleZ;n te = me * scaleZ;n te = me * scaleZ;n te = 0;n te = 0;n te = 0;n te = 0;n te = 1;n return this;n },n makeRotationFromEuler: function makeRotationFromEuler(euler) {n if (!(euler && euler.isEuler)) {n console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');n }nn var te = this.elements;n var x = euler.x,n y = euler.y,n z = euler.z;n var a = Math.cos(x),n b = Math.sin(x);n var c = Math.cos(y),n d = Math.sin(y);n var e = Math.cos(z),n f = Math.sin(z);nn if (euler.order === 'XYZ') {n var ae = a * e,n af = a * f,n be = b * e,n bf = b * f;n te = c * e;n te = -c * f;n te = d;n te = af + be * d;n te = ae - bf * d;n te = -b * c;n te = bf - ae * d;n te = be + af * d;n te = a * c;n } else if (euler.order === 'YXZ') {n var ce = c * e,n cf = c * f,n de = d * e,n df = d * f;n te = ce + df * b;n te = de * b - cf;n te = a * d;n te = a * f;n te = a * e;n te = -b;n te = cf * b - de;n te = df + ce * b;n te = a * c;n } else if (euler.order === 'ZXY') {n var ce = c * e,n cf = c * f,n de = d * e,n df = d * f;n te = ce - df * b;n te = -a * f;n te = de + cf * b;n te = cf + de * b;n te = a * e;n te = df - ce * b;n te = -a * d;n te = b;n te = a * c;n } else if (euler.order === 'ZYX') {n var ae = a * e,n af = a * f,n be = b * e,n bf = b * f;n te = c * e;n te = be * d - af;n te = ae * d + bf;n te = c * f;n te = bf * d + ae;n te = af * d - be;n te = -d;n te = b * c;n te = a * c;n } else if (euler.order === 'YZX') {n var ac = a * c,n ad = a * d,n bc = b * c,n bd = b * d;n te = c * e;n te = bd - ac * f;n te = bc * f + ad;n te = f;n te = a * e;n te = -b * e;n te = -d * e;n te = ad * f + bc;n te = ac - bd * f;n } else if (euler.order === 'XZY') {n var ac = a * c,n ad = a * d,n bc = b * c,n bd = b * d;n te = c * e;n te = -f;n te = d * e;n te = ac * f + bd;n te = a * e;n te = ad * f - bc;n te = bc * f - ad;n te = b * e;n te = bd * f + ac;n } // bottom rownnn te = 0;n te = 0;n te = 0; // last columnnn te = 0;n te = 0;n te = 0;n te = 1;n return this;n },n makeRotationFromQuaternion: function makeRotationFromQuaternion(q) {n return this.compose(_zero, q, _one);n },n lookAt: function lookAt(eye, target, up) {n var te = this.elements;nn _z.subVectors(eye, target);nn if (_z.lengthSq() === 0) {n // eye and target are in the same positionn _z.z = 1;n }nn _z.normalize();nn _x.crossVectors(up, _z);nn if (_x.lengthSq() === 0) {n // up and z are paralleln if (Math.abs(up.z) === 1) {n _z.x += 0.0001;n } else {n _z.z += 0.0001;n }nn _z.normalize();nn _x.crossVectors(up, _z);n }nn _x.normalize();nn _y.crossVectors(_z, _x);nn te = _x.x;n te = _y.x;n te = _z.x;n te = _x.y;n te = _y.y;n te = _z.y;n te = _x.z;n te = _y.z;n te = _z.z;n return this;n },n multiply: function multiply(m, n) {n if (n !== undefined) {n console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');n return this.multiplyMatrices(m, n);n }nn return this.multiplyMatrices(this, m);n },n premultiply: function premultiply(m) {n return this.multiplyMatrices(m, this);n },n multiplyMatrices: function multiplyMatrices(a, b) {n var ae = a.elements;n var be = b.elements;n var te = this.elements;n var a11 = ae,n a12 = ae,n a13 = ae,n a14 = ae;n var a21 = ae,n a22 = ae,n a23 = ae,n a24 = ae;n var a31 = ae,n a32 = ae,n a33 = ae,n a34 = ae;n var a41 = ae,n a42 = ae,n a43 = ae,n a44 = ae;n var b11 = be,n b12 = be,n b13 = be,n b14 = be;n var b21 = be,n b22 = be,n b23 = be,n b24 = be;n var b31 = be,n b32 = be,n b33 = be,n b34 = be;n var b41 = be,n b42 = be,n b43 = be,n b44 = be;n te = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;n te = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;n te = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;n te = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;n te = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;n te = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;n te = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;n te = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;n te = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;n te = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;n te = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;n te = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;n te = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;n te = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;n te = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;n te = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;n return this;n },n multiplyScalar: function multiplyScalar(s) {n var te = this.elements;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n te *= s;n return this;n },n applyToBufferAttribute: function applyToBufferAttribute(attribute) {n for (var i = 0, l = attribute.count; i < l; i++) {n _v1.x = attribute.getX(i);n _v1.y = attribute.getY(i);n _v1.z = attribute.getZ(i);nn _v1.applyMatrix4(this);nn attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);n }nn return attribute;n },n determinant: function determinant() {n var te = this.elements;n var n11 = te,n n12 = te,n n13 = te,n n14 = te;n var n21 = te,n n22 = te,n n23 = te,n n24 = te;n var n31 = te,n n32 = te,n n33 = te,n n34 = te;n var n41 = te,n n42 = te,n n43 = te,n n44 = te; //TODO: make this more efficientn //( based on www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )nn 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);n },n transpose: function transpose() {n var te = this.elements;n var tmp;n tmp = te;n te = te;n te = tmp;n tmp = te;n te = te;n te = tmp;n tmp = te;n te = te;n te = tmp;n tmp = te;n te = te;n te = tmp;n tmp = te;n te = te;n te = tmp;n tmp = te;n te = te;n te = tmp;n return this;n },n setPosition: function setPosition(x, y, z) {n var te = this.elements;nn if (x.isVector3) {n te = x.x;n te = x.y;n te = x.z;n } else {n te = x;n te = y;n te = z;n }nn return this;n },n getInverse: function getInverse(m, throwOnDegenerate) {n // based on www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htmn var te = this.elements,n me = m.elements,n n11 = me,n n21 = me,n n31 = me,n n41 = me,n n12 = me,n n22 = me,n n32 = me,n n42 = me,n n13 = me,n n23 = me,n n33 = me,n n43 = me,n n14 = me,n n24 = me,n n34 = me,n n44 = me,n t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,n t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,n t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,n t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;n var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;nn if (det === 0) {n var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";nn if (throwOnDegenerate === true) {n throw new Error(msg);n } else {n console.warn(msg);n }nn return this.identity();n }nn var detInv = 1 / det;n te = t11 * detInv;n te = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;n te = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;n te = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;n te = t12 * detInv;n te = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;n te = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;n te = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;n te = t13 * detInv;n te = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;n te = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;n te = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;n te = t14 * detInv;n te = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;n te = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;n te = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;n return this;n },n scale: function scale(v) {n var te = this.elements;n var x = v.x,n y = v.y,n z = v.z;n te *= x;n te *= y;n te *= z;n te *= x;n te *= y;n te *= z;n te *= x;n te *= y;n te *= z;n te *= x;n te *= y;n te *= z;n return this;n },n getMaxScaleOnAxis: function getMaxScaleOnAxis() {n var te = this.elements;n var scaleXSq = te * te + te * te + te * te;n var scaleYSq = te * te + te * te + te * te;n var scaleZSq = te * te + te * te + te * te;n return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));n },n makeTranslation: function makeTranslation(x, y, z) {n this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);n return this;n },n makeRotationX: function makeRotationX(theta) {n var c = Math.cos(theta),n s = Math.sin(theta);n this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);n return this;n },n makeRotationY: function makeRotationY(theta) {n var c = Math.cos(theta),n s = Math.sin(theta);n this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);n return this;n },n makeRotationZ: function makeRotationZ(theta) {n var c = Math.cos(theta),n s = Math.sin(theta);n this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);n return this;n },n makeRotationAxis: function makeRotationAxis(axis, angle) {n // Based on www.gamedev.net/reference/articles/article1199.aspn var c = Math.cos(angle);n var s = Math.sin(angle);n var t = 1 - c;n var x = axis.x,n y = axis.y,n z = axis.z;n var tx = t * x,n ty = t * y;n this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);n return this;n },n makeScale: function makeScale(x, y, z) {n this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);n return this;n },n makeShear: function makeShear(x, y, z) {n this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);n return this;n },n compose: function compose(position, quaternion, scale) {n var te = this.elements;n var x = quaternion._x,n y = quaternion._y,n z = quaternion._z,n w = quaternion._w;n var x2 = x + x,n y2 = y + y,n z2 = z + z;n var xx = x * x2,n xy = x * y2,n xz = x * z2;n var yy = y * y2,n yz = y * z2,n zz = z * z2;n var wx = w * x2,n wy = w * y2,n wz = w * z2;n var sx = scale.x,n sy = scale.y,n sz = scale.z;n te = (1 - (yy + zz)) * sx;n te = (xy + wz) * sx;n te = (xz - wy) * sx;n te = 0;n te = (xy - wz) * sy;n te = (1 - (xx + zz)) * sy;n te = (yz + wx) * sy;n te = 0;n te = (xz + wy) * sz;n te = (yz - wx) * sz;n te = (1 - (xx + yy)) * sz;n te = 0;n te = position.x;n te = position.y;n te = position.z;n te = 1;n return this;n },n decompose: function decompose(position, quaternion, scale) {n var te = this.elements;nn var sx = _v1.set(te, te, te).length();nn var sy = _v1.set(te, te, te).length();nn var sz = _v1.set(te, te, te).length(); // if determine is negative, we need to invert one scalennn var det = this.determinant();n if (det < 0) sx = -sx;n position.x = te;n position.y = te;n position.z = te; // scale the rotation partnn _m1.copy(this);nn var invSX = 1 / sx;n var invSY = 1 / sy;n var invSZ = 1 / sz;n _m1.elements *= invSX;n _m1.elements *= invSX;n _m1.elements *= invSX;n _m1.elements *= invSY;n _m1.elements *= invSY;n _m1.elements *= invSY;n _m1.elements *= invSZ;n _m1.elements *= invSZ;n _m1.elements *= invSZ;n quaternion.setFromRotationMatrix(_m1);n scale.x = sx;n scale.y = sy;n scale.z = sz;n return this;n },n makePerspective: function makePerspective(left, right, top, bottom, near, far) {n if (far === undefined) {n console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');n }nn var te = this.elements;n var x = 2 * near / (right - left);n var y = 2 * near / (top - bottom);n var a = (right + left) / (right - left);n var b = (top + bottom) / (top - bottom);n var c = -(far + near) / (far - near);n var d = -2 * far * near / (far - near);n te = x;n te = 0;n te = a;n te = 0;n te = 0;n te = y;n te = b;n te = 0;n te = 0;n te = 0;n te = c;n te = d;n te = 0;n te = 0;n te = -1;n te = 0;n return this;n },n makeOrthographic: function makeOrthographic(left, right, top, bottom, near, far) {n var te = this.elements;n var w = 1.0 / (right - left);n var h = 1.0 / (top - bottom);n var p = 1.0 / (far - near);n var x = (right + left) * w;n var y = (top + bottom) * h;n var z = (far + near) * p;n te = 2 * w;n te = 0;n te = 0;n te = -x;n te = 0;n te = 2 * h;n te = 0;n te = -y;n te = 0;n te = 0;n te = -2 * p;n te = -z;n te = 0;n te = 0;n te = 0;n te = 1;n return this;n },n equals: function equals(matrix) {n var te = this.elements;n var me = matrix.elements;nn for (var i = 0; i < 16; i++) {n if (te !== me) return false;n }nn return true;n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;nn for (var i = 0; i < 16; i++) {n this.elements = array[i + offset];n }nn return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n var te = this.elements;n array = te;n array[offset + 1] = te;n array[offset + 2] = te;n array[offset + 3] = te;n array[offset + 4] = te;n array[offset + 5] = te;n array[offset + 6] = te;n array[offset + 7] = te;n array[offset + 8] = te;n array[offset + 9] = te;n array[offset + 10] = te;n array[offset + 11] = te;n array[offset + 12] = te;n array[offset + 13] = te;n array[offset + 14] = te;n array[offset + 15] = te;n return array;n }n});n/**n * @author mrdoob / mrdoob.com/n * @author WestLangley / github.com/WestLangleyn * @author bhouston / clara.ion */nnvar _matrix = new Matrix4();nnvar _quaternion$1 = new Quaternion();nnfunction Euler(x, y, z, order) {n this._x = x || 0;n this._y = y || 0;n this._z = z || 0;n this._order = order || Euler.DefaultOrder;n}nnEuler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];nEuler.DefaultOrder = 'XYZ';nObject.defineProperties(Euler.prototype, {n x: {n get: function get() {n return this._x;n },n set: function set(value) {n this._x = value;nn this._onChangeCallback();n }n },n y: {n get: function get() {n return this._y;n },n set: function set(value) {n this._y = value;nn this._onChangeCallback();n }n },n z: {n get: function get() {n return this._z;n },n set: function set(value) {n this._z = value;nn this._onChangeCallback();n }n },n order: {n get: function get() {n return this._order;n },n set: function set(value) {n this._order = value;nn this._onChangeCallback();n }n }n});nObject.assign(Euler.prototype, {n isEuler: true,n set: function set(x, y, z, order) {n this._x = x;n this._y = y;n this._z = z;n this._order = order || this._order;nn this._onChangeCallback();nn return this;n },n clone: function clone() {n return new this.constructor(this._x, this._y, this._z, this._order);n },n copy: function copy(euler) {n this._x = euler._x;n this._y = euler._y;n this._z = euler._z;n this._order = euler._order;nn this._onChangeCallback();nn return this;n },n setFromRotationMatrix: function setFromRotationMatrix(m, order, update) {n var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)nn var te = m.elements;n var m11 = te,n m12 = te,n m13 = te;n var m21 = te,n m22 = te,n m23 = te;n var m31 = te,n m32 = te,n m33 = te;n order = order || this._order;nn if (order === 'XYZ') {n this._y = Math.asin(clamp(m13, -1, 1));nn if (Math.abs(m13) < 0.9999999) {n this._x = Math.atan2(-m23, m33);n this._z = Math.atan2(-m12, m11);n } else {n this._x = Math.atan2(m32, m22);n this._z = 0;n }n } else if (order === 'YXZ') {n this._x = Math.asin(-clamp(m23, -1, 1));nn if (Math.abs(m23) < 0.9999999) {n this._y = Math.atan2(m13, m33);n this._z = Math.atan2(m21, m22);n } else {n this._y = Math.atan2(-m31, m11);n this._z = 0;n }n } else if (order === 'ZXY') {n this._x = Math.asin(clamp(m32, -1, 1));nn if (Math.abs(m32) < 0.9999999) {n this._y = Math.atan2(-m31, m33);n this._z = Math.atan2(-m12, m22);n } else {n this._y = 0;n this._z = Math.atan2(m21, m11);n }n } else if (order === 'ZYX') {n this._y = Math.asin(-clamp(m31, -1, 1));nn if (Math.abs(m31) < 0.9999999) {n this._x = Math.atan2(m32, m33);n this._z = Math.atan2(m21, m11);n } else {n this._x = 0;n this._z = Math.atan2(-m12, m22);n }n } else if (order === 'YZX') {n this._z = Math.asin(clamp(m21, -1, 1));nn if (Math.abs(m21) < 0.9999999) {n this._x = Math.atan2(-m23, m22);n this._y = Math.atan2(-m31, m11);n } else {n this._x = 0;n this._y = Math.atan2(m13, m33);n }n } else if (order === 'XZY') {n this._z = Math.asin(-clamp(m12, -1, 1));nn if (Math.abs(m12) < 0.9999999) {n this._x = Math.atan2(m32, m22);n this._y = Math.atan2(m13, m11);n } else {n this._x = Math.atan2(-m23, m33);n this._y = 0;n }n } else {n console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);n }nn this._order = order;n if (update !== false) this._onChangeCallback();n return this;n },n setFromQuaternion: function setFromQuaternion(q, order, update) {n _matrix.makeRotationFromQuaternion(q);nn return this.setFromRotationMatrix(_matrix, order, update);n },n setFromVector3: function setFromVector3(v, order) {n return this.set(v.x, v.y, v.z, order || this._order);n },n reorder: function reorder(newOrder) {n // WARNING: this discards revolution information -bhoustonn _quaternion$1.setFromEuler(this);nn return this.setFromQuaternion(_quaternion$1, newOrder);n },n equals: function equals(euler) {n return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;n },n fromArray: function fromArray(array) {n this._x = array;n this._y = array;n this._z = array;n if (array !== undefined) this._order = array;nn this._onChangeCallback();nn return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n array = this._x;n array[offset + 1] = this._y;n array[offset + 2] = this._z;n array[offset + 3] = this._order;n return array;n },n toVector3: function toVector3(optionalResult) {n if (optionalResult) {n return optionalResult.set(this._x, this._y, this._z);n } else {n return new Vector3(this._x, this._y, this._z);n }n },n _onChange: function _onChange(callback) {n this._onChangeCallback = callback;n return this;n },n _onChangeCallback: function _onChangeCallback() {}n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction Layers() {n this.mask = 1 | 0;n}nnObject.assign(Layers.prototype, {n set: function set(channel) {n this.mask = 1 << channel | 0;n },n enable: function enable(channel) {n this.mask |= 1 << channel | 0;n },n enableAll: function enableAll() {n this.mask = 0xffffffff | 0;n },n toggle: function toggle(channel) {n this.mask ^= 1 << channel | 0;n },n disable: function disable(channel) {n this.mask &= ~(1 << channel | 0);n },n disableAll: function disableAll() {n this.mask = 0;n },n test: function test(layers) {n return (this.mask & layers.mask) !== 0;n }n});nvar _object3DId = 0;nnvar _v1$1 = new Vector3();nnvar _q1 = new Quaternion();nnvar _m1$1 = new Matrix4();nnvar _target = new Vector3();nnvar _position = new Vector3();nnvar _scale = new Vector3();nnvar _quaternion$2 = new Quaternion();nnvar _xAxis = new Vector3(1, 0, 0);nnvar _yAxis = new Vector3(0, 1, 0);nnvar _zAxis = new Vector3(0, 0, 1);nnvar _addedEvent = {n type: 'added'n};nvar _removedEvent = {n type: 'removed'n};n/**n * @author mrdoob / mrdoob.com/n * @author mikael emtinger / gomo.se/n * @author alteredq / alteredqualia.com/n * @author WestLangley / github.com/WestLangleyn * @author elephantatwork / www.elephantatwork.chn */nnfunction Object3D() {n Object.defineProperty(this, 'id', {n value: _object3DId++n });n this.uuid = _Math.generateUUID();n this.name = '';n this.type = 'Object3D';n this.parent = null;n this.children = [];n this.up = Object3D.DefaultUp.clone();n var position = new Vector3();n var rotation = new Euler();n var quaternion = new Quaternion();n var scale = new Vector3(1, 1, 1);nn function onRotationChange() {n quaternion.setFromEuler(rotation, false);n }nn function onQuaternionChange() {n rotation.setFromQuaternion(quaternion, undefined, false);n }nn rotation._onChange(onRotationChange);nn quaternion._onChange(onQuaternionChange);nn Object.defineProperties(this, {n position: {n configurable: true,n enumerable: true,n value: positionn },n rotation: {n configurable: true,n enumerable: true,n value: rotationn },n quaternion: {n configurable: true,n enumerable: true,n value: quaternionn },n scale: {n configurable: true,n enumerable: true,n value: scalen },n modelViewMatrix: {n value: new Matrix4()n },n normalMatrix: {n value: new Matrix3()n }n });n this.matrix = new Matrix4();n this.matrixWorld = new Matrix4();n this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;n this.matrixWorldNeedsUpdate = false;n this.layers = new Layers();n this.visible = true;n this.castShadow = false;n this.receiveShadow = false;n this.frustumCulled = true;n this.renderOrder = 0;n this.userData = {};n}nnObject3D.DefaultUp = new Vector3(0, 1, 0);nObject3D.DefaultMatrixAutoUpdate = true;nObject3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {n constructor: Object3D,n isObject3D: true,n onBeforeRender: function onBeforeRender() {},n onAfterRender: function onAfterRender() {},n applyMatrix: function applyMatrix(matrix) {n if (this.matrixAutoUpdate) this.updateMatrix();n this.matrix.premultiply(matrix);n this.matrix.decompose(this.position, this.quaternion, this.scale);n },n applyQuaternion: function applyQuaternion(q) {n this.quaternion.premultiply(q);n return this;n },n setRotationFromAxisAngle: function setRotationFromAxisAngle(axis, angle) {n // assumes axis is normalizedn this.quaternion.setFromAxisAngle(axis, angle);n },n setRotationFromEuler: function setRotationFromEuler(euler) {n this.quaternion.setFromEuler(euler, true);n },n setRotationFromMatrix: function setRotationFromMatrix(m) {n // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)n this.quaternion.setFromRotationMatrix(m);n },n setRotationFromQuaternion: function setRotationFromQuaternion(q) {n // assumes q is normalizedn this.quaternion.copy(q);n },n rotateOnAxis: function rotateOnAxis(axis, angle) {n // rotate object on axis in object spacen // axis is assumed to be normalizedn _q1.setFromAxisAngle(axis, angle);nn this.quaternion.multiply(_q1);n return this;n },n rotateOnWorldAxis: function rotateOnWorldAxis(axis, angle) {n // rotate object on axis in world spacen // axis is assumed to be normalizedn // method assumes no rotated parentn _q1.setFromAxisAngle(axis, angle);nn this.quaternion.premultiply(_q1);n return this;n },n rotateX: function rotateX(angle) {n return this.rotateOnAxis(_xAxis, angle);n },n rotateY: function rotateY(angle) {n return this.rotateOnAxis(_yAxis, angle);n },n rotateZ: function rotateZ(angle) {n return this.rotateOnAxis(_zAxis, angle);n },n translateOnAxis: function translateOnAxis(axis, distance) {n // translate object by distance along axis in object spacen // axis is assumed to be normalizedn _v1$1.copy(axis).applyQuaternion(this.quaternion);nn this.position.add(_v1$1.multiplyScalar(distance));n return this;n },n translateX: function translateX(distance) {n return this.translateOnAxis(_xAxis, distance);n },n translateY: function translateY(distance) {n return this.translateOnAxis(_yAxis, distance);n },n translateZ: function translateZ(distance) {n return this.translateOnAxis(_zAxis, distance);n },n localToWorld: function localToWorld(vector) {n return vector.applyMatrix4(this.matrixWorld);n },n worldToLocal: function worldToLocal(vector) {n return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));n },n lookAt: function lookAt(x, y, z) {n // This method does not support objects having non-uniformly-scaled parent(s)n if (x.isVector3) {n _target.copy(x);n } else {n _target.set(x, y, z);n }nn var parent = this.parent;n this.updateWorldMatrix(true, false);nn _position.setFromMatrixPosition(this.matrixWorld);nn if (this.isCamera || this.isLight) {n _m1$1.lookAt(_position, _target, this.up);n } else {n _m1$1.lookAt(_target, _position, this.up);n }nn this.quaternion.setFromRotationMatrix(_m1$1);nn if (parent) {n _m1$1.extractRotation(parent.matrixWorld);nn _q1.setFromRotationMatrix(_m1$1);nn this.quaternion.premultiply(_q1.inverse());n }n },n add: function add(object) {n if (arguments.length > 1) {n for (var i = 0; i < arguments.length; i++) {n this.add(arguments);n }nn return this;n }nn if (object === this) {n console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);n return this;n }nn if (object && object.isObject3D) {n if (object.parent !== null) {n object.parent.remove(object);n }nn object.parent = this;n this.children.push(object);n object.dispatchEvent(_addedEvent);n } else {n console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);n }nn return this;n },n remove: function remove(object) {n if (arguments.length > 1) {n for (var i = 0; i < arguments.length; i++) {n this.remove(arguments);n }nn return this;n }nn var index = this.children.indexOf(object);nn if (index !== -1) {n object.parent = null;n this.children.splice(index, 1);n object.dispatchEvent(_removedEvent);n }nn return this;n },n attach: function attach(object) {n // adds object as a child of this, while maintaining the object's world transformn this.updateWorldMatrix(true, false);nn _m1$1.getInverse(this.matrixWorld);nn if (object.parent !== null) {n object.parent.updateWorldMatrix(true, false);nn _m1$1.multiply(object.parent.matrixWorld);n }nn object.applyMatrix(_m1$1);n object.updateWorldMatrix(false, false);n this.add(object);n return this;n },n getObjectById: function getObjectById(id) {n return this.getObjectByProperty('id', id);n },n getObjectByName: function getObjectByName(name) {n return this.getObjectByProperty('name', name);n },n getObjectByProperty: function getObjectByProperty(name, value) {n if (this === value) return this;nn for (var i = 0, l = this.children.length; i < l; i++) {n var child = this.children;n var object = child.getObjectByProperty(name, value);nn if (object !== undefined) {n return object;n }n }nn return undefined;n },n getWorldPosition: function getWorldPosition(target) {n if (target === undefined) {n console.warn('THREE.Object3D: .getWorldPosition() target is now required');n target = new Vector3();n }nn this.updateMatrixWorld(true);n return target.setFromMatrixPosition(this.matrixWorld);n },n getWorldQuaternion: function getWorldQuaternion(target) {n if (target === undefined) {n console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');n target = new Quaternion();n }nn this.updateMatrixWorld(true);n this.matrixWorld.decompose(_position, target, _scale);n return target;n },n getWorldScale: function getWorldScale(target) {n if (target === undefined) {n console.warn('THREE.Object3D: .getWorldScale() target is now required');n target = new Vector3();n }nn this.updateMatrixWorld(true);n this.matrixWorld.decompose(_position, _quaternion$2, target);n return target;n },n getWorldDirection: function getWorldDirection(target) {n if (target === undefined) {n console.warn('THREE.Object3D: .getWorldDirection() target is now required');n target = new Vector3();n }nn this.updateMatrixWorld(true);n var e = this.matrixWorld.elements;n return target.set(e, e, e).normalize();n },n raycast: function raycast() {},n traverse: function traverse(callback) {n callback(this);n var children = this.children;nn for (var i = 0, l = children.length; i < l; i++) {n children.traverse(callback);n }n },n traverseVisible: function traverseVisible(callback) {n if (this.visible === false) return;n callback(this);n var children = this.children;nn for (var i = 0, l = children.length; i < l; i++) {n children.traverseVisible(callback);n }n },n traverseAncestors: function traverseAncestors(callback) {n var parent = this.parent;nn if (parent !== null) {n callback(parent);n parent.traverseAncestors(callback);n }n },n updateMatrix: function updateMatrix() {n this.matrix.compose(this.position, this.quaternion, this.scale);n this.matrixWorldNeedsUpdate = true;n },n updateMatrixWorld: function updateMatrixWorld(force) {n if (this.matrixAutoUpdate) this.updateMatrix();nn if (this.matrixWorldNeedsUpdate || force) {n if (this.parent === null) {n this.matrixWorld.copy(this.matrix);n } else {n this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);n }nn this.matrixWorldNeedsUpdate = false;n force = true;n } // update childrennnn var children = this.children;nn for (var i = 0, l = children.length; i < l; i++) {n children.updateMatrixWorld(force);n }n },n updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {n var parent = this.parent;nn if (updateParents === true && parent !== null) {n parent.updateWorldMatrix(true, false);n }nn if (this.matrixAutoUpdate) this.updateMatrix();nn if (this.parent === null) {n this.matrixWorld.copy(this.matrix);n } else {n this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);n } // update childrennnn if (updateChildren === true) {n var children = this.children;nn for (var i = 0, l = children.length; i < l; i++) {n children.updateWorldMatrix(false, true);n }n }n },n toJSON: function toJSON(meta) {n // meta is a string when called from JSON.stringifyn var isRootObject = meta === undefined || typeof meta === 'string';n var output = {}; // meta is a hash used to collect geometries, materials.n // not providing it implies that this is the root objectn // being serialized.nn if (isRootObject) {n // initialize meta objn meta = {n geometries: {},n materials: {},n textures: {},n images: {},n shapes: {}n };n output.metadata = {n version: 4.5,n type: 'Object',n generator: 'Object3D.toJSON'n };n } // standard Object3D serializationnnn var object = {};n object.uuid = this.uuid;n object.type = this.type;n if (this.name !== '') object.name = this.name;n if (this.castShadow === true) object.castShadow = true;n if (this.receiveShadow === true) object.receiveShadow = true;n if (this.visible === false) object.visible = false;n if (this.frustumCulled === false) object.frustumCulled = false;n if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;n if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;n object.layers = this.layers.mask;n object.matrix = this.matrix.toArray();n if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific propertiesnn if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //nn function serialize(library, element) {n if (library === undefined) {n library = element.toJSON(meta);n }nn return element.uuid;n }nn if (this.isMesh || this.isLine || this.isPoints) {n object.geometry = serialize(meta.geometries, this.geometry);n var parameters = this.geometry.parameters;nn if (parameters !== undefined && parameters.shapes !== undefined) {n var shapes = parameters.shapes;nn if (Array.isArray(shapes)) {n for (var i = 0, l = shapes.length; i < l; i++) {n var shape = shapes;n serialize(meta.shapes, shape);n }n } else {n serialize(meta.shapes, shapes);n }n }n }nn if (this.material !== undefined) {n if (Array.isArray(this.material)) {n var uuids = [];nn for (var i = 0, l = this.material.length; i < l; i++) {n uuids.push(serialize(meta.materials, this.material));n }nn object.material = uuids;n } else {n object.material = serialize(meta.materials, this.material);n }n } //nnn if (this.children.length > 0) {n object.children = [];nn for (var i = 0; i < this.children.length; i++) {n object.children.push(this.children.toJSON(meta).object);n }n }nn if (isRootObject) {n var geometries = extractFromCache(meta.geometries);n var materials = extractFromCache(meta.materials);n var textures = extractFromCache(meta.textures);n var images = extractFromCache(meta.images);n var shapes = extractFromCache(meta.shapes);n if (geometries.length > 0) output.geometries = geometries;n if (materials.length > 0) output.materials = materials;n if (textures.length > 0) output.textures = textures;n if (images.length > 0) output.images = images;n if (shapes.length > 0) output.shapes = shapes;n }nn output.object = object;n return output; // extract data from the cache hashn // remove metadata on each itemn // and return as arraynn function extractFromCache(cache) {n var values = [];nn for (var key in cache) {n var data = cache;n delete data.metadata;n values.push(data);n }nn return values;n }n },n clone: function clone(recursive) {n return new this.constructor().copy(this, recursive);n },n copy: function copy(source, recursive) {n if (recursive === undefined) recursive = true;n this.name = source.name;n this.up.copy(source.up);n this.position.copy(source.position);n this.quaternion.copy(source.quaternion);n this.scale.copy(source.scale);n this.matrix.copy(source.matrix);n this.matrixWorld.copy(source.matrixWorld);n this.matrixAutoUpdate = source.matrixAutoUpdate;n this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;n this.layers.mask = source.layers.mask;n this.visible = source.visible;n this.castShadow = source.castShadow;n this.receiveShadow = source.receiveShadow;n this.frustumCulled = source.frustumCulled;n this.renderOrder = source.renderOrder;n this.userData = JSON.parse(JSON.stringify(source.userData));nn if (recursive === true) {n for (var i = 0; i < source.children.length; i++) {n var child = source.children;n this.add(child.clone());n }n }nn return this;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction Scene() {n Object3D.call(this);n this.type = 'Scene';n this.background = null;n this.fog = null;n this.overrideMaterial = null;n this.autoUpdate = true; // checked by the renderernn if (typeof THREE_DEVTOOLS !== 'undefined') {n THREE_DEVTOOLS.dispatchEvent(new CustomEvent('observe', {n detail: thisn })); // eslint-disable-line no-undefnn }n}nnScene.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Scene,n isScene: true,n copy: function copy(source, recursive) {n Object3D.prototype.copy.call(this, source, recursive);n if (source.background !== null) this.background = source.background.clone();n if (source.fog !== null) this.fog = source.fog.clone();n if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();n this.autoUpdate = source.autoUpdate;n this.matrixAutoUpdate = source.matrixAutoUpdate;n return this;n },n toJSON: function toJSON(meta) {n var data = Object3D.prototype.toJSON.call(this, meta);n if (this.background !== null) data.object.background = this.background.toJSON(meta);n if (this.fog !== null) data.object.fog = this.fog.toJSON();n return data;n },n dispose: function dispose() {n this.dispatchEvent({n type: 'dispose'n });n }n});nvar _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];nnvar _vector$2 = new Vector3(); // triangle centered verticesnnnvar _v0 = new Vector3();nnvar _v1$2 = new Vector3();nnvar _v2 = new Vector3(); // triangle edge vectorsnnnvar _f0 = new Vector3();nnvar _f1 = new Vector3();nnvar _f2 = new Vector3();nnvar _center = new Vector3();nnvar _extents = new Vector3();nnvar _triangleNormal = new Vector3();nnvar _testAxis = new Vector3();n/**n * @author bhouston / clara.ion * @author WestLangley / github.com/WestLangleyn */nnnfunction Box3(min, max) {n this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);n this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);n}nnObject.assign(Box3.prototype, {n isBox3: true,n set: function set(min, max) {n this.min.copy(min);n this.max.copy(max);n return this;n },n setFromArray: function setFromArray(array) {n var minX = +Infinity;n var minY = +Infinity;n var minZ = +Infinity;n var maxX = -Infinity;n var maxY = -Infinity;n var maxZ = -Infinity;nn for (var i = 0, l = array.length; i < l; i += 3) {n var x = array;n var y = array[i + 1];n var z = array[i + 2];n if (x < minX) minX = x;n if (y < minY) minY = y;n if (z < minZ) minZ = z;n if (x > maxX) maxX = x;n if (y > maxY) maxY = y;n if (z > maxZ) maxZ = z;n }nn this.min.set(minX, minY, minZ);n this.max.set(maxX, maxY, maxZ);n return this;n },n setFromBufferAttribute: function setFromBufferAttribute(attribute) {n var minX = +Infinity;n var minY = +Infinity;n var minZ = +Infinity;n var maxX = -Infinity;n var maxY = -Infinity;n var maxZ = -Infinity;nn for (var i = 0, l = attribute.count; i < l; i++) {n var x = attribute.getX(i);n var y = attribute.getY(i);n var z = attribute.getZ(i);n if (x < minX) minX = x;n if (y < minY) minY = y;n if (z < minZ) minZ = z;n if (x > maxX) maxX = x;n if (y > maxY) maxY = y;n if (z > maxZ) maxZ = z;n }nn this.min.set(minX, minY, minZ);n this.max.set(maxX, maxY, maxZ);n return this;n },n setFromPoints: function setFromPoints(points) {n this.makeEmpty();nn for (var i = 0, il = points.length; i < il; i++) {n this.expandByPoint(points);n }nn return this;n },n setFromCenterAndSize: function setFromCenterAndSize(center, size) {n var halfSize = _vector$2.copy(size).multiplyScalar(0.5);nn this.min.copy(center).sub(halfSize);n this.max.copy(center).add(halfSize);n return this;n },n setFromObject: function setFromObject(object) {n this.makeEmpty();n return this.expandByObject(object);n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(box) {n this.min.copy(box.min);n this.max.copy(box.max);n return this;n },n makeEmpty: function makeEmpty() {n this.min.x = this.min.y = this.min.z = +Infinity;n this.max.x = this.max.y = this.max.z = -Infinity;n return this;n },n isEmpty: function isEmpty() {n // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axesn return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;n },n getCenter: function getCenter(target) {n if (target === undefined) {n console.warn('THREE.Box3: .getCenter() target is now required');n target = new Vector3();n }nn return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);n },n getSize: function getSize(target) {n if (target === undefined) {n console.warn('THREE.Box3: .getSize() target is now required');n target = new Vector3();n }nn return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);n },n expandByPoint: function expandByPoint(point) {n this.min.min(point);n this.max.max(point);n return this;n },n expandByVector: function expandByVector(vector) {n this.min.sub(vector);n this.max.add(vector);n return this;n },n expandByScalar: function expandByScalar(scalar) {n this.min.addScalar(-scalar);n this.max.addScalar(scalar);n return this;n },n expandByObject: function expandByObject(object) {n var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),n // accounting for both the object's, and children's, world transformsnn object.updateWorldMatrix(false, false);n var geometry = object.geometry;nn if (geometry !== undefined) {n if (geometry.isGeometry) {n var vertices = geometry.vertices;nn for (i = 0, l = vertices.length; i < l; i++) {n _vector$2.copy(vertices);nn _vector$2.applyMatrix4(object.matrixWorld);nn this.expandByPoint(_vector$2);n }n } else if (geometry.isBufferGeometry) {n var attribute = geometry.attributes.position;nn if (attribute !== undefined) {n for (i = 0, l = attribute.count; i < l; i++) {n _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);nn this.expandByPoint(_vector$2);n }n }n }n } //nnn var children = object.children;nn for (i = 0, l = children.length; i < l; i++) {n this.expandByObject(children);n }nn return this;n },n containsPoint: function containsPoint(point) {n 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;n },n containsBox: function containsBox(box) {n 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;n },n getParameter: function getParameter(point, target) {n // This can potentially have a divide by zero if the boxn // has a size dimension of 0.n if (target === undefined) {n console.warn('THREE.Box3: .getParameter() target is now required');n target = new Vector3();n }nn 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));n },n intersectsBox: function intersectsBox(box) {n // using 6 splitting planes to rule out intersections.n 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;n },n intersectsSphere: function intersectsSphere(sphere) {n // Find the point on the AABB closest to the sphere center.n this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.nn return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;n },n intersectsPlane: function intersectsPlane(plane) {n // We compute the minimum and maximum dot product values. If those valuesn // are on the same side (back or front) of the plane, then there is no intersection.n var min, max;nn if (plane.normal.x > 0) {n min = plane.normal.x * this.min.x;n max = plane.normal.x * this.max.x;n } else {n min = plane.normal.x * this.max.x;n max = plane.normal.x * this.min.x;n }nn if (plane.normal.y > 0) {n min += plane.normal.y * this.min.y;n max += plane.normal.y * this.max.y;n } else {n min += plane.normal.y * this.max.y;n max += plane.normal.y * this.min.y;n }nn if (plane.normal.z > 0) {n min += plane.normal.z * this.min.z;n max += plane.normal.z * this.max.z;n } else {n min += plane.normal.z * this.max.z;n max += plane.normal.z * this.min.z;n }nn return min <= -plane.constant && max >= -plane.constant;n },n intersectsTriangle: function intersectsTriangle(triangle) {n if (this.isEmpty()) {n return false;n } // compute box center and extentsnnn this.getCenter(_center);nn _extents.subVectors(this.max, _center); // translate triangle to aabb originnnn _v0.subVectors(triangle.a, _center);nn _v1$2.subVectors(triangle.b, _center);nn _v2.subVectors(triangle.c, _center); // compute edge vectors for trianglennn _f0.subVectors(_v1$2, _v0);nn _f1.subVectors(_v2, _v1$2);nn _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabbn // 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 separationn // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)nnn var 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];nn if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {n return false;n } // test 3 face normals from the aabbnnn axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];nn if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {n return false;n } // finally testing the face normal of the trianglen // use already existing triangle edge vectors herennn _triangleNormal.crossVectors(_f0, _f1);nn axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];n return satForAxes(axes, _v0, _v1$2, _v2, _extents);n },n clampPoint: function clampPoint(point, target) {n if (target === undefined) {n console.warn('THREE.Box3: .clampPoint() target is now required');n target = new Vector3();n }nn return target.copy(point).clamp(this.min, this.max);n },n distanceToPoint: function distanceToPoint(point) {n var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);nn return clampedPoint.sub(point).length();n },n getBoundingSphere: function getBoundingSphere(target) {n if (target === undefined) {n console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependencyn }nn this.getCenter(target.center);n target.radius = this.getSize(_vector$2).length() * 0.5;n return target;n },n intersect: function intersect(box) {n this.min.max(box.min);n this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.nn if (this.isEmpty()) this.makeEmpty();n return this;n },n union: function union(box) {n this.min.min(box.min);n this.max.max(box.max);n return this;n },n applyMatrix4: function applyMatrix4(matrix) {n // transform of empty box is an empty box.n if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations belownn _points.set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000nnn _points.set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001nnn _points.set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010nnn _points.set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011nnn _points.set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100nnn _points.set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101nnn _points.set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110nnn _points.set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111nnn this.setFromPoints(_points);n return this;n },n translate: function translate(offset) {n this.min.add(offset);n this.max.add(offset);n return this;n },n equals: function equals(box) {n return box.min.equals(this.min) && box.max.equals(this.max);n }n});nnfunction satForAxes(axes, v0, v1, v2, extents) {n var i, j;nn for (i = 0, j = axes.length - 3; i <= j; i += 3) {n _testAxis.fromArray(axes, i); // project the aabb onto the seperating axisnnn var 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 axisnn var p0 = v0.dot(_testAxis);n var p1 = v1.dot(_testAxis);n var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects rnn if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {n // points of the projected triangle are outside the projected half-length of the aabbn // the axis is seperating and we can exitn return false;n }n }nn return true;n}nnvar _box = new Box3();n/**n * @author bhouston / clara.ion * @author mrdoob / mrdoob.com/n */nnnfunction Sphere(center, radius) {n this.center = center !== undefined ? center : new Vector3();n this.radius = radius !== undefined ? radius : 0;n}nnObject.assign(Sphere.prototype, {n set: function set(center, radius) {n this.center.copy(center);n this.radius = radius;n return this;n },n setFromPoints: function setFromPoints(points, optionalCenter) {n var center = this.center;nn if (optionalCenter !== undefined) {n center.copy(optionalCenter);n } else {n _box.setFromPoints(points).getCenter(center);n }nn var maxRadiusSq = 0;nn for (var i = 0, il = points.length; i < il; i++) {n maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points));n }nn this.radius = Math.sqrt(maxRadiusSq);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(sphere) {n this.center.copy(sphere.center);n this.radius = sphere.radius;n return this;n },n empty: function empty() {n return this.radius <= 0;n },n containsPoint: function containsPoint(point) {n return point.distanceToSquared(this.center) <= this.radius * this.radius;n },n distanceToPoint: function distanceToPoint(point) {n return point.distanceTo(this.center) - this.radius;n },n intersectsSphere: function intersectsSphere(sphere) {n var radiusSum = this.radius + sphere.radius;n return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;n },n intersectsBox: function intersectsBox(box) {n return box.intersectsSphere(this);n },n intersectsPlane: function intersectsPlane(plane) {n return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;n },n clampPoint: function clampPoint(point, target) {n var deltaLengthSq = this.center.distanceToSquared(point);nn if (target === undefined) {n console.warn('THREE.Sphere: .clampPoint() target is now required');n target = new Vector3();n }nn target.copy(point);nn if (deltaLengthSq > this.radius * this.radius) {n target.sub(this.center).normalize();n target.multiplyScalar(this.radius).add(this.center);n }nn return target;n },n getBoundingBox: function getBoundingBox(target) {n if (target === undefined) {n console.warn('THREE.Sphere: .getBoundingBox() target is now required');n target = new Box3();n }nn target.set(this.center, this.center);n target.expandByScalar(this.radius);n return target;n },n applyMatrix4: function applyMatrix4(matrix) {n this.center.applyMatrix4(matrix);n this.radius = this.radius * matrix.getMaxScaleOnAxis();n return this;n },n translate: function translate(offset) {n this.center.add(offset);n return this;n },n equals: function equals(sphere) {n return sphere.center.equals(this.center) && sphere.radius === this.radius;n }n});nnvar _vector$3 = new Vector3();nnvar _segCenter = new Vector3();nnvar _segDir = new Vector3();nnvar _diff = new Vector3();nnvar _edge1 = new Vector3();nnvar _edge2 = new Vector3();nnvar _normal = new Vector3();n/**n * @author bhouston / clara.ion */nnnfunction Ray(origin, direction) {n this.origin = origin !== undefined ? origin : new Vector3();n this.direction = direction !== undefined ? direction : new Vector3();n}nnObject.assign(Ray.prototype, {n set: function set(origin, direction) {n this.origin.copy(origin);n this.direction.copy(direction);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(ray) {n this.origin.copy(ray.origin);n this.direction.copy(ray.direction);n return this;n },n at: function at(t, target) {n if (target === undefined) {n console.warn('THREE.Ray: .at() target is now required');n target = new Vector3();n }nn return target.copy(this.direction).multiplyScalar(t).add(this.origin);n },n lookAt: function lookAt(v) {n this.direction.copy(v).sub(this.origin).normalize();n return this;n },n recast: function recast(t) {n this.origin.copy(this.at(t, _vector$3));n return this;n },n closestPointToPoint: function closestPointToPoint(point, target) {n if (target === undefined) {n console.warn('THREE.Ray: .closestPointToPoint() target is now required');n target = new Vector3();n }nn target.subVectors(point, this.origin);n var directionDistance = target.dot(this.direction);nn if (directionDistance < 0) {n return target.copy(this.origin);n }nn return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);n },n distanceToPoint: function distanceToPoint(point) {n return Math.sqrt(this.distanceSqToPoint(point));n },n distanceSqToPoint: function distanceSqToPoint(point) {n var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the raynnn if (directionDistance < 0) {n return this.origin.distanceToSquared(point);n }nn _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);nn return _vector$3.distanceToSquared(point);n },n distanceSqToSegment: function distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {n // from www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.hn // It returns the min distance between the ray and the segmentn // defined by v0 and v1n // It can also set two optional targets :n // - The closest point on the rayn // - The closest point on the segmentn _segCenter.copy(v0).add(v1).multiplyScalar(0.5);nn _segDir.copy(v1).sub(v0).normalize();nn _diff.copy(this.origin).sub(_segCenter);nn var segExtent = v0.distanceTo(v1) * 0.5;n var a01 = -this.direction.dot(_segDir);nn var b0 = _diff.dot(this.direction);nn var b1 = -_diff.dot(_segDir);nn var c = _diff.lengthSq();nn var det = Math.abs(1 - a01 * a01);n var s0, s1, sqrDist, extDet;nn if (det > 0) {n // The ray and segment are not parallel.n s0 = a01 * b1 - b0;n s1 = a01 * b0 - b1;n extDet = segExtent * det;nn if (s0 >= 0) {n if (s1 >= -extDet) {n if (s1 <= extDet) {n // region 0n // Minimum at interior points of ray and segment.n var invDet = 1 / det;n s0 *= invDet;n s1 *= invDet;n sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;n } else {n // region 1n s1 = segExtent;n s0 = Math.max(0, -(a01 * s1 + b0));n sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;n }n } else {n // region 5n s1 = -segExtent;n s0 = Math.max(0, -(a01 * s1 + b0));n sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;n }n } else {n if (s1 <= -extDet) {n // region 4n s0 = Math.max(0, -(-a01 * segExtent + b0));n s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);n sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;n } else if (s1 <= extDet) {n // region 3n s0 = 0;n s1 = Math.min(Math.max(-segExtent, -b1), segExtent);n sqrDist = s1 * (s1 + 2 * b1) + c;n } else {n // region 2n s0 = Math.max(0, -(a01 * segExtent + b0));n s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);n sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;n }n }n } else {n // Ray and segment are parallel.n s1 = a01 > 0 ? -segExtent : segExtent;n s0 = Math.max(0, -(a01 * s1 + b0));n sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;n }nn if (optionalPointOnRay) {n optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);n }nn if (optionalPointOnSegment) {n optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);n }nn return sqrDist;n },n intersectSphere: function intersectSphere(sphere, target) {n _vector$3.subVectors(sphere.center, this.origin);nn var tca = _vector$3.dot(this.direction);nn var d2 = _vector$3.dot(_vector$3) - tca * tca;n var radius2 = sphere.radius * sphere.radius;n if (d2 > radius2) return null;n var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of spherenn var t0 = tca - thc; // t1 = second intersect point - exit point on back of spherenn var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return nullnn if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:n // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,n // in order to always return an intersect point that is in front of the ray.nn if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0nn return this.at(t0, target);n },n intersectsSphere: function intersectsSphere(sphere) {n return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;n },n distanceToPlane: function distanceToPlane(plane) {n var denominator = plane.normal.dot(this.direction);nn if (denominator === 0) {n // line is coplanar, return originn if (plane.distanceToPoint(this.origin) === 0) {n return 0;n } // Null is preferable to undefined since undefined means.… it is undefinednnn return null;n }nn var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the planenn return t >= 0 ? t : null;n },n intersectPlane: function intersectPlane(plane, target) {n var t = this.distanceToPlane(plane);nn if (t === null) {n return null;n }nn return this.at(t, target);n },n intersectsPlane: function intersectsPlane(plane) {n // check if the ray lies on the plane firstn var distToPoint = plane.distanceToPoint(this.origin);nn if (distToPoint === 0) {n return true;n }nn var denominator = plane.normal.dot(this.direction);nn if (denominator * distToPoint < 0) {n return true;n } // ray origin is behind the plane (and is pointing behind it)nnn return false;n },n intersectBox: function intersectBox(box, target) {n var tmin, tmax, tymin, tymax, tzmin, tzmax;n var invdirx = 1 / this.direction.x,n invdiry = 1 / this.direction.y,n invdirz = 1 / this.direction.z;n var origin = this.origin;nn if (invdirx >= 0) {n tmin = (box.min.x - origin.x) * invdirx;n tmax = (box.max.x - origin.x) * invdirx;n } else {n tmin = (box.max.x - origin.x) * invdirx;n tmax = (box.min.x - origin.x) * invdirx;n }nn if (invdiry >= 0) {n tymin = (box.min.y - origin.y) * invdiry;n tymax = (box.max.y - origin.y) * invdiry;n } else {n tymin = (box.max.y - origin.y) * invdiry;n tymax = (box.min.y - origin.y) * invdiry;n }nn if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaNn // (result of 0 * Infinity). x !== x returns true if x is NaNnn if (tymin > tmin || tmin !== tmin) tmin = tymin;n if (tymax < tmax || tmax !== tmax) tmax = tymax;nn if (invdirz >= 0) {n tzmin = (box.min.z - origin.z) * invdirz;n tzmax = (box.max.z - origin.z) * invdirz;n } else {n tzmin = (box.max.z - origin.z) * invdirz;n tzmax = (box.min.z - origin.z) * invdirz;n }nn if (tmin > tzmax || tzmin > tmax) return null;n if (tzmin > tmin || tmin !== tmin) tmin = tzmin;n if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)nn if (tmax < 0) return null;n return this.at(tmin >= 0 ? tmin : tmax, target);n },n intersectsBox: function intersectsBox(box) {n return this.intersectBox(box, _vector$3) !== null;n },n intersectTriangle: function intersectTriangle(a, b, c, backfaceCulling, target) {n // Compute the offset origin, edges, and normal.n // from www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.hn _edge1.subVectors(b, a);nn _edge2.subVectors(c, a);nn _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,n // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) byn // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))n // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))n // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)nnn var DdN = this.direction.dot(_normal);n var sign;nn if (DdN > 0) {n if (backfaceCulling) return null;n sign = 1;n } else if (DdN < 0) {n sign = -1;n DdN = -DdN;n } else {n return null;n }nn _diff.subVectors(this.origin, a);nn var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersectionnn if (DdQxE2 < 0) {n return null;n }nn var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersectionnn if (DdE1xQ < 0) {n return null;n } // b1+b2 > 1, no intersectionnnn if (DdQxE2 + DdE1xQ > DdN) {n return null;n } // Line intersects triangle, check if ray does.nnn var QdN = -sign * _diff.dot(_normal); // t < 0, no intersectionnnn if (QdN < 0) {n return null;n } // Ray intersects triangle.nnn return this.at(QdN / DdN, target);n },n applyMatrix4: function applyMatrix4(matrix4) {n this.origin.applyMatrix4(matrix4);n this.direction.transformDirection(matrix4);n return this;n },n equals: function equals(ray) {n return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);n }n});n/**n * @author bhouston / clara.ion * @author mrdoob / mrdoob.com/n */nnvar _v0$1 = new Vector3();nnvar _v1$3 = new Vector3();nnvar _v2$1 = new Vector3();nnvar _v3 = new Vector3();nnvar _vab = new Vector3();nnvar _vac = new Vector3();nnvar _vbc = new Vector3();nnvar _vap = new Vector3();nnvar _vbp = new Vector3();nnvar _vcp = new Vector3();nnfunction Triangle(a, b, c) {n this.a = a !== undefined ? a : new Vector3();n this.b = b !== undefined ? b : new Vector3();n this.c = c !== undefined ? c : new Vector3();n}nnObject.assign(Triangle, {n getNormal: function getNormal(a, b, c, target) {n if (target === undefined) {n console.warn('THREE.Triangle: .getNormal() target is now required');n target = new Vector3();n }nn target.subVectors(c, b);nn _v0$1.subVectors(a, b);nn target.cross(_v0$1);n var targetLengthSq = target.lengthSq();nn if (targetLengthSq > 0) {n return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));n }nn return target.set(0, 0, 0);n },n // static/instance method to calculate barycentric coordinatesn // based on: www.blackpawn.com/texts/pointinpoly/default.htmln getBarycoord: function getBarycoord(point, a, b, c, target) {n _v0$1.subVectors(c, a);nn _v1$3.subVectors(b, a);nn _v2$1.subVectors(point, a);nn var dot00 = _v0$1.dot(_v0$1);nn var dot01 = _v0$1.dot(_v1$3);nn var dot02 = _v0$1.dot(_v2$1);nn var dot11 = _v1$3.dot(_v1$3);nn var dot12 = _v1$3.dot(_v2$1);nn var denom = dot00 * dot11 - dot01 * dot01;nn if (target === undefined) {n console.warn('THREE.Triangle: .getBarycoord() target is now required');n target = new Vector3();n } // collinear or singular trianglennn if (denom === 0) {n // arbitrary location outside of triangle?n // not sure if this is the best idea, maybe should be returning undefinedn return target.set(-2, -1, -1);n }nn var invDenom = 1 / denom;n var u = (dot11 * dot02 - dot01 * dot12) * invDenom;n var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1nn return target.set(1 - u - v, v, u);n },n containsPoint: function containsPoint(point, a, b, c) {n Triangle.getBarycoord(point, a, b, c, _v3);n return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;n },n getUV: function getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {n this.getBarycoord(point, p1, p2, p3, _v3);n target.set(0, 0);n target.addScaledVector(uv1, _v3.x);n target.addScaledVector(uv2, _v3.y);n target.addScaledVector(uv3, _v3.z);n return target;n },n isFrontFacing: function isFrontFacing(a, b, c, direction) {n _v0$1.subVectors(c, b);nn _v1$3.subVectors(a, b); // strictly front facingnnn return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;n }n});nObject.assign(Triangle.prototype, {n set: function set(a, b, c) {n this.a.copy(a);n this.b.copy(b);n this.c.copy©;n return this;n },n setFromPointsAndIndices: function setFromPointsAndIndices(points, i0, i1, i2) {n this.a.copy(points);n this.b.copy(points);n this.c.copy(points);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(triangle) {n this.a.copy(triangle.a);n this.b.copy(triangle.b);n this.c.copy(triangle.c);n return this;n },n getArea: function getArea() {n _v0$1.subVectors(this.c, this.b);nn _v1$3.subVectors(this.a, this.b);nn return _v0$1.cross(_v1$3).length() * 0.5;n },n getMidpoint: function getMidpoint(target) {n if (target === undefined) {n console.warn('THREE.Triangle: .getMidpoint() target is now required');n target = new Vector3();n }nn return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);n },n getNormal: function getNormal(target) {n return Triangle.getNormal(this.a, this.b, this.c, target);n },n getPlane: function getPlane(target) {n if (target === undefined) {n console.warn('THREE.Triangle: .getPlane() target is now required');n target = new Vector3();n }nn return target.setFromCoplanarPoints(this.a, this.b, this.c);n },n getBarycoord: function getBarycoord(point, target) {n return Triangle.getBarycoord(point, this.a, this.b, this.c, target);n },n getUV: function getUV(point, uv1, uv2, uv3, target) {n return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);n },n containsPoint: function containsPoint(point) {n return Triangle.containsPoint(point, this.a, this.b, this.c);n },n isFrontFacing: function isFrontFacing(direction) {n return Triangle.isFrontFacing(this.a, this.b, this.c, direction);n },n intersectsBox: function intersectsBox(box) {n return box.intersectsTriangle(this);n },n closestPointToPoint: function closestPointToPoint(p, target) {n if (target === undefined) {n console.warn('THREE.Triangle: .closestPointToPoint() target is now required');n target = new Vector3();n }nn var a = this.a,n b = this.b,n c = this.c;n var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,n // published by Morgan Kaufmann Publishers, © 2005 Elsevier Inc.,n // under the accompanying license; see chapter 5.1.5 for detailed explanation.n // basically, we're distinguishing which of the voronoi regions of the trianglen // the point lies in with the minimum amount of redundant computation.nn _vab.subVectors(b, a);nn _vac.subVectors(c, a);nn _vap.subVectors(p, a);nn var d1 = _vab.dot(_vap);nn var d2 = _vac.dot(_vap);nn if (d1 <= 0 && d2 <= 0) {n // vertex region of A; barycentric coords (1, 0, 0)n return target.copy(a);n }nn _vbp.subVectors(p, b);nn var d3 = _vab.dot(_vbp);nn var d4 = _vac.dot(_vbp);nn if (d3 >= 0 && d4 <= d3) {n // vertex region of B; barycentric coords (0, 1, 0)n return target.copy(b);n }nn var vc = d1 * d4 - d3 * d2;nn if (vc <= 0 && d1 >= 0 && d3 <= 0) {n v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)nn return target.copy(a).addScaledVector(_vab, v);n }nn _vcp.subVectors(p, c);nn var d5 = _vab.dot(_vcp);nn var d6 = _vac.dot(_vcp);nn if (d6 >= 0 && d5 <= d6) {n // vertex region of C; barycentric coords (0, 0, 1)n return target.copy©;n }nn var vb = d5 * d2 - d1 * d6;nn if (vb <= 0 && d2 >= 0 && d6 <= 0) {n w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)nn return target.copy(a).addScaledVector(_vac, w);n }nn var va = d3 * d6 - d5 * d4;nn if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {n _vbc.subVectors(c, b);nn w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)nn return target.copy(b).addScaledVector(_vbc, w); // edge region of BCn } // face regionnnn var denom = 1 / (va + vb + vc); // u = va * denomnn v = vb * denom;n w = vc * denom;n return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);n },n equals: function equals(triangle) {n return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);n }n});n/**n * @author mrdoob / mrdoob.com/n */nnvar _colorKeywords = {n 'aliceblue': 0xF0F8FF,n 'antiquewhite': 0xFAEBD7,n 'aqua': 0x00FFFF,n 'aquamarine': 0x7FFFD4,n 'azure': 0xF0FFFF,n 'beige': 0xF5F5DC,n 'bisque': 0xFFE4C4,n 'black': 0x000000,n 'blanchedalmond': 0xFFEBCD,n 'blue': 0x0000FF,n 'blueviolet': 0x8A2BE2,n 'brown': 0xA52A2A,n 'burlywood': 0xDEB887,n 'cadetblue': 0x5F9EA0,n 'chartreuse': 0x7FFF00,n 'chocolate': 0xD2691E,n 'coral': 0xFF7F50,n 'cornflowerblue': 0x6495ED,n 'cornsilk': 0xFFF8DC,n 'crimson': 0xDC143C,n 'cyan': 0x00FFFF,n 'darkblue': 0x00008B,n 'darkcyan': 0x008B8B,n 'darkgoldenrod': 0xB8860B,n 'darkgray': 0xA9A9A9,n 'darkgreen': 0x006400,n 'darkgrey': 0xA9A9A9,n 'darkkhaki': 0xBDB76B,n 'darkmagenta': 0x8B008B,n 'darkolivegreen': 0x556B2F,n 'darkorange': 0xFF8C00,n 'darkorchid': 0x9932CC,n 'darkred': 0x8B0000,n 'darksalmon': 0xE9967A,n 'darkseagreen': 0x8FBC8F,n 'darkslateblue': 0x483D8B,n 'darkslategray': 0x2F4F4F,n 'darkslategrey': 0x2F4F4F,n 'darkturquoise': 0x00CED1,n 'darkviolet': 0x9400D3,n 'deeppink': 0xFF1493,n 'deepskyblue': 0x00BFFF,n 'dimgray': 0x696969,n 'dimgrey': 0x696969,n 'dodgerblue': 0x1E90FF,n 'firebrick': 0xB22222,n 'floralwhite': 0xFFFAF0,n 'forestgreen': 0x228B22,n 'fuchsia': 0xFF00FF,n 'gainsboro': 0xDCDCDC,n 'ghostwhite': 0xF8F8FF,n 'gold': 0xFFD700,n 'goldenrod': 0xDAA520,n 'gray': 0x808080,n 'green': 0x008000,n 'greenyellow': 0xADFF2F,n 'grey': 0x808080,n 'honeydew': 0xF0FFF0,n 'hotpink': 0xFF69B4,n 'indianred': 0xCD5C5C,n 'indigo': 0x4B0082,n 'ivory': 0xFFFFF0,n 'khaki': 0xF0E68C,n 'lavender': 0xE6E6FA,n 'lavenderblush': 0xFFF0F5,n 'lawngreen': 0x7CFC00,n 'lemonchiffon': 0xFFFACD,n 'lightblue': 0xADD8E6,n 'lightcoral': 0xF08080,n 'lightcyan': 0xE0FFFF,n 'lightgoldenrodyellow': 0xFAFAD2,n 'lightgray': 0xD3D3D3,n 'lightgreen': 0x90EE90,n 'lightgrey': 0xD3D3D3,n 'lightpink': 0xFFB6C1,n 'lightsalmon': 0xFFA07A,n 'lightseagreen': 0x20B2AA,n 'lightskyblue': 0x87CEFA,n 'lightslategray': 0x778899,n 'lightslategrey': 0x778899,n 'lightsteelblue': 0xB0C4DE,n 'lightyellow': 0xFFFFE0,n 'lime': 0x00FF00,n 'limegreen': 0x32CD32,n 'linen': 0xFAF0E6,n 'magenta': 0xFF00FF,n 'maroon': 0x800000,n 'mediumaquamarine': 0x66CDAA,n 'mediumblue': 0x0000CD,n 'mediumorchid': 0xBA55D3,n 'mediumpurple': 0x9370DB,n 'mediumseagreen': 0x3CB371,n 'mediumslateblue': 0x7B68EE,n 'mediumspringgreen': 0x00FA9A,n 'mediumturquoise': 0x48D1CC,n 'mediumvioletred': 0xC71585,n 'midnightblue': 0x191970,n 'mintcream': 0xF5FFFA,n 'mistyrose': 0xFFE4E1,n 'moccasin': 0xFFE4B5,n 'navajowhite': 0xFFDEAD,n 'navy': 0x000080,n 'oldlace': 0xFDF5E6,n 'olive': 0x808000,n 'olivedrab': 0x6B8E23,n 'orange': 0xFFA500,n 'orangered': 0xFF4500,n 'orchid': 0xDA70D6,n 'palegoldenrod': 0xEEE8AA,n 'palegreen': 0x98FB98,n 'paleturquoise': 0xAFEEEE,n 'palevioletred': 0xDB7093,n 'papayawhip': 0xFFEFD5,n 'peachpuff': 0xFFDAB9,n 'peru': 0xCD853F,n 'pink': 0xFFC0CB,n 'plum': 0xDDA0DD,n 'powderblue': 0xB0E0E6,n 'purple': 0x800080,n 'rebeccapurple': 0x663399,n 'red': 0xFF0000,n 'rosybrown': 0xBC8F8F,n 'royalblue': 0x4169E1,n 'saddlebrown': 0x8B4513,n 'salmon': 0xFA8072,n 'sandybrown': 0xF4A460,n 'seagreen': 0x2E8B57,n 'seashell': 0xFFF5EE,n 'sienna': 0xA0522D,n 'silver': 0xC0C0C0,n 'skyblue': 0x87CEEB,n 'slateblue': 0x6A5ACD,n 'slategray': 0x708090,n 'slategrey': 0x708090,n 'snow': 0xFFFAFA,n 'springgreen': 0x00FF7F,n 'steelblue': 0x4682B4,n 'tan': 0xD2B48C,n 'teal': 0x008080,n 'thistle': 0xD8BFD8,n 'tomato': 0xFF6347,n 'turquoise': 0x40E0D0,n 'violet': 0xEE82EE,n 'wheat': 0xF5DEB3,n 'white': 0xFFFFFF,n 'whitesmoke': 0xF5F5F5,n 'yellow': 0xFFFF00,n 'yellowgreen': 0x9ACD32n};nvar _hslA = {n h: 0,n s: 0,n l: 0n};nvar _hslB = {n h: 0,n s: 0,n l: 0n};nnfunction Color(r, g, b) {n if (g === undefined && b === undefined) {n // r is THREE.Color, hex or stringn return this.set®;n }nn return this.setRGB(r, g, b);n}nnfunction hue2rgb(p, q, t) {n if (t < 0) t += 1;n if (t > 1) t -= 1;n if (t < 1 / 6) return p + (q - p) * 6 * t;n if (t < 1 / 2) return q;n if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);n return p;n}nnfunction SRGBToLinear© {n return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);n}nnfunction LinearToSRGB© {n return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;n}nnObject.assign(Color.prototype, {n isColor: true,n r: 1,n g: 1,n b: 1,n set: function set(value) {n if (value && value.isColor) {n this.copy(value);n } else if (typeof value === 'number') {n this.setHex(value);n } else if (typeof value === 'string') {n this.setStyle(value);n }nn return this;n },n setScalar: function setScalar(scalar) {n this.r = scalar;n this.g = scalar;n this.b = scalar;n return this;n },n setHex: function setHex(hex) {n hex = Math.floor(hex);n this.r = (hex >> 16 & 255) / 255;n this.g = (hex >> 8 & 255) / 255;n this.b = (hex & 255) / 255;n return this;n },n setRGB: function setRGB(r, g, b) {n this.r = r;n this.g = g;n this.b = b;n return this;n },n setHSL: function setHSL(h, s, l) {n // h,s,l ranges are in 0.0 - 1.0n h = _Math.euclideanModulo(h, 1);n s = _Math.clamp(s, 0, 1);n l = _Math.clamp(l, 0, 1);nn if (s === 0) {n this.r = this.g = this.b = l;n } else {n var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;n var q = 2 * l - p;n this.r = hue2rgb(q, p, h + 1 / 3);n this.g = hue2rgb(q, p, h);n this.b = hue2rgb(q, p, h - 1 / 3);n }nn return this;n },n setStyle: function setStyle(style) {n function handleAlpha(string) {n if (string === undefined) return;nn if (parseFloat(string) < 1) {n console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');n }n }nn var m;nn if (m = /^((?:rgb|hsl)a?)\(\s*(*)\)/.exec(style)) {n // rgb / hsln var color;n var name = m;n var components = m;nn switch (name) {n case 'rgb':n case 'rgba':n if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {n // rgb(255,0,0) rgba(255,0,0,0.5)n this.r = Math.min(255, parseInt(color, 10)) / 255;n this.g = Math.min(255, parseInt(color, 10)) / 255;n this.b = Math.min(255, parseInt(color, 10)) / 255;n handleAlpha(color);n return this;n }nn if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {n // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)n this.r = Math.min(100, parseInt(color, 10)) / 100;n this.g = Math.min(100, parseInt(color, 10)) / 100;n this.b = Math.min(100, parseInt(color, 10)) / 100;n handleAlpha(color);n return this;n }nn break;nn case 'hsl':n case 'hsla':n if (color = /^([0-9]*\.?+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {n // hsl(120,50%,50%) hsla(120,50%,50%,0.5)n var h = parseFloat(color) / 360;n var s = parseInt(color, 10) / 100;n var l = parseInt(color, 10) / 100;n handleAlpha(color);n return this.setHSL(h, s, l);n }nn break;n }n } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {n // hex colorn var hex = m;n var size = hex.length;nn if (size === 3) {n // ff0n this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;n this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;n this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;n return this;n } else if (size === 6) {n // ff0000n this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;n this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;n this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;n return this;n }n }nn if (style && style.length > 0) {n // color keywordsn var hex = _colorKeywords;nn if (hex !== undefined) {n // redn this.setHex(hex);n } else {n // unknown colorn console.warn('THREE.Color: Unknown color ' + style);n }n }nn return this;n },n clone: function clone() {n return new this.constructor(this.r, this.g, this.b);n },n copy: function copy(color) {n this.r = color.r;n this.g = color.g;n this.b = color.b;n return this;n },n copyGammaToLinear: function copyGammaToLinear(color, gammaFactor) {n if (gammaFactor === undefined) gammaFactor = 2.0;n this.r = Math.pow(color.r, gammaFactor);n this.g = Math.pow(color.g, gammaFactor);n this.b = Math.pow(color.b, gammaFactor);n return this;n },n copyLinearToGamma: function copyLinearToGamma(color, gammaFactor) {n if (gammaFactor === undefined) gammaFactor = 2.0;n var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;n this.r = Math.pow(color.r, safeInverse);n this.g = Math.pow(color.g, safeInverse);n this.b = Math.pow(color.b, safeInverse);n return this;n },n convertGammaToLinear: function convertGammaToLinear(gammaFactor) {n this.copyGammaToLinear(this, gammaFactor);n return this;n },n convertLinearToGamma: function convertLinearToGamma(gammaFactor) {n this.copyLinearToGamma(this, gammaFactor);n return this;n },n copySRGBToLinear: function copySRGBToLinear(color) {n this.r = SRGBToLinear(color.r);n this.g = SRGBToLinear(color.g);n this.b = SRGBToLinear(color.b);n return this;n },n copyLinearToSRGB: function copyLinearToSRGB(color) {n this.r = LinearToSRGB(color.r);n this.g = LinearToSRGB(color.g);n this.b = LinearToSRGB(color.b);n return this;n },n convertSRGBToLinear: function convertSRGBToLinear() {n this.copySRGBToLinear(this);n return this;n },n convertLinearToSRGB: function convertLinearToSRGB() {n this.copyLinearToSRGB(this);n return this;n },n getHex: function getHex() {n return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;n },n getHexString: function getHexString() {n return ('000000' + this.getHex().toString(16)).slice(-6);n },n getHSL: function getHSL(target) {n // h,s,l ranges are in 0.0 - 1.0n if (target === undefined) {n console.warn('THREE.Color: .getHSL() target is now required');n target = {n h: 0,n s: 0,n l: 0n };n }nn var r = this.r,n g = this.g,n b = this.b;n var max = Math.max(r, g, b);n var min = Math.min(r, g, b);n var hue, saturation;n var lightness = (min + max) / 2.0;nn if (min === max) {n hue = 0;n saturation = 0;n } else {n var delta = max - min;n saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);nn switch (max) {n case r:n hue = (g - b) / delta + (g < b ? 6 : 0);n break;nn case g:n hue = (b - r) / delta + 2;n break;nn case b:n hue = (r - g) / delta + 4;n break;n }nn hue /= 6;n }nn target.h = hue;n target.s = saturation;n target.l = lightness;n return target;n },n getStyle: function getStyle() {n return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';n },n offsetHSL: function offsetHSL(h, s, l) {n this.getHSL(_hslA);n _hslA.h += h;n _hslA.s += s;n _hslA.l += l;n this.setHSL(_hslA.h, _hslA.s, _hslA.l);n return this;n },n add: function add(color) {n this.r += color.r;n this.g += color.g;n this.b += color.b;n return this;n },n addColors: function addColors(color1, color2) {n this.r = color1.r + color2.r;n this.g = color1.g + color2.g;n this.b = color1.b + color2.b;n return this;n },n addScalar: function addScalar(s) {n this.r += s;n this.g += s;n this.b += s;n return this;n },n sub: function sub(color) {n this.r = Math.max(0, this.r - color.r);n this.g = Math.max(0, this.g - color.g);n this.b = Math.max(0, this.b - color.b);n return this;n },n multiply: function multiply(color) {n this.r *= color.r;n this.g *= color.g;n this.b *= color.b;n return this;n },n multiplyScalar: function multiplyScalar(s) {n this.r *= s;n this.g *= s;n this.b *= s;n return this;n },n lerp: function lerp(color, alpha) {n this.r += (color.r - this.r) * alpha;n this.g += (color.g - this.g) * alpha;n this.b += (color.b - this.b) * alpha;n return this;n },n lerpHSL: function lerpHSL(color, alpha) {n this.getHSL(_hslA);n color.getHSL(_hslB);nn var h = _Math.lerp(_hslA.h, _hslB.h, alpha);nn var s = _Math.lerp(_hslA.s, _hslB.s, alpha);nn var l = _Math.lerp(_hslA.l, _hslB.l, alpha);nn this.setHSL(h, s, l);n return this;n },n equals: function equals© {n return c.r === this.r && c.g === this.g && c.b === this.b;n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;n this.r = array;n this.g = array[offset + 1];n this.b = array[offset + 2];n return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n array = this.r;n array[offset + 1] = this.g;n array[offset + 2] = this.b;n return array;n },n toJSON: function toJSON() {n return this.getHex();n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n */nnfunction Face3(a, b, c, normal, color, materialIndex) {n this.a = a;n this.b = b;n this.c = c;n this.normal = normal && normal.isVector3 ? normal : new Vector3();n this.vertexNormals = Array.isArray(normal) ? normal : [];n this.color = color && color.isColor ? color : new Color();n this.vertexColors = Array.isArray(color) ? color : [];n this.materialIndex = materialIndex !== undefined ? materialIndex : 0;n}nnObject.assign(Face3.prototype, {n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(source) {n this.a = source.a;n this.b = source.b;n this.c = source.c;n this.normal.copy(source.normal);n this.color.copy(source.color);n this.materialIndex = source.materialIndex;nn for (var i = 0, il = source.vertexNormals.length; i < il; i++) {n this.vertexNormals = source.vertexNormals.clone();n }nn for (var i = 0, il = source.vertexColors.length; i < il; i++) {n this.vertexColors = source.vertexColors.clone();n }nn return this;n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n */nnvar materialId = 0;nnfunction Material() {n Object.defineProperty(this, 'id', {n value: materialId++n });n this.uuid = _Math.generateUUID();n this.name = '';n this.type = 'Material';n this.fog = true;n this.lights = true;n this.blending = NormalBlending;n this.side = FrontSide;n this.flatShading = false;n this.vertexTangents = false;n this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColorsnn this.opacity = 1;n this.transparent = false;n this.blendSrc = SrcAlphaFactor;n this.blendDst = OneMinusSrcAlphaFactor;n this.blendEquation = AddEquation;n this.blendSrcAlpha = null;n this.blendDstAlpha = null;n this.blendEquationAlpha = null;n this.depthFunc = LessEqualDepth;n this.depthTest = true;n this.depthWrite = true;n this.stencilFunc = AlwaysStencilFunc;n this.stencilRef = 0;n this.stencilMask = 0xff;n this.stencilFail = KeepStencilOp;n this.stencilZFail = KeepStencilOp;n this.stencilZPass = KeepStencilOp;n this.stencilWrite = false;n this.clippingPlanes = null;n this.clipIntersection = false;n this.clipShadows = false;n this.shadowSide = null;n this.colorWrite = true;n this.precision = null; // override the renderer's default precision for this materialnn this.polygonOffset = false;n this.polygonOffsetFactor = 0;n this.polygonOffsetUnits = 0;n this.dithering = false;n this.alphaTest = 0;n this.premultipliedAlpha = false;n this.visible = true;n this.toneMapped = true;n this.userData = {};n this.needsUpdate = true;n}nnMaterial.prototype = Object.assign(Object.create(EventDispatcher.prototype), {n constructor: Material,n isMaterial: true,n onBeforeCompile: function onBeforeCompile() {},n setValues: function setValues(values) {n if (values === undefined) return;nn for (var key in values) {n var newValue = values;nn if (newValue === undefined) {n console.warn("THREE.Material: '" + key + "' parameter is undefined.");n continue;n } // for backward compatability if shading is set in the constructornnn if (key === 'shading') {n console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');n this.flatShading = newValue === FlatShading ? true : false;n continue;n }nn var currentValue = this;nn if (currentValue === undefined) {n console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");n continue;n }nn if (currentValue && currentValue.isColor) {n currentValue.set(newValue);n } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {n currentValue.copy(newValue);n } else {n this = newValue;n }n }n },n toJSON: function toJSON(meta) {n var isRoot = meta === undefined || typeof meta === 'string';nn if (isRoot) {n meta = {n textures: {},n images: {}n };n }nn var data = {n metadata: {n version: 4.5,n type: 'Material',n generator: 'Material.toJSON'n }n }; // standard Material serializationnn data.uuid = this.uuid;n data.type = this.type;n if (this.name !== '') data.name = this.name;n if (this.color && this.color.isColor) data.color = this.color.getHex();n if (this.roughness !== undefined) data.roughness = this.roughness;n if (this.metalness !== undefined) data.metalness = this.metalness;n if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();n if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;n if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();n if (this.shininess !== undefined) data.shininess = this.shininess;n if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;n if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;nn if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {n data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;n data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();n }nn if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;n if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;n if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;n if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;nn if (this.aoMap && this.aoMap.isTexture) {n data.aoMap = this.aoMap.toJSON(meta).uuid;n data.aoMapIntensity = this.aoMapIntensity;n }nn if (this.bumpMap && this.bumpMap.isTexture) {n data.bumpMap = this.bumpMap.toJSON(meta).uuid;n data.bumpScale = this.bumpScale;n }nn if (this.normalMap && this.normalMap.isTexture) {n data.normalMap = this.normalMap.toJSON(meta).uuid;n data.normalMapType = this.normalMapType;n data.normalScale = this.normalScale.toArray();n }nn if (this.displacementMap && this.displacementMap.isTexture) {n data.displacementMap = this.displacementMap.toJSON(meta).uuid;n data.displacementScale = this.displacementScale;n data.displacementBias = this.displacementBias;n }nn if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;n if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;n if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;n if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;nn if (this.envMap && this.envMap.isTexture) {n data.envMap = this.envMap.toJSON(meta).uuid;n data.reflectivity = this.reflectivity; // Scale behind envMapnn data.refractionRatio = this.refractionRatio;n if (this.combine !== undefined) data.combine = this.combine;n if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;n }nn if (this.gradientMap && this.gradientMap.isTexture) {n data.gradientMap = this.gradientMap.toJSON(meta).uuid;n }nn if (this.size !== undefined) data.size = this.size;n if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;n if (this.blending !== NormalBlending) data.blending = this.blending;n if (this.flatShading === true) data.flatShading = this.flatShading;n if (this.side !== FrontSide) data.side = this.side;n if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;n if (this.opacity < 1) data.opacity = this.opacity;n if (this.transparent === true) data.transparent = this.transparent;n data.depthFunc = this.depthFunc;n data.depthTest = this.depthTest;n data.depthWrite = this.depthWrite;n data.stencilWrite = this.stencilWrite;n data.stencilFunc = this.stencilFunc;n data.stencilRef = this.stencilRef;n data.stencilMask = this.stencilMask;n data.stencilFail = this.stencilFail;n data.stencilZFail = this.stencilZFail;n data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)nn if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;n if (this.polygonOffset === true) data.polygonOffset = true;n if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;n if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;n if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;n if (this.dashSize !== undefined) data.dashSize = this.dashSize;n if (this.gapSize !== undefined) data.gapSize = this.gapSize;n if (this.scale !== undefined) data.scale = this.scale;n if (this.dithering === true) data.dithering = true;n if (this.alphaTest > 0) data.alphaTest = this.alphaTest;n if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;n if (this.wireframe === true) data.wireframe = this.wireframe;n if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;n if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;n if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;n if (this.morphTargets === true) data.morphTargets = true;n if (this.morphNormals === true) data.morphNormals = true;n if (this.skinning === true) data.skinning = true;n if (this.visible === false) data.visible = false;n if (this.toneMapped === false) data.toneMapped = false;n if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSONnn function extractFromCache(cache) {n var values = [];nn for (var key in cache) {n var data = cache;n delete data.metadata;n values.push(data);n }nn return values;n }nn if (isRoot) {n var textures = extractFromCache(meta.textures);n var images = extractFromCache(meta.images);n if (textures.length > 0) data.textures = textures;n if (images.length > 0) data.images = images;n }nn return data;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(source) {n this.name = source.name;n this.fog = source.fog;n this.lights = source.lights;n this.blending = source.blending;n this.side = source.side;n this.flatShading = source.flatShading;n this.vertexColors = source.vertexColors;n this.opacity = source.opacity;n this.transparent = source.transparent;n this.blendSrc = source.blendSrc;n this.blendDst = source.blendDst;n this.blendEquation = source.blendEquation;n this.blendSrcAlpha = source.blendSrcAlpha;n this.blendDstAlpha = source.blendDstAlpha;n this.blendEquationAlpha = source.blendEquationAlpha;n this.depthFunc = source.depthFunc;n this.depthTest = source.depthTest;n this.depthWrite = source.depthWrite;n this.stencilWrite = source.stencilWrite;n this.stencilFunc = source.stencilFunc;n this.stencilRef = source.stencilRef;n this.stencilMask = source.stencilMask;n this.stencilFail = source.stencilFail;n this.stencilZFail = source.stencilZFail;n this.stencilZPass = source.stencilZPass;n this.colorWrite = source.colorWrite;n this.precision = source.precision;n this.polygonOffset = source.polygonOffset;n this.polygonOffsetFactor = source.polygonOffsetFactor;n this.polygonOffsetUnits = source.polygonOffsetUnits;n this.dithering = source.dithering;n this.alphaTest = source.alphaTest;n this.premultipliedAlpha = source.premultipliedAlpha;n this.visible = source.visible;n this.toneMapped = source.toneMapped;n this.userData = JSON.parse(JSON.stringify(source.userData));n this.clipShadows = source.clipShadows;n this.clipIntersection = source.clipIntersection;n var srcPlanes = source.clippingPlanes,n dstPlanes = null;nn if (srcPlanes !== null) {n var n = srcPlanes.length;n dstPlanes = new Array(n);nn for (var i = 0; i !== n; ++i) {n dstPlanes = srcPlanes.clone();n }n }nn this.clippingPlanes = dstPlanes;n this.shadowSide = source.shadowSide;n return this;n },n dispose: function dispose() {n this.dispatchEvent({n type: 'dispose'n });n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n *n * parameters = {n * color: <hex>,n * opacity: <float>,n * map: new THREE.Texture( <Image> ),n *n * lightMap: new THREE.Texture( <Image> ),n * lightMapIntensity: <float>n *n * aoMap: new THREE.Texture( <Image> ),n * aoMapIntensity: <float>n *n * specularMap: new THREE.Texture( <Image> ),n *n * alphaMap: new THREE.Texture( <Image> ),n *n * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),n * combine: THREE.Multiply,n * reflectivity: <float>,n * refractionRatio: <float>,n *n * depthTest: <bool>,n * depthWrite: <bool>,n *n * wireframe: <boolean>,n * wireframeLinewidth: <float>,n *n * skinning: <bool>,n * morphTargets: <bool>n * }n */nnfunction MeshBasicMaterial(parameters) {n Material.call(this);n this.type = 'MeshBasicMaterial';n this.color = new Color(0xffffff); // emissivenn this.map = null;n this.lightMap = null;n this.lightMapIntensity = 1.0;n this.aoMap = null;n this.aoMapIntensity = 1.0;n this.specularMap = null;n this.alphaMap = null;n this.envMap = null;n this.combine = MultiplyOperation;n this.reflectivity = 1;n this.refractionRatio = 0.98;n this.wireframe = false;n this.wireframeLinewidth = 1;n this.wireframeLinecap = 'round';n this.wireframeLinejoin = 'round';n this.skinning = false;n this.morphTargets = false;n this.lights = false;n this.setValues(parameters);n}nnMeshBasicMaterial.prototype = Object.create(Material.prototype);nMeshBasicMaterial.prototype.constructor = MeshBasicMaterial;nMeshBasicMaterial.prototype.isMeshBasicMaterial = true;nnMeshBasicMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.color.copy(source.color);n this.map = source.map;n this.lightMap = source.lightMap;n this.lightMapIntensity = source.lightMapIntensity;n this.aoMap = source.aoMap;n this.aoMapIntensity = source.aoMapIntensity;n this.specularMap = source.specularMap;n this.alphaMap = source.alphaMap;n this.envMap = source.envMap;n this.combine = source.combine;n this.reflectivity = source.reflectivity;n this.refractionRatio = source.refractionRatio;n this.wireframe = source.wireframe;n this.wireframeLinewidth = source.wireframeLinewidth;n this.wireframeLinecap = source.wireframeLinecap;n this.wireframeLinejoin = source.wireframeLinejoin;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n return this;n};n/**n * @author mrdoob / mrdoob.com/n */nnnfunction BufferAttribute(array, itemSize, normalized) {n if (Array.isArray(array)) {n throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');n }nn this.name = '';n this.array = array;n this.itemSize = itemSize;n this.count = array !== undefined ? array.length / itemSize : 0;n this.normalized = normalized === true;n this.dynamic = false;n this.updateRange = {n offset: 0,n count: -1n };n this.version = 0;n}nnObject.defineProperty(BufferAttribute.prototype, 'needsUpdate', {n set: function set(value) {n if (value === true) this.version++;n }n});nObject.assign(BufferAttribute.prototype, {n isBufferAttribute: true,n onUploadCallback: function onUploadCallback() {},n setArray: function setArray(array) {n if (Array.isArray(array)) {n throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');n }nn this.count = array !== undefined ? array.length / this.itemSize : 0;n this.array = array;n return this;n },n setDynamic: function setDynamic(value) {n this.dynamic = value;n return this;n },n copy: function copy(source) {n this.name = source.name;n this.array = new source.array.constructor(source.array);n this.itemSize = source.itemSize;n this.count = source.count;n this.normalized = source.normalized;n this.dynamic = source.dynamic;n return this;n },n copyAt: function copyAt(index1, attribute, index2) {n index1 *= this.itemSize;n index2 *= attribute.itemSize;nn for (var i = 0, l = this.itemSize; i < l; i++) {n this.array[index1 + i] = attribute.array[index2 + i];n }nn return this;n },n copyArray: function copyArray(array) {n this.array.set(array);n return this;n },n copyColorsArray: function copyColorsArray(colors) {n var array = this.array,n offset = 0;nn for (var i = 0, l = colors.length; i < l; i++) {n var color = colors;nn if (color === undefined) {n console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);n color = new Color();n }nn array = color.r;n array = color.g;n array = color.b;n }nn return this;n },n copyVector2sArray: function copyVector2sArray(vectors) {n var array = this.array,n offset = 0;nn for (var i = 0, l = vectors.length; i < l; i++) {n var vector = vectors;nn if (vector === undefined) {n console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);n vector = new Vector2();n }nn array = vector.x;n array = vector.y;n }nn return this;n },n copyVector3sArray: function copyVector3sArray(vectors) {n var array = this.array,n offset = 0;nn for (var i = 0, l = vectors.length; i < l; i++) {n var vector = vectors;nn if (vector === undefined) {n console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);n vector = new Vector3();n }nn array = vector.x;n array = vector.y;n array = vector.z;n }nn return this;n },n copyVector4sArray: function copyVector4sArray(vectors) {n var array = this.array,n offset = 0;nn for (var i = 0, l = vectors.length; i < l; i++) {n var vector = vectors;nn if (vector === undefined) {n console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);n vector = new Vector4();n }nn array = vector.x;n array = vector.y;n array = vector.z;n array = vector.w;n }nn return this;n },n set: function set(value, offset) {n if (offset === undefined) offset = 0;n this.array.set(value, offset);n return this;n },n getX: function getX(index) {n return this.array[index * this.itemSize];n },n setX: function setX(index, x) {n this.array[index * this.itemSize] = x;n return this;n },n getY: function getY(index) {n return this.array[index * this.itemSize + 1];n },n setY: function setY(index, y) {n this.array[index * this.itemSize + 1] = y;n return this;n },n getZ: function getZ(index) {n return this.array[index * this.itemSize + 2];n },n setZ: function setZ(index, z) {n this.array[index * this.itemSize + 2] = z;n return this;n },n getW: function getW(index) {n return this.array[index * this.itemSize + 3];n },n setW: function setW(index, w) {n this.array[index * this.itemSize + 3] = w;n return this;n },n setXY: function setXY(index, x, y) {n index *= this.itemSize;n this.array[index + 0] = x;n this.array[index + 1] = y;n return this;n },n setXYZ: function setXYZ(index, x, y, z) {n index *= this.itemSize;n this.array[index + 0] = x;n this.array[index + 1] = y;n this.array[index + 2] = z;n return this;n },n setXYZW: function setXYZW(index, x, y, z, w) {n index *= this.itemSize;n this.array[index + 0] = x;n this.array[index + 1] = y;n this.array[index + 2] = z;n this.array[index + 3] = w;n return this;n },n onUpload: function onUpload(callback) {n this.onUploadCallback = callback;n return this;n },n clone: function clone() {n return new this.constructor(this.array, this.itemSize).copy(this);n },n toJSON: function toJSON() {n return {n itemSize: this.itemSize,n type: this.array.constructor.name,n array: Array.prototype.slice.call(this.array),n normalized: this.normalizedn };n }n}); //nnfunction Int8BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);n}nnInt8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nInt8BufferAttribute.prototype.constructor = Int8BufferAttribute;nnfunction Uint8BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);n}nnUint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nUint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;nnfunction Uint8ClampedBufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);n}nnUint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);nUint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;nnfunction Int16BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);n}nnInt16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nInt16BufferAttribute.prototype.constructor = Int16BufferAttribute;nnfunction Uint16BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);n}nnUint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nUint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;nnfunction Int32BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);n}nnInt32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nInt32BufferAttribute.prototype.constructor = Int32BufferAttribute;nnfunction Uint32BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);n}nnUint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nUint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;nnfunction Float32BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);n}nnFloat32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nFloat32BufferAttribute.prototype.constructor = Float32BufferAttribute;nnfunction Float64BufferAttribute(array, itemSize, normalized) {n BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);n}nnFloat64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);nFloat64BufferAttribute.prototype.constructor = Float64BufferAttribute;n/**n * @author mrdoob / mrdoob.com/n */nnfunction DirectGeometry() {n this.vertices = [];n this.normals = [];n this.colors = [];n this.uvs = [];n this.uvs2 = [];n this.groups = [];n this.morphTargets = {};n this.skinWeights = [];n this.skinIndices = []; // this.lineDistances = [];nn this.boundingBox = null;n this.boundingSphere = null; // update flagsnn this.verticesNeedUpdate = false;n this.normalsNeedUpdate = false;n this.colorsNeedUpdate = false;n this.uvsNeedUpdate = false;n this.groupsNeedUpdate = false;n}nnObject.assign(DirectGeometry.prototype, {n computeGroups: function computeGroups(geometry) {n var group;n var groups = [];n var materialIndex = undefined;n var faces = geometry.faces;nn for (var i = 0; i < faces.length; i++) {n var face = faces; // materialsnn if (face.materialIndex !== materialIndex) {n materialIndex = face.materialIndex;nn if (group !== undefined) {n group.count = i * 3 - group.start;n groups.push(group);n }nn group = {n start: i * 3,n materialIndex: materialIndexn };n }n }nn if (group !== undefined) {n group.count = i * 3 - group.start;n groups.push(group);n }nn this.groups = groups;n },n fromGeometry: function fromGeometry(geometry) {n var faces = geometry.faces;n var vertices = geometry.vertices;n var faceVertexUvs = geometry.faceVertexUvs;n var hasFaceVertexUv = faceVertexUvs && faceVertexUvs.length > 0;n var hasFaceVertexUv2 = faceVertexUvs && faceVertexUvs.length > 0; // morphsnn var morphTargets = geometry.morphTargets;n var morphTargetsLength = morphTargets.length;n var morphTargetsPosition;nn if (morphTargetsLength > 0) {n morphTargetsPosition = [];nn for (var i = 0; i < morphTargetsLength; i++) {n morphTargetsPosition = {n name: morphTargets.name,n data: []n };n }nn this.morphTargets.position = morphTargetsPosition;n }nn var morphNormals = geometry.morphNormals;n var morphNormalsLength = morphNormals.length;n var morphTargetsNormal;nn if (morphNormalsLength > 0) {n morphTargetsNormal = [];nn for (var i = 0; i < morphNormalsLength; i++) {n morphTargetsNormal = {n name: morphNormals.name,n data: []n };n }nn this.morphTargets.normal = morphTargetsNormal;n } // skinsnnn var skinIndices = geometry.skinIndices;n var skinWeights = geometry.skinWeights;n var hasSkinIndices = skinIndices.length === vertices.length;n var hasSkinWeights = skinWeights.length === vertices.length; //nn if (vertices.length > 0 && faces.length === 0) {n console.error('THREE.DirectGeometry: Faceless geometries are not supported.');n }nn for (var i = 0; i < faces.length; i++) {n var face = faces;n this.vertices.push(vertices, vertices, vertices);n var vertexNormals = face.vertexNormals;nn if (vertexNormals.length === 3) {n this.normals.push(vertexNormals, vertexNormals, vertexNormals);n } else {n var normal = face.normal;n this.normals.push(normal, normal, normal);n }nn var vertexColors = face.vertexColors;nn if (vertexColors.length === 3) {n this.colors.push(vertexColors, vertexColors, vertexColors);n } else {n var color = face.color;n this.colors.push(color, color, color);n }nn if (hasFaceVertexUv === true) {n var vertexUvs = faceVertexUvs[i];nn if (vertexUvs !== undefined) {n this.uvs.push(vertexUvs, vertexUvs, vertexUvs);n } else {n console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);n this.uvs.push(new Vector2(), new Vector2(), new Vector2());n }n }nn if (hasFaceVertexUv2 === true) {n var vertexUvs = faceVertexUvs[i];nn if (vertexUvs !== undefined) {n this.uvs2.push(vertexUvs, vertexUvs, vertexUvs);n } else {n console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);n this.uvs2.push(new Vector2(), new Vector2(), new Vector2());n }n } // morphsnnn for (var j = 0; j < morphTargetsLength; j++) {n var morphTarget = morphTargets.vertices;n morphTargetsPosition.data.push(morphTarget, morphTarget, morphTarget);n }nn for (var j = 0; j < morphNormalsLength; j++) {n var morphNormal = morphNormals.vertexNormals;n morphTargetsNormal.data.push(morphNormal.a, morphNormal.b, morphNormal.c);n } // skinsnnn if (hasSkinIndices) {n this.skinIndices.push(skinIndices, skinIndices, skinIndices);n }nn if (hasSkinWeights) {n this.skinWeights.push(skinWeights, skinWeights, skinWeights);n }n }nn this.computeGroups(geometry);n this.verticesNeedUpdate = geometry.verticesNeedUpdate;n this.normalsNeedUpdate = geometry.normalsNeedUpdate;n this.colorsNeedUpdate = geometry.colorsNeedUpdate;n this.uvsNeedUpdate = geometry.uvsNeedUpdate;n this.groupsNeedUpdate = geometry.groupsNeedUpdate;nn if (geometry.boundingSphere !== null) {n this.boundingSphere = geometry.boundingSphere.clone();n }nn if (geometry.boundingBox !== null) {n this.boundingBox = geometry.boundingBox.clone();n }nn return this;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction arrayMax(array) {n if (array.length === 0) return -Infinity;n var max = array;nn for (var i = 1, l = array.length; i < l; ++i) {n if (array > max) max = array;n }nn return max;n}n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n */nnnvar _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Idnnvar _m1$2 = new Matrix4();nnvar _obj = new Object3D();nnvar _offset = new Vector3();nnvar _box$1 = new Box3();nnvar _boxMorphTargets = new Box3();nnvar _vector$4 = new Vector3();nnfunction BufferGeometry() {n Object.defineProperty(this, 'id', {n value: _bufferGeometryId += 2n });n this.uuid = _Math.generateUUID();n this.name = '';n this.type = 'BufferGeometry';n this.index = null;n this.attributes = {};n this.morphAttributes = {};n this.groups = [];n this.boundingBox = null;n this.boundingSphere = null;n this.drawRange = {n start: 0,n count: Infinityn };n this.userData = {};n}nnBufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {n constructor: BufferGeometry,n isBufferGeometry: true,n getIndex: function getIndex() {n return this.index;n },n setIndex: function setIndex(index) {n if (Array.isArray(index)) {n this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);n } else {n this.index = index;n }n },n addAttribute: function addAttribute(name, attribute) {n if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {n console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');n return this.addAttribute(name, new BufferAttribute(arguments, arguments));n }nn if (name === 'index') {n console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');n this.setIndex(attribute);n return this;n }nn this.attributes = attribute;n return this;n },n getAttribute: function getAttribute(name) {n return this.attributes;n },n removeAttribute: function removeAttribute(name) {n delete this.attributes;n return this;n },n addGroup: function addGroup(start, count, materialIndex) {n this.groups.push({n start: start,n count: count,n materialIndex: materialIndex !== undefined ? materialIndex : 0n });n },n clearGroups: function clearGroups() {n this.groups = [];n },n setDrawRange: function setDrawRange(start, count) {n this.drawRange.start = start;n this.drawRange.count = count;n },n applyMatrix: function applyMatrix(matrix) {n var position = this.attributes.position;nn if (position !== undefined) {n matrix.applyToBufferAttribute(position);n position.needsUpdate = true;n }nn var normal = this.attributes.normal;nn if (normal !== undefined) {n var normalMatrix = new Matrix3().getNormalMatrix(matrix);n normalMatrix.applyToBufferAttribute(normal);n normal.needsUpdate = true;n }nn var tangent = this.attributes.tangent;nn if (tangent !== undefined) {n var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).nn normalMatrix.applyToBufferAttribute(tangent);n tangent.needsUpdate = true;n }nn if (this.boundingBox !== null) {n this.computeBoundingBox();n }nn if (this.boundingSphere !== null) {n this.computeBoundingSphere();n }nn return this;n },n rotateX: function rotateX(angle) {n // rotate geometry around world x-axisn _m1$2.makeRotationX(angle);nn this.applyMatrix(_m1$2);n return this;n },n rotateY: function rotateY(angle) {n // rotate geometry around world y-axisn _m1$2.makeRotationY(angle);nn this.applyMatrix(_m1$2);n return this;n },n rotateZ: function rotateZ(angle) {n // rotate geometry around world z-axisn _m1$2.makeRotationZ(angle);nn this.applyMatrix(_m1$2);n return this;n },n translate: function translate(x, y, z) {n // translate geometryn _m1$2.makeTranslation(x, y, z);nn this.applyMatrix(_m1$2);n return this;n },n scale: function scale(x, y, z) {n // scale geometryn _m1$2.makeScale(x, y, z);nn this.applyMatrix(_m1$2);n return this;n },n lookAt: function lookAt(vector) {n _obj.lookAt(vector);nn _obj.updateMatrix();nn this.applyMatrix(_obj.matrix);n return this;n },n center: function center() {n this.computeBoundingBox();n this.boundingBox.getCenter(_offset).negate();n this.translate(_offset.x, _offset.y, _offset.z);n return this;n },n setFromObject: function setFromObject(object) {n // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );n var geometry = object.geometry;nn if (object.isPoints || object.isLine) {n var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);n var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);n this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));n this.addAttribute('color', colors.copyColorsArray(geometry.colors));nn if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {n var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);n this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));n }nn if (geometry.boundingSphere !== null) {n this.boundingSphere = geometry.boundingSphere.clone();n }nn if (geometry.boundingBox !== null) {n this.boundingBox = geometry.boundingBox.clone();n }n } else if (object.isMesh) {n if (geometry && geometry.isGeometry) {n this.fromGeometry(geometry);n }n }nn return this;n },n setFromPoints: function setFromPoints(points) {n var position = [];nn for (var i = 0, l = points.length; i < l; i++) {n var point = points;n position.push(point.x, point.y, point.z || 0);n }nn this.addAttribute('position', new Float32BufferAttribute(position, 3));n return this;n },n updateFromObject: function updateFromObject(object) {n var geometry = object.geometry;nn if (object.isMesh) {n var direct = geometry.__directGeometry;nn if (geometry.elementsNeedUpdate === true) {n direct = undefined;n geometry.elementsNeedUpdate = false;n }nn if (direct === undefined) {n return this.fromGeometry(geometry);n }nn direct.verticesNeedUpdate = geometry.verticesNeedUpdate;n direct.normalsNeedUpdate = geometry.normalsNeedUpdate;n direct.colorsNeedUpdate = geometry.colorsNeedUpdate;n direct.uvsNeedUpdate = geometry.uvsNeedUpdate;n direct.groupsNeedUpdate = geometry.groupsNeedUpdate;n geometry.verticesNeedUpdate = false;n geometry.normalsNeedUpdate = false;n geometry.colorsNeedUpdate = false;n geometry.uvsNeedUpdate = false;n geometry.groupsNeedUpdate = false;n geometry = direct;n }nn var attribute;nn if (geometry.verticesNeedUpdate === true) {n attribute = this.attributes.position;nn if (attribute !== undefined) {n attribute.copyVector3sArray(geometry.vertices);n attribute.needsUpdate = true;n }nn geometry.verticesNeedUpdate = false;n }nn if (geometry.normalsNeedUpdate === true) {n attribute = this.attributes.normal;nn if (attribute !== undefined) {n attribute.copyVector3sArray(geometry.normals);n attribute.needsUpdate = true;n }nn geometry.normalsNeedUpdate = false;n }nn if (geometry.colorsNeedUpdate === true) {n attribute = this.attributes.color;nn if (attribute !== undefined) {n attribute.copyColorsArray(geometry.colors);n attribute.needsUpdate = true;n }nn geometry.colorsNeedUpdate = false;n }nn if (geometry.uvsNeedUpdate) {n attribute = this.attributes.uv;nn if (attribute !== undefined) {n attribute.copyVector2sArray(geometry.uvs);n attribute.needsUpdate = true;n }nn geometry.uvsNeedUpdate = false;n }nn if (geometry.lineDistancesNeedUpdate) {n attribute = this.attributes.lineDistance;nn if (attribute !== undefined) {n attribute.copyArray(geometry.lineDistances);n attribute.needsUpdate = true;n }nn geometry.lineDistancesNeedUpdate = false;n }nn if (geometry.groupsNeedUpdate) {n geometry.computeGroups(object.geometry);n this.groups = geometry.groups;n geometry.groupsNeedUpdate = false;n }nn return this;n },n fromGeometry: function fromGeometry(geometry) {n geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);n return this.fromDirectGeometry(geometry.__directGeometry);n },n fromDirectGeometry: function fromDirectGeometry(geometry) {n var positions = new Float32Array(geometry.vertices.length * 3);n this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));nn if (geometry.normals.length > 0) {n var normals = new Float32Array(geometry.normals.length * 3);n this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));n }nn if (geometry.colors.length > 0) {n var colors = new Float32Array(geometry.colors.length * 3);n this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));n }nn if (geometry.uvs.length > 0) {n var uvs = new Float32Array(geometry.uvs.length * 2);n this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));n }nn if (geometry.uvs2.length > 0) {n var uvs2 = new Float32Array(geometry.uvs2.length * 2);n this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));n } // groupsnnn this.groups = geometry.groups; // morphsnn for (var name in geometry.morphTargets) {n var array = [];n var morphTargets = geometry.morphTargets;nn for (var i = 0, l = morphTargets.length; i < l; i++) {n var morphTarget = morphTargets;n var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);n attribute.name = morphTarget.name;n array.push(attribute.copyVector3sArray(morphTarget.data));n }nn this.morphAttributes = array;n } // skinningnnn if (geometry.skinIndices.length > 0) {n var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);n this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));n }nn if (geometry.skinWeights.length > 0) {n var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);n this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));n } //nnn if (geometry.boundingSphere !== null) {n this.boundingSphere = geometry.boundingSphere.clone();n }nn if (geometry.boundingBox !== null) {n this.boundingBox = geometry.boundingBox.clone();n }nn return this;n },n computeBoundingBox: function computeBoundingBox() {n if (this.boundingBox === null) {n this.boundingBox = new Box3();n }nn var position = this.attributes.position;n var morphAttributesPosition = this.morphAttributes.position;nn if (position !== undefined) {n this.boundingBox.setFromBufferAttribute(position); // process morph attributes if presentnn if (morphAttributesPosition) {n for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {n var morphAttribute = morphAttributesPosition;nn _box$1.setFromBufferAttribute(morphAttribute);nn this.boundingBox.expandByPoint(_box$1.min);n this.boundingBox.expandByPoint(_box$1.max);n }n }n } else {n this.boundingBox.makeEmpty();n }nn if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {n console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);n }n },n computeBoundingSphere: function computeBoundingSphere() {n if (this.boundingSphere === null) {n this.boundingSphere = new Sphere();n }nn var position = this.attributes.position;n var morphAttributesPosition = this.morphAttributes.position;nn if (position) {n // first, find the center of the bounding spheren var center = this.boundingSphere.center;nn _box$1.setFromBufferAttribute(position); // process morph attributes if presentnnn if (morphAttributesPosition) {n for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {n var morphAttribute = morphAttributesPosition;nn _boxMorphTargets.setFromBufferAttribute(morphAttribute);nn _box$1.expandByPoint(_boxMorphTargets.min);nn _box$1.expandByPoint(_boxMorphTargets.max);n }n }nn _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than then // boundingSphere of the boundingBox: sqrt(3) smaller in the best casennn var maxRadiusSq = 0;nn for (var i = 0, il = position.count; i < il; i++) {n _vector$4.fromBufferAttribute(position, i);nn maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));n } // process morph attributes if presentnnn if (morphAttributesPosition) {n for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {n var morphAttribute = morphAttributesPosition;nn for (var j = 0, jl = morphAttribute.count; j < jl; j++) {n _vector$4.fromBufferAttribute(morphAttribute, j);nn maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));n }n }n }nn this.boundingSphere.radius = Math.sqrt(maxRadiusSq);nn if (isNaN(this.boundingSphere.radius)) {n console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);n }n }n },n computeFaceNormals: function computeFaceNormals() {// backwards compatibilityn },n computeVertexNormals: function computeVertexNormals() {n var index = this.index;n var attributes = this.attributes;nn if (attributes.position) {n var positions = attributes.position.array;nn if (attributes.normal === undefined) {n this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));n } else {n // reset existing normals to zeron var array = attributes.normal.array;nn for (var i = 0, il = array.length; i < il; i++) {n array = 0;n }n }nn var normals = attributes.normal.array;n var vA, vB, vC;n var pA = new Vector3(),n pB = new Vector3(),n pC = new Vector3();n var cb = new Vector3(),n ab = new Vector3(); // indexed elementsnn if (index) {n var indices = index.array;nn for (var i = 0, il = index.count; i < il; i += 3) {n vA = indices[i + 0] * 3;n vB = indices[i + 1] * 3;n vC = indices[i + 2] * 3;n pA.fromArray(positions, vA);n pB.fromArray(positions, vB);n pC.fromArray(positions, vC);n cb.subVectors(pC, pB);n ab.subVectors(pA, pB);n cb.cross(ab);n normals += cb.x;n normals[vA + 1] += cb.y;n normals[vA + 2] += cb.z;n normals += cb.x;n normals[vB + 1] += cb.y;n normals[vB + 2] += cb.z;n normals += cb.x;n normals[vC + 1] += cb.y;n normals[vC + 2] += cb.z;n }n } else {n // non-indexed elements (unconnected triangle soup)n for (var i = 0, il = positions.length; i < il; i += 9) {n pA.fromArray(positions, i);n pB.fromArray(positions, i + 3);n pC.fromArray(positions, i + 6);n cb.subVectors(pC, pB);n ab.subVectors(pA, pB);n cb.cross(ab);n normals = cb.x;n normals[i + 1] = cb.y;n normals[i + 2] = cb.z;n normals[i + 3] = cb.x;n normals[i + 4] = cb.y;n normals[i + 5] = cb.z;n normals[i + 6] = cb.x;n normals[i + 7] = cb.y;n normals[i + 8] = cb.z;n }n }nn this.normalizeNormals();n attributes.normal.needsUpdate = true;n }n },n merge: function merge(geometry, offset) {n if (!(geometry && geometry.isBufferGeometry)) {n console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);n return;n }nn if (offset === undefined) {n offset = 0;n console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');n }nn var attributes = this.attributes;nn for (var key in attributes) {n if (geometry.attributes === undefined) continue;n var attribute1 = attributes;n var attributeArray1 = attribute1.array;n var attribute2 = geometry.attributes;n var attributeArray2 = attribute2.array;n var attributeOffset = attribute2.itemSize * offset;n var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);nn for (var i = 0, j = attributeOffset; i < length; i++, j++) {n attributeArray1 = attributeArray2;n }n }nn return this;n },n normalizeNormals: function normalizeNormals() {n var normals = this.attributes.normal;nn for (var i = 0, il = normals.count; i < il; i++) {n _vector$4.x = normals.getX(i);n _vector$4.y = normals.getY(i);n _vector$4.z = normals.getZ(i);nn _vector$4.normalize();nn normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);n }n },n toNonIndexed: function toNonIndexed() {n function convertBufferAttribute(attribute, indices) {n var array = attribute.array;n var itemSize = attribute.itemSize;n var array2 = new array.constructor(indices.length * itemSize);n var index = 0,n index2 = 0;nn for (var i = 0, l = indices.length; i < l; i++) {n index = indices * itemSize;nn for (var j = 0; j < itemSize; j++) {n array2 = array;n }n }nn return new BufferAttribute(array2, itemSize);n } //nnn if (this.index === null) {n console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');n return this;n }nn var geometry2 = new BufferGeometry();n var indices = this.index.array;n var attributes = this.attributes; // attributesnn for (var name in attributes) {n var attribute = attributes;n var newAttribute = convertBufferAttribute(attribute, indices);n geometry2.addAttribute(name, newAttribute);n } // morph attributesnnn var morphAttributes = this.morphAttributes;nn for (name in morphAttributes) {n var morphArray = [];n var morphAttribute = morphAttributes; // morphAttribute: array of Float32BufferAttributesnn for (var i = 0, il = morphAttribute.length; i < il; i++) {n var attribute = morphAttribute;n var newAttribute = convertBufferAttribute(attribute, indices);n morphArray.push(newAttribute);n }nn geometry2.morphAttributes = morphArray;n } // groupsnnn var groups = this.groups;nn for (var i = 0, l = groups.length; i < l; i++) {n var group = groups;n geometry2.addGroup(group.start, group.count, group.materialIndex);n }nn return geometry2;n },n toJSON: function toJSON() {n var data = {n metadata: {n version: 4.5,n type: 'BufferGeometry',n generator: 'BufferGeometry.toJSON'n }n }; // standard BufferGeometry serializationnn data.uuid = this.uuid;n data.type = this.type;n if (this.name !== '') data.name = this.name;n if (Object.keys(this.userData).length > 0) data.userData = this.userData;nn if (this.parameters !== undefined) {n var parameters = this.parameters;nn for (var key in parameters) {n if (parameters !== undefined) data = parameters;n }nn return data;n }nn data.data = {n attributes: {}n };n var index = this.index;nn if (index !== null) {n data.data.index = {n type: index.array.constructor.name,n array: Array.prototype.slice.call(index.array)n };n }nn var attributes = this.attributes;nn for (var key in attributes) {n var attribute = attributes;n var attributeData = attribute.toJSON();n if (attribute.name !== '') attributeData.name = attribute.name;n data.data.attributes = attributeData;n }nn var morphAttributes = {};n var hasMorphAttributes = false;nn for (var key in this.morphAttributes) {n var attributeArray = this.morphAttributes;n var array = [];nn for (var i = 0, il = attributeArray.length; i < il; i++) {n var attribute = attributeArray;n var attributeData = attribute.toJSON();n if (attribute.name !== '') attributeData.name = attribute.name;n array.push(attributeData);n }nn if (array.length > 0) {n morphAttributes = array;n hasMorphAttributes = true;n }n }nn if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;n var groups = this.groups;nn if (groups.length > 0) {n data.data.groups = JSON.parse(JSON.stringify(groups));n }nn var boundingSphere = this.boundingSphere;nn if (boundingSphere !== null) {n data.data.boundingSphere = {n center: boundingSphere.center.toArray(),n radius: boundingSphere.radiusn };n }nn return data;n },n clone: function clone() {n /*n // Handle primitivesn t var parameters = this.parameters;n t if ( parameters !== undefined ) {n t var values = [];n t for ( var key in parameters ) {n t values.push( parameters[ key ] );n t }n t var geometry = Object.create( this.constructor.prototype );n this.constructor.apply( geometry, values );n return geometry;n t }n t return new this.constructor().copy( this );n */n return new BufferGeometry().copy(this);n },n copy: function copy(source) {n var name, i, l; // resetnn this.index = null;n this.attributes = {};n this.morphAttributes = {};n this.groups = [];n this.boundingBox = null;n this.boundingSphere = null; // namenn this.name = source.name; // indexnn var index = source.index;nn if (index !== null) {n this.setIndex(index.clone());n } // attributesnnn var attributes = source.attributes;nn for (name in attributes) {n var attribute = attributes;n this.addAttribute(name, attribute.clone());n } // morph attributesnnn var morphAttributes = source.morphAttributes;nn for (name in morphAttributes) {n var array = [];n var morphAttribute = morphAttributes; // morphAttribute: array of Float32BufferAttributesnn for (i = 0, l = morphAttribute.length; i < l; i++) {n array.push(morphAttribute.clone());n }nn this.morphAttributes = array;n } // groupsnnn var groups = source.groups;nn for (i = 0, l = groups.length; i < l; i++) {n var group = groups;n this.addGroup(group.start, group.count, group.materialIndex);n } // bounding boxnnn var boundingBox = source.boundingBox;nn if (boundingBox !== null) {n this.boundingBox = boundingBox.clone();n } // bounding spherennn var boundingSphere = source.boundingSphere;nn if (boundingSphere !== null) {n this.boundingSphere = boundingSphere.clone();n } // draw rangennn this.drawRange.start = source.drawRange.start;n this.drawRange.count = source.drawRange.count; // user datann this.userData = source.userData;n return this;n },n dispose: function dispose() {n this.dispatchEvent({n type: 'dispose'n });n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n * @author mikael emtinger / gomo.se/n * @author jonobr1 / jonobr1.com/n */nnvar _inverseMatrix = new Matrix4();nnvar _ray = new Ray();nnvar _sphere = new Sphere();nnvar _vA = new Vector3();nnvar _vB = new Vector3();nnvar _vC = new Vector3();nnvar _tempA = new Vector3();nnvar _tempB = new Vector3();nnvar _tempC = new Vector3();nnvar _morphA = new Vector3();nnvar _morphB = new Vector3();nnvar _morphC = new Vector3();nnvar _uvA = new Vector2();nnvar _uvB = new Vector2();nnvar _uvC = new Vector2();nnvar _intersectionPoint = new Vector3();nnvar _intersectionPointWorld = new Vector3();nnfunction Mesh(geometry, material) {n Object3D.call(this);n this.type = 'Mesh';n this.geometry = geometry !== undefined ? geometry : new BufferGeometry();n this.material = material !== undefined ? material : new MeshBasicMaterial({n color: Math.random() * 0xffffffn });n this.drawMode = TrianglesDrawMode;n this.updateMorphTargets();n}nnMesh.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Mesh,n isMesh: true,n setDrawMode: function setDrawMode(value) {n this.drawMode = value;n },n copy: function copy(source) {n Object3D.prototype.copy.call(this, source);n this.drawMode = source.drawMode;nn if (source.morphTargetInfluences !== undefined) {n this.morphTargetInfluences = source.morphTargetInfluences.slice();n }nn if (source.morphTargetDictionary !== undefined) {n this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);n }nn return this;n },n updateMorphTargets: function updateMorphTargets() {n var geometry = this.geometry;n var m, ml, name;nn if (geometry.isBufferGeometry) {n var morphAttributes = geometry.morphAttributes;n var keys = Object.keys(morphAttributes);nn if (keys.length > 0) {n var morphAttribute = morphAttributes[keys];nn if (morphAttribute !== undefined) {n this.morphTargetInfluences = [];n this.morphTargetDictionary = {};nn for (m = 0, ml = morphAttribute.length; m < ml; m++) {n name = morphAttribute.name || String(m);n this.morphTargetInfluences.push(0);n this.morphTargetDictionary = m;n }n }n }n } else {n var morphTargets = geometry.morphTargets;nn if (morphTargets !== undefined && morphTargets.length > 0) {n console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');n }n }n },n raycast: function raycast(raycaster, intersects) {n var geometry = this.geometry;n var material = this.material;n var matrixWorld = this.matrixWorld;n if (material === undefined) return; // Checking boundingSphere distance to raynn if (geometry.boundingSphere === null) geometry.computeBoundingSphere();nn _sphere.copy(geometry.boundingSphere);nn _sphere.applyMatrix4(matrixWorld);nn if (raycaster.ray.intersectsSphere(_sphere) === false) return; //nn _inverseMatrix.getInverse(matrixWorld);nn _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuingnnn if (geometry.boundingBox !== null) {n if (_ray.intersectsBox(geometry.boundingBox) === false) return;n }nn var intersection;nn if (geometry.isBufferGeometry) {n var a, b, c;n var index = geometry.index;n var position = geometry.attributes.position;n var morphPosition = geometry.morphAttributes.position;n var uv = geometry.attributes.uv;n var uv2 = geometry.attributes.uv2;n var groups = geometry.groups;n var drawRange = geometry.drawRange;n var i, j, il, jl;n var group, groupMaterial;n var start, end;nn if (index !== null) {n // indexed buffer geometryn if (Array.isArray(material)) {n for (i = 0, il = groups.length; i < il; i++) {n group = groups;n groupMaterial = material;n start = Math.max(group.start, drawRange.start);n end = Math.min(group.start + group.count, drawRange.start + drawRange.count);nn for (j = start, jl = end; j < jl; j += 3) {n a = index.getX(j);n b = index.getX(j + 1);n c = index.getX(j + 2);n intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);nn if (intersection) {n intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semanticsnn intersection.face.materialIndex = group.materialIndex;n intersects.push(intersection);n }n }n }n } else {n start = Math.max(0, drawRange.start);n end = Math.min(index.count, drawRange.start + drawRange.count);nn for (i = start, il = end; i < il; i += 3) {n a = index.getX(i);n b = index.getX(i + 1);n c = index.getX(i + 2);n intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);nn if (intersection) {n intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semanticsnn intersects.push(intersection);n }n }n }n } else if (position !== undefined) {n // non-indexed buffer geometryn if (Array.isArray(material)) {n for (i = 0, il = groups.length; i < il; i++) {n group = groups;n groupMaterial = material;n start = Math.max(group.start, drawRange.start);n end = Math.min(group.start + group.count, drawRange.start + drawRange.count);nn for (j = start, jl = end; j < jl; j += 3) {n a = j;n b = j + 1;n c = j + 2;n intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);nn if (intersection) {n intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semanticsnn intersection.face.materialIndex = group.materialIndex;n intersects.push(intersection);n }n }n }n } else {n start = Math.max(0, drawRange.start);n end = Math.min(position.count, drawRange.start + drawRange.count);nn for (i = start, il = end; i < il; i += 3) {n a = i;n b = i + 1;n c = i + 2;n intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);nn if (intersection) {n intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semanticsnn intersects.push(intersection);n }n }n }n }n } else if (geometry.isGeometry) {n var fvA, fvB, fvC;n var isMultiMaterial = Array.isArray(material);n var vertices = geometry.vertices;n var faces = geometry.faces;n var uvs;n var faceVertexUvs = geometry.faceVertexUvs;n if (faceVertexUvs.length > 0) uvs = faceVertexUvs;nn for (var f = 0, fl = faces.length; f < fl; f++) {n var face = faces;n var faceMaterial = isMultiMaterial ? material : material;n if (faceMaterial === undefined) continue;n fvA = vertices;n fvB = vertices;n fvC = vertices;n intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);nn if (intersection) {n if (uvs && uvs) {n var uvs_f = uvs;nn _uvA.copy(uvs_f);nn _uvB.copy(uvs_f);nn _uvC.copy(uvs_f);nn intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());n }nn intersection.face = face;n intersection.faceIndex = f;n intersects.push(intersection);n }n }n }n },n clone: function clone() {n return new this.constructor(this.geometry, this.material).copy(this);n }n});nnfunction checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {n var intersect;nn if (material.side === BackSide) {n intersect = ray.intersectTriangle(pC, pB, pA, true, point);n } else {n intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);n }nn if (intersect === null) return null;nn _intersectionPointWorld.copy(point);nn _intersectionPointWorld.applyMatrix4(object.matrixWorld);nn var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);n if (distance < raycaster.near || distance > raycaster.far) return null;n return {n distance: distance,n point: _intersectionPointWorld.clone(),n object: objectn };n}nnfunction checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {n _vA.fromBufferAttribute(position, a);nn _vB.fromBufferAttribute(position, b);nn _vC.fromBufferAttribute(position, c);nn var morphInfluences = object.morphTargetInfluences;nn if (material.morphTargets && morphPosition && morphInfluences) {n _morphA.set(0, 0, 0);nn _morphB.set(0, 0, 0);nn _morphC.set(0, 0, 0);nn for (var i = 0, il = morphPosition.length; i < il; i++) {n var influence = morphInfluences;n var morphAttribute = morphPosition;n if (influence === 0) continue;nn _tempA.fromBufferAttribute(morphAttribute, a);nn _tempB.fromBufferAttribute(morphAttribute, b);nn _tempC.fromBufferAttribute(morphAttribute, c);nn _morphA.addScaledVector(_tempA.sub(_vA), influence);nn _morphB.addScaledVector(_tempB.sub(_vB), influence);nn _morphC.addScaledVector(_tempC.sub(_vC), influence);n }nn _vA.add(_morphA);nn _vB.add(_morphB);nn _vC.add(_morphC);n }nn var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);nn if (intersection) {n if (uv) {n _uvA.fromBufferAttribute(uv, a);nn _uvB.fromBufferAttribute(uv, b);nn _uvC.fromBufferAttribute(uv, c);nn intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());n }nn if (uv2) {n _uvA.fromBufferAttribute(uv2, a);nn _uvB.fromBufferAttribute(uv2, b);nn _uvC.fromBufferAttribute(uv2, c);nn intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());n }nn var face = new Face3(a, b, c);n Triangle.getNormal(_vA, _vB, _vC, face.normal);n intersection.face = face;n }nn return intersection;n}n/**n * @author mrdoob / mrdoob.com/n * @author kile / kile.stravaganza.org/n * @author alteredq / alteredqualia.com/n * @author mikael emtinger / gomo.se/n * @author zz85 / www.lab4games.net/zz85/blogn * @author bhouston / clara.ion */nnnvar _geometryId = 0; // Geometry uses even numbers as Idnnvar _m1$3 = new Matrix4();nnvar _obj$1 = new Object3D();nnvar _offset$1 = new Vector3();nnfunction Geometry() {n Object.defineProperty(this, 'id', {n value: _geometryId += 2n });n this.uuid = _Math.generateUUID();n this.name = '';n this.type = 'Geometry';n this.vertices = [];n this.colors = [];n this.faces = [];n this.faceVertexUvs = [[]];n this.morphTargets = [];n this.morphNormals = [];n this.skinWeights = [];n this.skinIndices = [];n this.lineDistances = [];n this.boundingBox = null;n this.boundingSphere = null; // update flagsnn this.elementsNeedUpdate = false;n this.verticesNeedUpdate = false;n this.uvsNeedUpdate = false;n this.normalsNeedUpdate = false;n this.colorsNeedUpdate = false;n this.lineDistancesNeedUpdate = false;n this.groupsNeedUpdate = false;n}nnGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {n constructor: Geometry,n isGeometry: true,n applyMatrix: function applyMatrix(matrix) {n var normalMatrix = new Matrix3().getNormalMatrix(matrix);nn for (var i = 0, il = this.vertices.length; i < il; i++) {n var vertex = this.vertices;n vertex.applyMatrix4(matrix);n }nn for (var i = 0, il = this.faces.length; i < il; i++) {n var face = this.faces;n face.normal.applyMatrix3(normalMatrix).normalize();nn for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {n face.vertexNormals.applyMatrix3(normalMatrix).normalize();n }n }nn if (this.boundingBox !== null) {n this.computeBoundingBox();n }nn if (this.boundingSphere !== null) {n this.computeBoundingSphere();n }nn this.verticesNeedUpdate = true;n this.normalsNeedUpdate = true;n return this;n },n rotateX: function rotateX(angle) {n // rotate geometry around world x-axisn _m1$3.makeRotationX(angle);nn this.applyMatrix(_m1$3);n return this;n },n rotateY: function rotateY(angle) {n // rotate geometry around world y-axisn _m1$3.makeRotationY(angle);nn this.applyMatrix(_m1$3);n return this;n },n rotateZ: function rotateZ(angle) {n // rotate geometry around world z-axisn _m1$3.makeRotationZ(angle);nn this.applyMatrix(_m1$3);n return this;n },n translate: function translate(x, y, z) {n // translate geometryn _m1$3.makeTranslation(x, y, z);nn this.applyMatrix(_m1$3);n return this;n },n scale: function scale(x, y, z) {n // scale geometryn _m1$3.makeScale(x, y, z);nn this.applyMatrix(_m1$3);n return this;n },n lookAt: function lookAt(vector) {n _obj$1.lookAt(vector);nn _obj$1.updateMatrix();nn this.applyMatrix(_obj$1.matrix);n return this;n },n fromBufferGeometry: function fromBufferGeometry(geometry) {n var scope = this;n var indices = geometry.index !== null ? geometry.index.array : undefined;n var attributes = geometry.attributes;n var positions = attributes.position.array;n var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;n var colors = attributes.color !== undefined ? attributes.color.array : undefined;n var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;n var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;n if (uvs2 !== undefined) this.faceVertexUvs = [];nn for (var i = 0; i < positions.length; i += 3) {n scope.vertices.push(new Vector3().fromArray(positions, i));nn if (colors !== undefined) {n scope.colors.push(new Color().fromArray(colors, i));n }n }nn function addFace(a, b, c, materialIndex) {n var vertexColors = colors === undefined ? [] : [scope.colors.clone(), scope.colors.clone(), scope.colors.clone()];n var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];n var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);n scope.faces.push(face);nn if (uvs !== undefined) {n scope.faceVertexUvs.push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);n }nn if (uvs2 !== undefined) {n scope.faceVertexUvs.push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);n }n }nn var groups = geometry.groups;nn if (groups.length > 0) {n for (var i = 0; i < groups.length; i++) {n var group = groups;n var start = group.start;n var count = group.count;nn for (var j = start, jl = start + count; j < jl; j += 3) {n if (indices !== undefined) {n addFace(indices, indices[j + 1], indices[j + 2], group.materialIndex);n } else {n addFace(j, j + 1, j + 2, group.materialIndex);n }n }n }n } else {n if (indices !== undefined) {n for (var i = 0; i < indices.length; i += 3) {n addFace(indices, indices[i + 1], indices[i + 2]);n }n } else {n for (var i = 0; i < positions.length / 3; i += 3) {n addFace(i, i + 1, i + 2);n }n }n }nn this.computeFaceNormals();nn if (geometry.boundingBox !== null) {n this.boundingBox = geometry.boundingBox.clone();n }nn if (geometry.boundingSphere !== null) {n this.boundingSphere = geometry.boundingSphere.clone();n }nn return this;n },n center: function center() {n this.computeBoundingBox();n this.boundingBox.getCenter(_offset$1).negate();n this.translate(_offset$1.x, _offset$1.y, _offset$1.z);n return this;n },n normalize: function normalize() {n this.computeBoundingSphere();n var center = this.boundingSphere.center;n var radius = this.boundingSphere.radius;n var s = radius === 0 ? 1 : 1.0 / radius;n var matrix = new Matrix4();n matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);n this.applyMatrix(matrix);n return this;n },n computeFaceNormals: function computeFaceNormals() {n var cb = new Vector3(),n ab = new Vector3();nn for (var f = 0, fl = this.faces.length; f < fl; f++) {n var face = this.faces;n var vA = this.vertices;n var vB = this.vertices;n var vC = this.vertices;n cb.subVectors(vC, vB);n ab.subVectors(vA, vB);n cb.cross(ab);n cb.normalize();n face.normal.copy(cb);n }n },n computeVertexNormals: function computeVertexNormals(areaWeighted) {n if (areaWeighted === undefined) areaWeighted = true;n var v, vl, f, fl, face, vertices;n vertices = new Array(this.vertices.length);nn for (v = 0, vl = this.vertices.length; v < vl; v++) {n vertices = new Vector3();n }nn if (areaWeighted) {n // vertex normals weighted by triangle areasn // www.iquilezles.org/www/articles/normals/normals.htmn var vA, vB, vC;n var cb = new Vector3(),n ab = new Vector3();nn for (f = 0, fl = this.faces.length; f < fl; f++) {n face = this.faces;n vA = this.vertices;n vB = this.vertices;n vC = this.vertices;n cb.subVectors(vC, vB);n ab.subVectors(vA, vB);n cb.cross(ab);n vertices.add(cb);n vertices.add(cb);n vertices.add(cb);n }n } else {n this.computeFaceNormals();nn for (f = 0, fl = this.faces.length; f < fl; f++) {n face = this.faces;n vertices.add(face.normal);n vertices.add(face.normal);n vertices.add(face.normal);n }n }nn for (v = 0, vl = this.vertices.length; v < vl; v++) {n vertices.normalize();n }nn for (f = 0, fl = this.faces.length; f < fl; f++) {n face = this.faces;n var vertexNormals = face.vertexNormals;nn if (vertexNormals.length === 3) {n vertexNormals.copy(vertices);n vertexNormals.copy(vertices);n vertexNormals.copy(vertices);n } else {n vertexNormals = vertices.clone();n vertexNormals = vertices.clone();n vertexNormals = vertices.clone();n }n }nn if (this.faces.length > 0) {n this.normalsNeedUpdate = true;n }n },n computeFlatVertexNormals: function computeFlatVertexNormals() {n var f, fl, face;n this.computeFaceNormals();nn for (f = 0, fl = this.faces.length; f < fl; f++) {n face = this.faces;n var vertexNormals = face.vertexNormals;nn if (vertexNormals.length === 3) {n vertexNormals.copy(face.normal);n vertexNormals.copy(face.normal);n vertexNormals.copy(face.normal);n } else {n vertexNormals = face.normal.clone();n vertexNormals = face.normal.clone();n vertexNormals = face.normal.clone();n }n }nn if (this.faces.length > 0) {n this.normalsNeedUpdate = true;n }n },n computeMorphNormals: function computeMorphNormals() {n var i, il, f, fl, face; // save original normalsn // - create temp variables on first accessn // otherwise just copy (for faster repeated calls)nn for (f = 0, fl = this.faces.length; f < fl; f++) {n face = this.faces;nn if (!face.__originalFaceNormal) {n face.__originalFaceNormal = face.normal.clone();n } else {n face.__originalFaceNormal.copy(face.normal);n }nn if (!face.__originalVertexNormals) face.__originalVertexNormals = [];nn for (i = 0, il = face.vertexNormals.length; i < il; i++) {n if (!face.__originalVertexNormals) {n face.__originalVertexNormals = face.vertexNormals.clone();n } else {n face.__originalVertexNormals.copy(face.vertexNormals);n }n }n } // use temp geometry to compute face and vertex normals for each morphnnn var tmpGeo = new Geometry();n tmpGeo.faces = this.faces;nn for (i = 0, il = this.morphTargets.length; i < il; i++) {n // create on first accessn if (!this.morphNormals) {n this.morphNormals = {};n this.morphNormals.faceNormals = [];n this.morphNormals.vertexNormals = [];n var dstNormalsFace = this.morphNormals.faceNormals;n var dstNormalsVertex = this.morphNormals.vertexNormals;n var faceNormal, vertexNormals;nn for (f = 0, fl = this.faces.length; f < fl; f++) {n faceNormal = new Vector3();n vertexNormals = {n a: new Vector3(),n b: new Vector3(),n c: new Vector3()n };n dstNormalsFace.push(faceNormal);n dstNormalsVertex.push(vertexNormals);n }n }nn var morphNormals = this.morphNormals; // set vertices to morph targetnn tmpGeo.vertices = this.morphTargets.vertices; // compute morph normalsnn tmpGeo.computeFaceNormals();n tmpGeo.computeVertexNormals(); // store morph normalsnn var faceNormal, vertexNormals;nn for (f = 0, fl = this.faces.length; f < fl; f++) {n face = this.faces;n faceNormal = morphNormals.faceNormals;n vertexNormals = morphNormals.vertexNormals;n faceNormal.copy(face.normal);n vertexNormals.a.copy(face.vertexNormals);n vertexNormals.b.copy(face.vertexNormals);n vertexNormals.c.copy(face.vertexNormals);n }n } // restore original normalsnnn for (f = 0, fl = this.faces.length; f < fl; f++) {n face = this.faces;n face.normal = face.__originalFaceNormal;n face.vertexNormals = face.__originalVertexNormals;n }n },n computeBoundingBox: function computeBoundingBox() {n if (this.boundingBox === null) {n this.boundingBox = new Box3();n }nn this.boundingBox.setFromPoints(this.vertices);n },n computeBoundingSphere: function computeBoundingSphere() {n if (this.boundingSphere === null) {n this.boundingSphere = new Sphere();n }nn this.boundingSphere.setFromPoints(this.vertices);n },n merge: function merge(geometry, matrix, materialIndexOffset) {n if (!(geometry && geometry.isGeometry)) {n console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);n return;n }nn var normalMatrix,n vertexOffset = this.vertices.length,n vertices1 = this.vertices,n vertices2 = geometry.vertices,n faces1 = this.faces,n faces2 = geometry.faces,n colors1 = this.colors,n colors2 = geometry.colors;n if (materialIndexOffset === undefined) materialIndexOffset = 0;nn if (matrix !== undefined) {n normalMatrix = new Matrix3().getNormalMatrix(matrix);n } // verticesnnn for (var i = 0, il = vertices2.length; i < il; i++) {n var vertex = vertices2;n var vertexCopy = vertex.clone();n if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);n vertices1.push(vertexCopy);n } // colorsnnn for (var i = 0, il = colors2.length; i < il; i++) {n colors1.push(colors2.clone());n } // facesnnn for (i = 0, il = faces2.length; i < il; i++) {n var face = faces2,n faceCopy,n normal,n color,n faceVertexNormals = face.vertexNormals,n faceVertexColors = face.vertexColors;n faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);n faceCopy.normal.copy(face.normal);nn if (normalMatrix !== undefined) {n faceCopy.normal.applyMatrix3(normalMatrix).normalize();n }nn for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {n normal = faceVertexNormals.clone();nn if (normalMatrix !== undefined) {n normal.applyMatrix3(normalMatrix).normalize();n }nn faceCopy.vertexNormals.push(normal);n }nn faceCopy.color.copy(face.color);nn for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {n color = faceVertexColors;n faceCopy.vertexColors.push(color.clone());n }nn faceCopy.materialIndex = face.materialIndex + materialIndexOffset;n faces1.push(faceCopy);n } // uvsnnn for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {n var faceVertexUvs2 = geometry.faceVertexUvs;n if (this.faceVertexUvs === undefined) this.faceVertexUvs = [];nn for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {n var uvs2 = faceVertexUvs2,n uvsCopy = [];nn for (var k = 0, kl = uvs2.length; k < kl; k++) {n uvsCopy.push(uvs2.clone());n }nn this.faceVertexUvs.push(uvsCopy);n }n }n },n mergeMesh: function mergeMesh(mesh) {n if (!(mesh && mesh.isMesh)) {n console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);n return;n }nn if (mesh.matrixAutoUpdate) mesh.updateMatrix();n this.merge(mesh.geometry, mesh.matrix);n },nn /*n * Checks for duplicate vertices with hashmap.n * Duplicated vertices are removedn * and faces' vertices are updated.n */n mergeVertices: function mergeVertices() {n var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)nn var unique = [],n changes = [];n var v, key;n var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001nn var precision = Math.pow(10, precisionPoints);n var i, il, face;n var indices, j, jl;nn for (i = 0, il = this.vertices.length; i < il; i++) {n v = this.vertices;n key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);nn if (verticesMap === undefined) {n verticesMap = i;n unique.push(this.vertices);n changes = unique.length - 1;n } else {n //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap);n changes = changes[verticesMap];n }n } // if faces are completely degenerate after merging vertices, wen // have to remove them from the geometry.nnn var faceIndicesToRemove = [];nn for (i = 0, il = this.faces.length; i < il; i++) {n face = this.faces;n face.a = changes;n face.b = changes;n face.c = changes;n indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3n // we have to remove the face as nothing can be savednn for (var n = 0; n < 3; n++) {n if (indices === indices[(n + 1) % 3]) {n faceIndicesToRemove.push(i);n break;n }n }n }nn for (i = faceIndicesToRemove.length - 1; i >= 0; i–) {n var idx = faceIndicesToRemove;n this.faces.splice(idx, 1);nn for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {n this.faceVertexUvs.splice(idx, 1);n }n } // Use unique set of verticesnnn var diff = this.vertices.length - unique.length;n this.vertices = unique;n return diff;n },n setFromPoints: function setFromPoints(points) {n this.vertices = [];nn for (var i = 0, l = points.length; i < l; i++) {n var point = points;n this.vertices.push(new Vector3(point.x, point.y, point.z || 0));n }nn return this;n },n sortFacesByMaterialIndex: function sortFacesByMaterialIndex() {n var faces = this.faces;n var length = faces.length; // tag facesnn for (var i = 0; i < length; i++) {n faces._id = i;n } // sort facesnnn function materialIndexSort(a, b) {n return a.materialIndex - b.materialIndex;n }nn faces.sort(materialIndexSort); // sort uvsnn var uvs1 = this.faceVertexUvs;n var uvs2 = this.faceVertexUvs;n var newUvs1, newUvs2;n if (uvs1 && uvs1.length === length) newUvs1 = [];n if (uvs2 && uvs2.length === length) newUvs2 = [];nn for (var i = 0; i < length; i++) {n var id = faces._id;n if (newUvs1) newUvs1.push(uvs1);n if (newUvs2) newUvs2.push(uvs2);n }nn if (newUvs1) this.faceVertexUvs = newUvs1;n if (newUvs2) this.faceVertexUvs = newUvs2;n },n toJSON: function toJSON() {n var data = {n metadata: {n version: 4.5,n type: 'Geometry',n generator: 'Geometry.toJSON'n }n }; // standard Geometry serializationnn data.uuid = this.uuid;n data.type = this.type;n if (this.name !== '') data.name = this.name;nn if (this.parameters !== undefined) {n var parameters = this.parameters;nn for (var key in parameters) {n if (parameters !== undefined) data = parameters;n }nn return data;n }nn var vertices = [];nn for (var i = 0; i < this.vertices.length; i++) {n var vertex = this.vertices;n vertices.push(vertex.x, vertex.y, vertex.z);n }nn var faces = [];n var normals = [];n var normalsHash = {};n var colors = [];n var colorsHash = {};n var uvs = [];n var uvsHash = {};nn for (var i = 0; i < this.faces.length; i++) {n var face = this.faces;n var hasMaterial = true;n var hasFaceUv = false; // deprecatednn var hasFaceVertexUv = this.faceVertexUvs[i] !== undefined;n var hasFaceNormal = face.normal.length() > 0;n var hasFaceVertexNormal = face.vertexNormals.length > 0;n var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;n var hasFaceVertexColor = face.vertexColors.length > 0;n var faceType = 0;n faceType = setBit(faceType, 0, 0); // isQuadnn faceType = setBit(faceType, 1, hasMaterial);n faceType = setBit(faceType, 2, hasFaceUv);n faceType = setBit(faceType, 3, hasFaceVertexUv);n faceType = setBit(faceType, 4, hasFaceNormal);n faceType = setBit(faceType, 5, hasFaceVertexNormal);n faceType = setBit(faceType, 6, hasFaceColor);n faceType = setBit(faceType, 7, hasFaceVertexColor);n faces.push(faceType);n faces.push(face.a, face.b, face.c);n faces.push(face.materialIndex);nn if (hasFaceVertexUv) {n var faceVertexUvs = this.faceVertexUvs[i];n faces.push(getUvIndex(faceVertexUvs), getUvIndex(faceVertexUvs), getUvIndex(faceVertexUvs));n }nn if (hasFaceNormal) {n faces.push(getNormalIndex(face.normal));n }nn if (hasFaceVertexNormal) {n var vertexNormals = face.vertexNormals;n faces.push(getNormalIndex(vertexNormals), getNormalIndex(vertexNormals), getNormalIndex(vertexNormals));n }nn if (hasFaceColor) {n faces.push(getColorIndex(face.color));n }nn if (hasFaceVertexColor) {n var vertexColors = face.vertexColors;n faces.push(getColorIndex(vertexColors), getColorIndex(vertexColors), getColorIndex(vertexColors));n }n }nn function setBit(value, position, enabled) {n return enabled ? value | 1 << position : value & ~(1 << position);n }nn function getNormalIndex(normal) {n var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();nn if (normalsHash !== undefined) {n return normalsHash;n }nn normalsHash = normals.length / 3;n normals.push(normal.x, normal.y, normal.z);n return normalsHash;n }nn function getColorIndex(color) {n var hash = color.r.toString() + color.g.toString() + color.b.toString();nn if (colorsHash !== undefined) {n return colorsHash;n }nn colorsHash = colors.length;n colors.push(color.getHex());n return colorsHash;n }nn function getUvIndex(uv) {n var hash = uv.x.toString() + uv.y.toString();nn if (uvsHash !== undefined) {n return uvsHash;n }nn uvsHash = uvs.length / 2;n uvs.push(uv.x, uv.y);n return uvsHash;n }nn data.data = {};n data.data.vertices = vertices;n data.data.normals = normals;n if (colors.length > 0) data.data.colors = colors;n if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibilitynn data.data.faces = faces;n return data;n },n clone: function clone() {n /*n // Handle primitivesn t var parameters = this.parameters;n t if ( parameters !== undefined ) {n t var values = [];n t for ( var key in parameters ) {n t values.push( parameters[ key ] );n t }n t var geometry = Object.create( this.constructor.prototype );n this.constructor.apply( geometry, values );n return geometry;n t }n t return new this.constructor().copy( this );n */n return new Geometry().copy(this);n },n copy: function copy(source) {n var i, il, j, jl, k, kl; // resetnn this.vertices = [];n this.colors = [];n this.faces = [];n this.faceVertexUvs = [[]];n this.morphTargets = [];n this.morphNormals = [];n this.skinWeights = [];n this.skinIndices = [];n this.lineDistances = [];n this.boundingBox = null;n this.boundingSphere = null; // namenn this.name = source.name; // verticesnn var vertices = source.vertices;nn for (i = 0, il = vertices.length; i < il; i++) {n this.vertices.push(vertices.clone());n } // colorsnnn var colors = source.colors;nn for (i = 0, il = colors.length; i < il; i++) {n this.colors.push(colors.clone());n } // facesnnn var faces = source.faces;nn for (i = 0, il = faces.length; i < il; i++) {n this.faces.push(faces.clone());n } // face vertex uvsnnn for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {n var faceVertexUvs = source.faceVertexUvs;nn if (this.faceVertexUvs === undefined) {n this.faceVertexUvs = [];n }nn for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {n var uvs = faceVertexUvs,n uvsCopy = [];nn for (k = 0, kl = uvs.length; k < kl; k++) {n var uv = uvs;n uvsCopy.push(uv.clone());n }nn this.faceVertexUvs.push(uvsCopy);n }n } // morph targetsnnn var morphTargets = source.morphTargets;nn for (i = 0, il = morphTargets.length; i < il; i++) {n var morphTarget = {};n morphTarget.name = morphTargets.name; // verticesnn if (morphTargets.vertices !== undefined) {n morphTarget.vertices = [];nn for (j = 0, jl = morphTargets.vertices.length; j < jl; j++) {n morphTarget.vertices.push(morphTargets.vertices.clone());n }n } // normalsnnn if (morphTargets.normals !== undefined) {n morphTarget.normals = [];nn for (j = 0, jl = morphTargets.normals.length; j < jl; j++) {n morphTarget.normals.push(morphTargets.normals.clone());n }n }nn this.morphTargets.push(morphTarget);n } // morph normalsnnn var morphNormals = source.morphNormals;nn for (i = 0, il = morphNormals.length; i < il; i++) {n var morphNormal = {}; // vertex normalsnn if (morphNormals.vertexNormals !== undefined) {n morphNormal.vertexNormals = [];nn for (j = 0, jl = morphNormals.vertexNormals.length; j < jl; j++) {n var srcVertexNormal = morphNormals.vertexNormals;n var destVertexNormal = {};n destVertexNormal.a = srcVertexNormal.a.clone();n destVertexNormal.b = srcVertexNormal.b.clone();n destVertexNormal.c = srcVertexNormal.c.clone();n morphNormal.vertexNormals.push(destVertexNormal);n }n } // face normalsnnn if (morphNormals.faceNormals !== undefined) {n morphNormal.faceNormals = [];nn for (j = 0, jl = morphNormals.faceNormals.length; j < jl; j++) {n morphNormal.faceNormals.push(morphNormals.faceNormals.clone());n }n }nn this.morphNormals.push(morphNormal);n } // skin weightsnnn var skinWeights = source.skinWeights;nn for (i = 0, il = skinWeights.length; i < il; i++) {n this.skinWeights.push(skinWeights.clone());n } // skin indicesnnn var skinIndices = source.skinIndices;nn for (i = 0, il = skinIndices.length; i < il; i++) {n this.skinIndices.push(skinIndices.clone());n } // line distancesnnn var lineDistances = source.lineDistances;nn for (i = 0, il = lineDistances.length; i < il; i++) {n this.lineDistances.push(lineDistances);n } // bounding boxnnn var boundingBox = source.boundingBox;nn if (boundingBox !== null) {n this.boundingBox = boundingBox.clone();n } // bounding spherennn var boundingSphere = source.boundingSphere;nn if (boundingSphere !== null) {n this.boundingSphere = boundingSphere.clone();n } // update flagsnnn this.elementsNeedUpdate = source.elementsNeedUpdate;n this.verticesNeedUpdate = source.verticesNeedUpdate;n this.uvsNeedUpdate = source.uvsNeedUpdate;n this.normalsNeedUpdate = source.normalsNeedUpdate;n this.colorsNeedUpdate = source.colorsNeedUpdate;n this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;n this.groupsNeedUpdate = source.groupsNeedUpdate;n return this;n },n dispose: function dispose() {n this.dispatchEvent({n type: 'dispose'n });n }n});n/**n * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n */n// BoxGeometrynnfunction BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {n Geometry.call(this);n this.type = 'BoxGeometry';n this.parameters = {n width: width,n height: height,n depth: depth,n widthSegments: widthSegments,n heightSegments: heightSegments,n depthSegments: depthSegmentsn };n this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));n this.mergeVertices();n}nnBoxGeometry.prototype = Object.create(Geometry.prototype);nBoxGeometry.prototype.constructor = BoxGeometry; // BoxBufferGeometrynnfunction BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {n BufferGeometry.call(this);n this.type = 'BoxBufferGeometry';n this.parameters = {n width: width,n height: height,n depth: depth,n widthSegments: widthSegments,n heightSegments: heightSegments,n depthSegments: depthSegmentsn };n var scope = this;n width = width || 1;n height = height || 1;n depth = depth || 1; // segmentsnn widthSegments = Math.floor(widthSegments) || 1;n heightSegments = Math.floor(heightSegments) || 1;n depthSegments = Math.floor(depthSegments) || 1; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // helper variablesnn var numberOfVertices = 0;n var groupStart = 0; // build each side of the box geometrynn buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // pxnn buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nxnn buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // pynn buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // nynn buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pznn buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nzn // build geometrynn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));nn function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {n var segmentWidth = width / gridX;n var segmentHeight = height / gridY;n var widthHalf = width / 2;n var heightHalf = height / 2;n var depthHalf = depth / 2;n var gridX1 = gridX + 1;n var gridY1 = gridY + 1;n var vertexCounter = 0;n var groupCount = 0;n var ix, iy;n var vector = new Vector3(); // generate vertices, normals and uvsnn for (iy = 0; iy < gridY1; iy++) {n var y = iy * segmentHeight - heightHalf;nn for (ix = 0; ix < gridX1; ix++) {n var x = ix * segmentWidth - widthHalf; // set values to correct vector componentnn vector = x * udir;n vector = y * vdir;n vector = depthHalf; // now apply vector to vertex buffernn vertices.push(vector.x, vector.y, vector.z); // set values to correct vector componentnn vector = 0;n vector = 0;n vector = depth > 0 ? 1 : -1; // now apply vector to normal buffernn normals.push(vector.x, vector.y, vector.z); // uvsnn uvs.push(ix / gridX);n uvs.push(1 - iy / gridY); // countersnn vertexCounter += 1;n }n } // indicesn // 1. you need three indices to draw a single facen // 2. a single segment consists of two facesn // 3. so we need to generate six (2*3) indices per segmentnnn for (iy = 0; iy < gridY; iy++) {n for (ix = 0; ix < gridX; ix++) {n var a = numberOfVertices + ix + gridX1 * iy;n var b = numberOfVertices + ix + gridX1 * (iy + 1);n var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);n var d = numberOfVertices + (ix + 1) + gridX1 * iy; // facesnn indices.push(a, b, d);n indices.push(b, c, d); // increase counternn groupCount += 6;n }n } // add a group to the geometry. this will ensure multi material supportnnn scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groupsnn groupStart += groupCount; // update total number of verticesnn numberOfVertices += vertexCounter;n }n}nnBoxBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nBoxBufferGeometry.prototype.constructor = BoxBufferGeometry;n/**n * Uniform Utilitiesn */nnfunction cloneUniforms(src) {n var dst = {};nn for (var u in src) {n dst = {};nn for (var p in src) {n var property = src[p];nn if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {n dst[p] = property.clone();n } else if (Array.isArray(property)) {n dst[p] = property.slice();n } else {n dst[p] = property;n }n }n }nn return dst;n}nnfunction mergeUniforms(uniforms) {n var merged = {};nn for (var u = 0; u < uniforms.length; u++) {n var tmp = cloneUniforms(uniforms);nn for (var p in tmp) {n merged = tmp;n }n }nn return merged;n} // Legacynnnvar UniformsUtils = {n clone: cloneUniforms,n merge: mergeUniformsn};nvar default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";nvar default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";n/**n * @author alteredq / alteredqualia.com/n *n * parameters = {n * defines: { "label" : "value" },n * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },n *n * fragmentShader: <string>,n * vertexShader: <string>,n *n * wireframe: <boolean>,n * wireframeLinewidth: <float>,n *n * lights: <bool>,n *n * skinning: <bool>,n * morphTargets: <bool>,n * morphNormals: <bool>n * }n */nnfunction ShaderMaterial(parameters) {n Material.call(this);n this.type = 'ShaderMaterial';n this.defines = {};n this.uniforms = {};n this.vertexShader = default_vertex;n this.fragmentShader = default_fragment;n this.linewidth = 1;n this.wireframe = false;n this.wireframeLinewidth = 1;n this.fog = false; // set to use scene fognn this.lights = false; // set to use scene lightsnn this.clipping = false; // set to use user-defined clipping planesnn this.skinning = false; // set to use skinning attribute streamsnn this.morphTargets = false; // set to use morph targetsnn this.morphNormals = false; // set to use morph normalsnn this.extensions = {n derivatives: false,n // set to use derivativesn fragDepth: false,n // set to use fragment depth valuesn drawBuffers: false,n // set to use draw buffersn shaderTextureLOD: false // set to use shader texture LODnn }; // When rendered geometry doesn't include these attributes but the material does,n // use these default values in WebGL. This avoids errors when buffer data is missing.nn this.defaultAttributeValues = {n 'color': [1, 1, 1],n 'uv': [0, 0],n 'uv2': [0, 0]n };n this.index0AttributeName = undefined;n this.uniformsNeedUpdate = false;nn if (parameters !== undefined) {n if (parameters.attributes !== undefined) {n console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');n }nn this.setValues(parameters);n }n}nnShaderMaterial.prototype = Object.create(Material.prototype);nShaderMaterial.prototype.constructor = ShaderMaterial;nShaderMaterial.prototype.isShaderMaterial = true;nnShaderMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.fragmentShader = source.fragmentShader;n this.vertexShader = source.vertexShader;n this.uniforms = cloneUniforms(source.uniforms);n this.defines = Object.assign({}, source.defines);n this.wireframe = source.wireframe;n this.wireframeLinewidth = source.wireframeLinewidth;n this.lights = source.lights;n this.clipping = source.clipping;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.morphNormals = source.morphNormals;n this.extensions = source.extensions;n return this;n};nnShaderMaterial.prototype.toJSON = function (meta) {n var data = Material.prototype.toJSON.call(this, meta);n data.uniforms = {};nn for (var name in this.uniforms) {n var uniform = this.uniforms;n var value = uniform.value;nn if (value && value.isTexture) {n data.uniforms = {n type: 't',n value: value.toJSON(meta).uuidn };n } else if (value && value.isColor) {n data.uniforms = {n type: 'c',n value: value.getHex()n };n } else if (value && value.isVector2) {n data.uniforms = {n type: 'v2',n value: value.toArray()n };n } else if (value && value.isVector3) {n data.uniforms = {n type: 'v3',n value: value.toArray()n };n } else if (value && value.isVector4) {n data.uniforms = {n type: 'v4',n value: value.toArray()n };n } else if (value && value.isMatrix3) {n data.uniforms = {n type: 'm3',n value: value.toArray()n };n } else if (value && value.isMatrix4) {n data.uniforms = {n type: 'm4',n value: value.toArray()n };n } else {n data.uniforms = {n value: valuen }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so farn }n }nn if (Object.keys(this.defines).length > 0) data.defines = this.defines;n data.vertexShader = this.vertexShader;n data.fragmentShader = this.fragmentShader;n var extensions = {};nn for (var key in this.extensions) {n if (this.extensions === true) extensions = true;n }nn if (Object.keys(extensions).length > 0) data.extensions = extensions;n return data;n};n/**n * @author mrdoob / mrdoob.com/n * @author mikael emtinger / gomo.se/n * @author WestLangley / github.com/WestLangleyn*/nnnfunction Camera() {n Object3D.call(this);n this.type = 'Camera';n this.matrixWorldInverse = new Matrix4();n this.projectionMatrix = new Matrix4();n this.projectionMatrixInverse = new Matrix4();n}nnCamera.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Camera,n isCamera: true,n copy: function copy(source, recursive) {n Object3D.prototype.copy.call(this, source, recursive);n this.matrixWorldInverse.copy(source.matrixWorldInverse);n this.projectionMatrix.copy(source.projectionMatrix);n this.projectionMatrixInverse.copy(source.projectionMatrixInverse);n return this;n },n getWorldDirection: function getWorldDirection(target) {n if (target === undefined) {n console.warn('THREE.Camera: .getWorldDirection() target is now required');n target = new Vector3();n }nn this.updateMatrixWorld(true);n var e = this.matrixWorld.elements;n return target.set(-e, -e, -e).normalize();n },n updateMatrixWorld: function updateMatrixWorld(force) {n Object3D.prototype.updateMatrixWorld.call(this, force);n this.matrixWorldInverse.getInverse(this.matrixWorld);n },n clone: function clone() {n return new this.constructor().copy(this);n }n});n/**n * @author mrdoob / mrdoob.com/n * @author greggman / games.greggman.com/n * @author zz85 / www.lab4games.net/zz85/blogn * @author tschwn */nnfunction PerspectiveCamera(fov, aspect, near, far) {n Camera.call(this);n this.type = 'PerspectiveCamera';n this.fov = fov !== undefined ? fov : 50;n this.zoom = 1;n this.near = near !== undefined ? near : 0.1;n this.far = far !== undefined ? far : 2000;n this.focus = 10;n this.aspect = aspect !== undefined ? aspect : 1;n this.view = null;n this.filmGauge = 35; // width of the film (default in millimeters)nn this.filmOffset = 0; // horizontal film offset (same unit as gauge)nn this.updateProjectionMatrix();n}nnPerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {n constructor: PerspectiveCamera,n isPerspectiveCamera: true,n copy: function copy(source, recursive) {n Camera.prototype.copy.call(this, source, recursive);n this.fov = source.fov;n this.zoom = source.zoom;n this.near = source.near;n this.far = source.far;n this.focus = source.focus;n this.aspect = source.aspect;n this.view = source.view === null ? null : Object.assign({}, source.view);n this.filmGauge = source.filmGauge;n this.filmOffset = source.filmOffset;n return this;n },nn /**n * Sets the FOV by focal length in respect to the current .filmGauge.n *n * The default film gauge is 35, so that the focal length can be specified forn * a 35mm (full frame) camera.n *n * Values for focal length and film gauge must have the same unit.n */n setFocalLength: function setFocalLength(focalLength) {n // see www.bobatkins.com/photography/technical/field_of_view.htmln var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;n this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);n this.updateProjectionMatrix();n },nn /**n * Calculates the focal length from the current .fov and .filmGauge.n */n getFocalLength: function getFocalLength() {n var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);n return 0.5 * this.getFilmHeight() / vExtentSlope;n },n getEffectiveFOV: function getEffectiveFOV() {n return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);n },n getFilmWidth: function getFilmWidth() {n // film not completely covered in portrait format (aspect < 1)n return this.filmGauge * Math.min(this.aspect, 1);n },n getFilmHeight: function getFilmHeight() {n // film not completely covered in landscape format (aspect > 1)n return this.filmGauge / Math.max(this.aspect, 1);n },nn /**n * Sets an offset in a larger frustum. This is useful for multi-window orn * multi-monitor/multi-machine setups.n *n * For example, if you have 3x2 monitors and each monitor is 1920x1080 andn * the monitors are in grid like thisn *n * ---
—---
n * | A | B | C |n * ---
—---
n * | D | E | F |n * ---
—---
n *n * then for each monitor you would call it like thisn *n * var w = 1920;n * var h = 1080;n * var fullWidth = w * 3;n * var fullHeight = h * 2;n *n * –A–n * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );n * –B–n * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );n * –C–n * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );n * –D–n * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );n * –E–n * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );n * –F–n * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );n *n * Note there is no reason monitors have to be the same size or in a grid.n */n setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {n this.aspect = fullWidth / fullHeight;nn if (this.view === null) {n this.view = {n enabled: true,n fullWidth: 1,n fullHeight: 1,n offsetX: 0,n offsetY: 0,n width: 1,n height: 1n };n }nn this.view.enabled = true;n this.view.fullWidth = fullWidth;n this.view.fullHeight = fullHeight;n this.view.offsetX = x;n this.view.offsetY = y;n this.view.width = width;n this.view.height = height;n this.updateProjectionMatrix();n },n clearViewOffset: function clearViewOffset() {n if (this.view !== null) {n this.view.enabled = false;n }nn this.updateProjectionMatrix();n },n updateProjectionMatrix: function updateProjectionMatrix() {n var near = this.near,n top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,n height = 2 * top,n width = this.aspect * height,n left = -0.5 * width,n view = this.view;nn if (this.view !== null && this.view.enabled) {n var fullWidth = view.fullWidth,n fullHeight = view.fullHeight;n left += view.offsetX * width / fullWidth;n top -= view.offsetY * height / fullHeight;n width *= view.width / fullWidth;n height *= view.height / fullHeight;n }nn var skew = this.filmOffset;n if (skew !== 0) left += near * skew / this.getFilmWidth();n this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);n this.projectionMatrixInverse.getInverse(this.projectionMatrix);n },n toJSON: function toJSON(meta) {n var data = Object3D.prototype.toJSON.call(this, meta);n data.object.fov = this.fov;n data.object.zoom = this.zoom;n data.object.near = this.near;n data.object.far = this.far;n data.object.focus = this.focus;n data.object.aspect = this.aspect;n if (this.view !== null) data.object.view = Object.assign({}, this.view);n data.object.filmGauge = this.filmGauge;n data.object.filmOffset = this.filmOffset;n return data;n }n});n/**n * Camera for rendering cube mapsn *t- renders scene into axis-aligned cuben *n * @author alteredq / alteredqualia.com/n */nnvar fov = 90,n aspect = 1;nnfunction CubeCamera(near, far, cubeResolution, options) {n Object3D.call(this);n this.type = 'CubeCamera';n var cameraPX = new PerspectiveCamera(fov, aspect, near, far);n cameraPX.up.set(0, -1, 0);n cameraPX.lookAt(new Vector3(1, 0, 0));n this.add(cameraPX);n var cameraNX = new PerspectiveCamera(fov, aspect, near, far);n cameraNX.up.set(0, -1, 0);n cameraNX.lookAt(new Vector3(-1, 0, 0));n this.add(cameraNX);n var cameraPY = new PerspectiveCamera(fov, aspect, near, far);n cameraPY.up.set(0, 0, 1);n cameraPY.lookAt(new Vector3(0, 1, 0));n this.add(cameraPY);n var cameraNY = new PerspectiveCamera(fov, aspect, near, far);n cameraNY.up.set(0, 0, -1);n cameraNY.lookAt(new Vector3(0, -1, 0));n this.add(cameraNY);n var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);n cameraPZ.up.set(0, -1, 0);n cameraPZ.lookAt(new Vector3(0, 0, 1));n this.add(cameraPZ);n var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);n cameraNZ.up.set(0, -1, 0);n cameraNZ.lookAt(new Vector3(0, 0, -1));n this.add(cameraNZ);n options = options || {n format: RGBFormat,n magFilter: LinearFilter,n minFilter: LinearFiltern };n this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);n this.renderTarget.texture.name = "CubeCamera";nn this.update = function (renderer, scene) {n if (this.parent === null) this.updateMatrixWorld();n var currentRenderTarget = renderer.getRenderTarget();n var renderTarget = this.renderTarget;n var generateMipmaps = renderTarget.texture.generateMipmaps;n renderTarget.texture.generateMipmaps = false;n renderer.setRenderTarget(renderTarget, 0);n renderer.render(scene, cameraPX);n renderer.setRenderTarget(renderTarget, 1);n renderer.render(scene, cameraNX);n renderer.setRenderTarget(renderTarget, 2);n renderer.render(scene, cameraPY);n renderer.setRenderTarget(renderTarget, 3);n renderer.render(scene, cameraNY);n renderer.setRenderTarget(renderTarget, 4);n renderer.render(scene, cameraPZ);n renderTarget.texture.generateMipmaps = generateMipmaps;n renderer.setRenderTarget(renderTarget, 5);n renderer.render(scene, cameraNZ);n renderer.setRenderTarget(currentRenderTarget);n };nn this.clear = function (renderer, color, depth, stencil) {n var currentRenderTarget = renderer.getRenderTarget();n var renderTarget = this.renderTarget;nn for (var i = 0; i < 6; i++) {n renderer.setRenderTarget(renderTarget, i);n renderer.clear(color, depth, stencil);n }nn renderer.setRenderTarget(currentRenderTarget);n };n}nnCubeCamera.prototype = Object.create(Object3D.prototype);nCubeCamera.prototype.constructor = CubeCamera;n/**n * @author alteredq / alteredqualia.comn * @author WestLangley / github.com/WestLangleyn */nnfunction WebGLRenderTargetCube(width, height, options) {n WebGLRenderTarget.call(this, width, height, options);n}nnWebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);nWebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;nWebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;nnWebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {n this.texture.type = texture.type;n this.texture.format = texture.format;n this.texture.encoding = texture.encoding;n var scene = new Scene();n var shader = {n uniforms: {n tEquirect: {n value: nulln }n },n vertexShader: ["varying vec3 vWorldDirection;", "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {", "treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );", "}", "void main() {", "tvWorldDirection = transformDirection( position, modelMatrix );", "t#include <begin_vertex>", "t#include <project_vertex>", "}"].join('\n'),n fragmentShader: ["uniform sampler2D tEquirect;", "varying vec3 vWorldDirection;", "#define RECIPROCAL_PI 0.31830988618", "#define RECIPROCAL_PI2 0.15915494", "void main() {", "tvec3 direction = normalize( vWorldDirection );", "tvec2 sampleUV;", "tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;", "tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", "tgl_FragColor = texture2D( tEquirect, sampleUV );", "}"].join('\n')n };n var material = new ShaderMaterial({n type: 'CubemapFromEquirect',n uniforms: cloneUniforms(shader.uniforms),n vertexShader: shader.vertexShader,n fragmentShader: shader.fragmentShader,n side: BackSide,n blending: NoBlendingn });n material.uniforms.tEquirect.value = texture;n var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);n scene.add(mesh);n var camera = new CubeCamera(1, 10, 1);n camera.renderTarget = this;n camera.renderTarget.texture.name = 'CubeCameraTexture';n camera.update(renderer, scene);n mesh.geometry.dispose();n mesh.material.dispose();n return this;n};n/**n * @author alteredq / alteredqualia.com/n */nnnfunction DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {n Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);n this.image = {n data: data,n width: width,n height: heightn };n this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;n this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;n this.generateMipmaps = false;n this.flipY = false;n this.unpackAlignment = 1;n}nnDataTexture.prototype = Object.create(Texture.prototype);nDataTexture.prototype.constructor = DataTexture;nDataTexture.prototype.isDataTexture = true;n/**n * @author bhouston / clara.ion */nnvar _vector1 = new Vector3();nnvar _vector2 = new Vector3();nnvar _normalMatrix = new Matrix3();nnfunction Plane(normal, constant) {n // normal is assumed to be normalizedn this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);n this.constant = constant !== undefined ? constant : 0;n}nnObject.assign(Plane.prototype, {n isPlane: true,n set: function set(normal, constant) {n this.normal.copy(normal);n this.constant = constant;n return this;n },n setComponents: function setComponents(x, y, z, w) {n this.normal.set(x, y, z);n this.constant = w;n return this;n },n setFromNormalAndCoplanarPoint: function setFromNormalAndCoplanarPoint(normal, point) {n this.normal.copy(normal);n this.constant = -point.dot(this.normal);n return this;n },n setFromCoplanarPoints: function setFromCoplanarPoints(a, b, c) {n var 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)?nnn this.setFromNormalAndCoplanarPoint(normal, a);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(plane) {n this.normal.copy(plane.normal);n this.constant = plane.constant;n return this;n },n normalize: function normalize() {n // Note: will lead to a divide by zero if the plane is invalid.n var inverseNormalLength = 1.0 / this.normal.length();n this.normal.multiplyScalar(inverseNormalLength);n this.constant *= inverseNormalLength;n return this;n },n negate: function negate() {n this.constant *= -1;n this.normal.negate();n return this;n },n distanceToPoint: function distanceToPoint(point) {n return this.normal.dot(point) + this.constant;n },n distanceToSphere: function distanceToSphere(sphere) {n return this.distanceToPoint(sphere.center) - sphere.radius;n },n projectPoint: function projectPoint(point, target) {n if (target === undefined) {n console.warn('THREE.Plane: .projectPoint() target is now required');n target = new Vector3();n }nn return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);n },n intersectLine: function intersectLine(line, target) {n if (target === undefined) {n console.warn('THREE.Plane: .intersectLine() target is now required');n target = new Vector3();n }nn var direction = line.delta(_vector1);n var denominator = this.normal.dot(direction);nn if (denominator === 0) {n // line is coplanar, return originn if (this.distanceToPoint(line.start) === 0) {n return target.copy(line.start);n } // Unsure if this is the correct method to handle this case.nnn return undefined;n }nn var t = -(line.start.dot(this.normal) + this.constant) / denominator;nn if (t < 0 || t > 1) {n return undefined;n }nn return target.copy(direction).multiplyScalar(t).add(line.start);n },n intersectsLine: function intersectsLine(line) {n // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.n var startSign = this.distanceToPoint(line.start);n var endSign = this.distanceToPoint(line.end);n return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;n },n intersectsBox: function intersectsBox(box) {n return box.intersectsPlane(this);n },n intersectsSphere: function intersectsSphere(sphere) {n return sphere.intersectsPlane(this);n },n coplanarPoint: function coplanarPoint(target) {n if (target === undefined) {n console.warn('THREE.Plane: .coplanarPoint() target is now required');n target = new Vector3();n }nn return target.copy(this.normal).multiplyScalar(-this.constant);n },n applyMatrix4: function applyMatrix4(matrix, optionalNormalMatrix) {n var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);nn var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);n var normal = this.normal.applyMatrix3(normalMatrix).normalize();n this.constant = -referencePoint.dot(normal);n return this;n },n translate: function translate(offset) {n this.constant -= offset.dot(this.normal);n return this;n },n equals: function equals(plane) {n return plane.normal.equals(this.normal) && plane.constant === this.constant;n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n * @author bhouston / clara.ion */nnvar _sphere$1 = new Sphere();nnvar _vector$5 = new Vector3();nnfunction Frustum(p0, p1, p2, p3, p4, p5) {n this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];n}nnObject.assign(Frustum.prototype, {n set: function set(p0, p1, p2, p3, p4, p5) {n var planes = this.planes;n planes.copy(p0);n planes.copy(p1);n planes.copy(p2);n planes.copy(p3);n planes.copy(p4);n planes.copy(p5);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(frustum) {n var planes = this.planes;nn for (var i = 0; i < 6; i++) {n planes.copy(frustum.planes);n }nn return this;n },n setFromMatrix: function setFromMatrix(m) {n var planes = this.planes;n var me = m.elements;n var me0 = me,n me1 = me,n me2 = me,n me3 = me;n var me4 = me,n me5 = me,n me6 = me,n me7 = me;n var me8 = me,n me9 = me,n me10 = me,n me11 = me;n var me12 = me,n me13 = me,n me14 = me,n me15 = me;n planes.setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();n planes.setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();n planes.setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();n planes.setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();n planes.setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();n planes.setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();n return this;n },n intersectsObject: function intersectsObject(object) {n var geometry = object.geometry;n if (geometry.boundingSphere === null) geometry.computeBoundingSphere();nn _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);nn return this.intersectsSphere(_sphere$1);n },n intersectsSprite: function intersectsSprite(sprite) {n _sphere$1.center.set(0, 0, 0);nn _sphere$1.radius = 0.7071067811865476;nn _sphere$1.applyMatrix4(sprite.matrixWorld);nn return this.intersectsSphere(_sphere$1);n },n intersectsSphere: function intersectsSphere(sphere) {n var planes = this.planes;n var center = sphere.center;n var negRadius = -sphere.radius;nn for (var i = 0; i < 6; i++) {n var distance = planes.distanceToPoint(center);nn if (distance < negRadius) {n return false;n }n }nn return true;n },n intersectsBox: function intersectsBox(box) {n var planes = this.planes;nn for (var i = 0; i < 6; i++) {n var plane = planes; // corner at max distancenn _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;n _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;n _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;nn if (plane.distanceToPoint(_vector$5) < 0) {n return false;n }n }nn return true;n },n containsPoint: function containsPoint(point) {n var planes = this.planes;nn for (var i = 0; i < 6; i++) {n if (planes.distanceToPoint(point) < 0) {n return false;n }n }nn return true;n }n});nvar alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";nvar alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";nvar alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";nvar 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";nvar aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";nvar begin_vertex = "vec3 transformed = vec3( position );";nvar beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";nvar 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";nvar 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 ) {\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 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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";nvar clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";nvar clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";nvar clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";nvar clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";nvar color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";nvar color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";nvar color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";nvar color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";nvar common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define 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}";nvar cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize®;\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif";nvar defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";nvar displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";nvar displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif";nvar emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";nvar emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";nvar encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";nvar 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 = min( floor( D ) / 255.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}";nvar envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, 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_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\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";nvar 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";nvar 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";nvar 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";nvar envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\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";nvar fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";nvar fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";nvar 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";nvar 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";nvar gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif";nvar lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";nvar lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";nvar lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\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;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\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#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\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#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\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#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\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#endif";nvar lights_pars_begin = "uniform 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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\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";nvar 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\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 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 vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 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\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";nvar lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";nvar lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\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)";nvar lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 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 = saturate( clearcoat );\tmaterial.clearcoatRoughness = clamp( clearcoatRoughness, 0.04, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";nvar lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\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.indirectDiffuse += 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}";nvar lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = 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#pragma unroll_loop\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\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\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\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\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\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\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#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\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";nvar lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * 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";nvar 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";nvar logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";nvar logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n#endif";nvar logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";nvar logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif";nvar map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";nvar map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";nvar map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif";nvar map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";nvar metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";nvar metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";nvar morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif";nvar morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";nvar morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";nvar normal_fragment_begin = "#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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";nvar 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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, normalScale, normalMap );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";nvar 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, vec2 normalScale, in sampler2D normalMap ) {\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\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy *= normalScale;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvec3 NfromST = cross( S, T );\n\t\t\tif( dot( NfromST, N ) > 0.0 ) {\n\t\t\t\tS *= -1.0;\n\t\t\t\tT *= -1.0;\n\t\t\t}\n\t\t#else\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";nvar clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";nvar clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = clearcoatNormalScale * mapN.xy;\n\t\tclearcoatNormal = normalize( vTBN * mapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatNormalScale, clearcoatNormalMap );\n\t#endif\n#endif";nvar clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";nvar 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 encodeHalfRGBA ( vec2 v ) {\n\tvec4 encoded = vec4( 0.0 );\n\tconst vec2 offset = vec2( 1.0 / 255.0, 0.0 );\n\tencoded.xy = vec2( v.x, fract( v.x * 255.0 ) );\n\tencoded.xy = encoded.xy - ( encoded.yy * offset );\n\tencoded.zw = vec2( v.y, fract( v.y * 255.0 ) );\n\tencoded.zw = encoded.zw - ( encoded.ww * offset );\n\treturn encoded;\n}\nvec2 decodeHalfRGBA( 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}";nvar premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";nvar project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;";nvar dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";nvar dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";nvar roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";nvar roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";nvar 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#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#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#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 decodeHalfRGBA( 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 texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = ( floor( uv * size - 0.5 ) + 0.5 ) * texelSize;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\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 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\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\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";nvar 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#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#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#endif\n#endif";nvar shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";nvar shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}";nvar 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";nvar 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";nvar 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";nvar skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";nvar specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";nvar specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";nvar tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";nvar tonemapping_pars_fragment = "#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\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}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\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 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";nvar uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";nvar uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";nvar uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";nvar uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";nvar uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";nvar uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";nvar worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif";nvar background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";nvar 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}";nvar cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";nvar cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";nvar depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}";nvar depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}";nvar distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";nvar distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";nvar equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";nvar equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";nvar linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";nvar linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";nvar meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";nvar meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";nvar 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 <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\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 <lightmap_fragment>\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 <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";nvar 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 <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";nvar 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 <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";nvar meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";nvar meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";nvar meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";nvar meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\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 <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";nvar 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 <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\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 <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";nvar 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 <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";nvar 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 <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\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 <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";nvar points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";nvar points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";nvar shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}";nvar shadow_vert = "#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";nvar sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";nvar sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\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 = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\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 <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";nvar ShaderChunk = {n alphamap_fragment: alphamap_fragment,n alphamap_pars_fragment: alphamap_pars_fragment,n alphatest_fragment: alphatest_fragment,n aomap_fragment: aomap_fragment,n aomap_pars_fragment: aomap_pars_fragment,n begin_vertex: begin_vertex,n beginnormal_vertex: beginnormal_vertex,n bsdfs: bsdfs,n bumpmap_pars_fragment: bumpmap_pars_fragment,n clipping_planes_fragment: clipping_planes_fragment,n clipping_planes_pars_fragment: clipping_planes_pars_fragment,n clipping_planes_pars_vertex: clipping_planes_pars_vertex,n clipping_planes_vertex: clipping_planes_vertex,n color_fragment: color_fragment,n color_pars_fragment: color_pars_fragment,n color_pars_vertex: color_pars_vertex,n color_vertex: color_vertex,n common: common,n cube_uv_reflection_fragment: cube_uv_reflection_fragment,n defaultnormal_vertex: defaultnormal_vertex,n displacementmap_pars_vertex: displacementmap_pars_vertex,n displacementmap_vertex: displacementmap_vertex,n emissivemap_fragment: emissivemap_fragment,n emissivemap_pars_fragment: emissivemap_pars_fragment,n encodings_fragment: encodings_fragment,n encodings_pars_fragment: encodings_pars_fragment,n envmap_fragment: envmap_fragment,n envmap_common_pars_fragment: envmap_common_pars_fragment,n envmap_pars_fragment: envmap_pars_fragment,n envmap_pars_vertex: envmap_pars_vertex,n envmap_physical_pars_fragment: envmap_physical_pars_fragment,n envmap_vertex: envmap_vertex,n fog_vertex: fog_vertex,n fog_pars_vertex: fog_pars_vertex,n fog_fragment: fog_fragment,n fog_pars_fragment: fog_pars_fragment,n gradientmap_pars_fragment: gradientmap_pars_fragment,n lightmap_fragment: lightmap_fragment,n lightmap_pars_fragment: lightmap_pars_fragment,n lights_lambert_vertex: lights_lambert_vertex,n lights_pars_begin: lights_pars_begin,n lights_phong_fragment: lights_phong_fragment,n lights_phong_pars_fragment: lights_phong_pars_fragment,n lights_physical_fragment: lights_physical_fragment,n lights_physical_pars_fragment: lights_physical_pars_fragment,n lights_fragment_begin: lights_fragment_begin,n lights_fragment_maps: lights_fragment_maps,n lights_fragment_end: lights_fragment_end,n logdepthbuf_fragment: logdepthbuf_fragment,n logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,n logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,n logdepthbuf_vertex: logdepthbuf_vertex,n map_fragment: map_fragment,n map_pars_fragment: map_pars_fragment,n map_particle_fragment: map_particle_fragment,n map_particle_pars_fragment: map_particle_pars_fragment,n metalnessmap_fragment: metalnessmap_fragment,n metalnessmap_pars_fragment: metalnessmap_pars_fragment,n morphnormal_vertex: morphnormal_vertex,n morphtarget_pars_vertex: morphtarget_pars_vertex,n morphtarget_vertex: morphtarget_vertex,n normal_fragment_begin: normal_fragment_begin,n normal_fragment_maps: normal_fragment_maps,n normalmap_pars_fragment: normalmap_pars_fragment,n clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,n clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,n clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,n packing: packing,n premultiplied_alpha_fragment: premultiplied_alpha_fragment,n project_vertex: project_vertex,n dithering_fragment: dithering_fragment,n dithering_pars_fragment: dithering_pars_fragment,n roughnessmap_fragment: roughnessmap_fragment,n roughnessmap_pars_fragment: roughnessmap_pars_fragment,n shadowmap_pars_fragment: shadowmap_pars_fragment,n shadowmap_pars_vertex: shadowmap_pars_vertex,n shadowmap_vertex: shadowmap_vertex,n shadowmask_pars_fragment: shadowmask_pars_fragment,n skinbase_vertex: skinbase_vertex,n skinning_pars_vertex: skinning_pars_vertex,n skinning_vertex: skinning_vertex,n skinnormal_vertex: skinnormal_vertex,n specularmap_fragment: specularmap_fragment,n specularmap_pars_fragment: specularmap_pars_fragment,n tonemapping_fragment: tonemapping_fragment,n tonemapping_pars_fragment: tonemapping_pars_fragment,n uv_pars_fragment: uv_pars_fragment,n uv_pars_vertex: uv_pars_vertex,n uv_vertex: uv_vertex,n uv2_pars_fragment: uv2_pars_fragment,n uv2_pars_vertex: uv2_pars_vertex,n uv2_vertex: uv2_vertex,n worldpos_vertex: worldpos_vertex,n background_frag: background_frag,n background_vert: background_vert,n cube_frag: cube_frag,n cube_vert: cube_vert,n depth_frag: depth_frag,n depth_vert: depth_vert,n distanceRGBA_frag: distanceRGBA_frag,n distanceRGBA_vert: distanceRGBA_vert,n equirect_frag: equirect_frag,n equirect_vert: equirect_vert,n linedashed_frag: linedashed_frag,n linedashed_vert: linedashed_vert,n meshbasic_frag: meshbasic_frag,n meshbasic_vert: meshbasic_vert,n meshlambert_frag: meshlambert_frag,n meshlambert_vert: meshlambert_vert,n meshmatcap_frag: meshmatcap_frag,n meshmatcap_vert: meshmatcap_vert,n meshphong_frag: meshphong_frag,n meshphong_vert: meshphong_vert,n meshphysical_frag: meshphysical_frag,n meshphysical_vert: meshphysical_vert,n normal_frag: normal_frag,n normal_vert: normal_vert,n points_frag: points_frag,n points_vert: points_vert,n shadow_frag: shadow_frag,n shadow_vert: shadow_vert,n sprite_frag: sprite_frag,n sprite_vert: sprite_vertn};n/**n * Uniforms library for shared webgl shadersn */nnvar UniformsLib = {n common: {n diffuse: {n value: new Color(0xeeeeee)n },n opacity: {n value: 1.0n },n map: {n value: nulln },n uvTransform: {n value: new Matrix3()n },n alphaMap: {n value: nulln }n },n specularmap: {n specularMap: {n value: nulln }n },n envmap: {n envMap: {n value: nulln },n flipEnvMap: {n value: -1n },n reflectivity: {n value: 1.0n },n refractionRatio: {n value: 0.98n },n maxMipLevel: {n value: 0n }n },n aomap: {n aoMap: {n value: nulln },n aoMapIntensity: {n value: 1n }n },n lightmap: {n lightMap: {n value: nulln },n lightMapIntensity: {n value: 1n }n },n emissivemap: {n emissiveMap: {n value: nulln }n },n bumpmap: {n bumpMap: {n value: nulln },n bumpScale: {n value: 1n }n },n normalmap: {n normalMap: {n value: nulln },n normalScale: {n value: new Vector2(1, 1)n }n },n displacementmap: {n displacementMap: {n value: nulln },n displacementScale: {n value: 1n },n displacementBias: {n value: 0n }n },n roughnessmap: {n roughnessMap: {n value: nulln }n },n metalnessmap: {n metalnessMap: {n value: nulln }n },n gradientmap: {n gradientMap: {n value: nulln }n },n fog: {n fogDensity: {n value: 0.00025n },n fogNear: {n value: 1n },n fogFar: {n value: 2000n },n fogColor: {n value: new Color(0xffffff)n }n },n lights: {n ambientLightColor: {n value: []n },n lightProbe: {n value: []n },n directionalLights: {n value: [],n properties: {n direction: {},n color: {},n shadow: {},n shadowBias: {},n shadowRadius: {},n shadowMapSize: {}n }n },n directionalShadowMap: {n value: []n },n directionalShadowMatrix: {n value: []n },n spotLights: {n value: [],n properties: {n color: {},n position: {},n direction: {},n distance: {},n coneCos: {},n penumbraCos: {},n decay: {},n shadow: {},n shadowBias: {},n shadowRadius: {},n shadowMapSize: {}n }n },n spotShadowMap: {n value: []n },n spotShadowMatrix: {n value: []n },n pointLights: {n value: [],n properties: {n color: {},n position: {},n decay: {},n distance: {},n shadow: {},n shadowBias: {},n shadowRadius: {},n shadowMapSize: {},n shadowCameraNear: {},n shadowCameraFar: {}n }n },n pointShadowMap: {n value: []n },n pointShadowMatrix: {n value: []n },n hemisphereLights: {n value: [],n properties: {n direction: {},n skyColor: {},n groundColor: {}n }n },n // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main srcn rectAreaLights: {n value: [],n properties: {n color: {},n position: {},n width: {},n height: {}n }n }n },n points: {n diffuse: {n value: new Color(0xeeeeee)n },n opacity: {n value: 1.0n },n size: {n value: 1.0n },n scale: {n value: 1.0n },n map: {n value: nulln },n uvTransform: {n value: new Matrix3()n }n },n sprite: {n diffuse: {n value: new Color(0xeeeeee)n },n opacity: {n value: 1.0n },n center: {n value: new Vector2(0.5, 0.5)n },n rotation: {n value: 0.0n },n map: {n value: nulln },n uvTransform: {n value: new Matrix3()n }n }n};n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n * @author mikael emtinger / gomo.se/n */nnvar ShaderLib = {n basic: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),n vertexShader: ShaderChunk.meshbasic_vert,n fragmentShader: ShaderChunk.meshbasic_fragn },n lambert: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {n emissive: {n value: new Color(0x000000)n }n }]),n vertexShader: ShaderChunk.meshlambert_vert,n fragmentShader: ShaderChunk.meshlambert_fragn },n phong: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {n emissive: {n value: new Color(0x000000)n },n specular: {n value: new Color(0x111111)n },n shininess: {n value: 30n }n }]),n vertexShader: ShaderChunk.meshphong_vert,n fragmentShader: ShaderChunk.meshphong_fragn },n standard: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {n emissive: {n value: new Color(0x000000)n },n roughness: {n value: 0.5n },n metalness: {n value: 0.5n },n envMapIntensity: {n value: 1 // temporarynn }n }]),n vertexShader: ShaderChunk.meshphysical_vert,n fragmentShader: ShaderChunk.meshphysical_fragn },n matcap: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {n matcap: {n value: nulln }n }]),n vertexShader: ShaderChunk.meshmatcap_vert,n fragmentShader: ShaderChunk.meshmatcap_fragn },n points: {n uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),n vertexShader: ShaderChunk.points_vert,n fragmentShader: ShaderChunk.points_fragn },n dashed: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {n scale: {n value: 1n },n dashSize: {n value: 1n },n totalSize: {n value: 2n }n }]),n vertexShader: ShaderChunk.linedashed_vert,n fragmentShader: ShaderChunk.linedashed_fragn },n depth: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),n vertexShader: ShaderChunk.depth_vert,n fragmentShader: ShaderChunk.depth_fragn },n normal: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {n opacity: {n value: 1.0n }n }]),n vertexShader: ShaderChunk.normal_vert,n fragmentShader: ShaderChunk.normal_fragn },n sprite: {n uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),n vertexShader: ShaderChunk.sprite_vert,n fragmentShader: ShaderChunk.sprite_fragn },n background: {n uniforms: {n uvTransform: {n value: new Matrix3()n },n t2D: {n value: nulln }n },n vertexShader: ShaderChunk.background_vert,n fragmentShader: ShaderChunk.background_fragn },nn /* ————————————————————————-n //tCube map shadern ————————————————————————- */n cube: {n uniforms: {n tCube: {n value: nulln },n tFlip: {n value: -1n },n opacity: {n value: 1.0n }n },n vertexShader: ShaderChunk.cube_vert,n fragmentShader: ShaderChunk.cube_fragn },n equirect: {n uniforms: {n tEquirect: {n value: nulln }n },n vertexShader: ShaderChunk.equirect_vert,n fragmentShader: ShaderChunk.equirect_fragn },n distanceRGBA: {n uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {n referencePosition: {n value: new Vector3()n },n nearDistance: {n value: 1n },n farDistance: {n value: 1000n }n }]),n vertexShader: ShaderChunk.distanceRGBA_vert,n fragmentShader: ShaderChunk.distanceRGBA_fragn },n shadow: {n uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {n color: {n value: new Color(0x00000)n },n opacity: {n value: 1.0n }n }]),n vertexShader: ShaderChunk.shadow_vert,n fragmentShader: ShaderChunk.shadow_fragn }n};nShaderLib.physical = {n uniforms: mergeUniforms([ShaderLib.standard.uniforms, {n transparency: {n value: 0n },n clearcoat: {n value: 0n },n clearcoatRoughness: {n value: 0n },n sheen: {n value: new Color(0x000000)n },n clearcoatNormalScale: {n value: new Vector2(1, 1)n },n clearcoatNormalMap: {n value: nulln }n }]),n vertexShader: ShaderChunk.meshphysical_vert,n fragmentShader: ShaderChunk.meshphysical_fragn};n/**n * @author mrdoob / mrdoob.com/n */nnfunction WebGLAnimation() {n var context = null;n var isAnimating = false;n var animationLoop = null;nn function onAnimationFrame(time, frame) {n if (isAnimating === false) return;n animationLoop(time, frame);n context.requestAnimationFrame(onAnimationFrame);n }nn return {n start: function start() {n if (isAnimating === true) return;n if (animationLoop === null) return;n context.requestAnimationFrame(onAnimationFrame);n isAnimating = true;n },n stop: function stop() {n isAnimating = false;n },n setAnimationLoop: function setAnimationLoop(callback) {n animationLoop = callback;n },n setContext: function setContext(value) {n context = value;n }n };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLAttributes(gl) {n var buffers = new WeakMap();nn function createBuffer(attribute, bufferType) {n var array = attribute.array;n var usage = attribute.dynamic ? 35048 : 35044;n var buffer = gl.createBuffer();n gl.bindBuffer(bufferType, buffer);n gl.bufferData(bufferType, array, usage);n attribute.onUploadCallback();n var type = 5126;nn if (array instanceof Float32Array) {n type = 5126;n } else if (array instanceof Float64Array) {n console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');n } else if (array instanceof Uint16Array) {n type = 5123;n } else if (array instanceof Int16Array) {n type = 5122;n } else if (array instanceof Uint32Array) {n type = 5125;n } else if (array instanceof Int32Array) {n type = 5124;n } else if (array instanceof Int8Array) {n type = 5120;n } else if (array instanceof Uint8Array) {n type = 5121;n }nn return {n buffer: buffer,n type: type,n bytesPerElement: array.BYTES_PER_ELEMENT,n version: attribute.versionn };n }nn function updateBuffer(buffer, attribute, bufferType) {n var array = attribute.array;n var updateRange = attribute.updateRange;n gl.bindBuffer(bufferType, buffer);nn if (attribute.dynamic === false) {n gl.bufferData(bufferType, array, 35044);n } else if (updateRange.count === -1) {n // Not using update rangesn gl.bufferSubData(bufferType, 0, array);n } else if (updateRange.count === 0) {n console.error('THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.');n } else {n gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));n updateRange.count = -1; // reset rangen }n } //nnn function get(attribute) {n if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;n return buffers.get(attribute);n }nn function remove(attribute) {n if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;n var data = buffers.get(attribute);nn if (data) {n gl.deleteBuffer(data.buffer);n buffers(attribute);n }n }nn function update(attribute, bufferType) {n if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;n var data = buffers.get(attribute);nn if (data === undefined) {n buffers.set(attribute, createBuffer(attribute, bufferType));n } else if (data.version < attribute.version) {n updateBuffer(data.buffer, attribute, bufferType);n data.version = attribute.version;n }n }nn return {n get: get,n remove: remove,n update: updaten };n}n/**n * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n */n// PlaneGeometrynnnfunction PlaneGeometry(width, height, widthSegments, heightSegments) {n Geometry.call(this);n this.type = 'PlaneGeometry';n this.parameters = {n width: width,n height: height,n widthSegments: widthSegments,n heightSegments: heightSegmentsn };n this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));n this.mergeVertices();n}nnPlaneGeometry.prototype = Object.create(Geometry.prototype);nPlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometrynnfunction PlaneBufferGeometry(width, height, widthSegments, heightSegments) {n BufferGeometry.call(this);n this.type = 'PlaneBufferGeometry';n this.parameters = {n width: width,n height: height,n widthSegments: widthSegments,n heightSegments: heightSegmentsn };n width = width || 1;n height = height || 1;n var width_half = width / 2;n var height_half = height / 2;n var gridX = Math.floor(widthSegments) || 1;n var gridY = Math.floor(heightSegments) || 1;n var gridX1 = gridX + 1;n var gridY1 = gridY + 1;n var segment_width = width / gridX;n var segment_height = height / gridY;n var ix, iy; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // generate vertices, normals and uvsnn for (iy = 0; iy < gridY1; iy++) {n var y = iy * segment_height - height_half;nn for (ix = 0; ix < gridX1; ix++) {n var x = ix * segment_width - width_half;n vertices.push(x, -y, 0);n normals.push(0, 0, 1);n uvs.push(ix / gridX);n uvs.push(1 - iy / gridY);n }n } // indicesnnn for (iy = 0; iy < gridY; iy++) {n for (ix = 0; ix < gridX; ix++) {n var a = ix + gridX1 * iy;n var b = ix + gridX1 * (iy + 1);n var c = ix + 1 + gridX1 * (iy + 1);n var d = ix + 1 + gridX1 * iy; // facesnn indices.push(a, b, d);n indices.push(b, c, d);n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));n}nnPlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nPlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;n/**n * @author mrdoob / mrdoob.com/n */nnfunction WebGLBackground(renderer, state, objects, premultipliedAlpha) {n var clearColor = new Color(0x000000);n var clearAlpha = 0;n var planeMesh;n var boxMesh; // Store the current background texture and its `version`n // so we can recompile the material accordingly.nn var currentBackground = null;n var currentBackgroundVersion = 0;nn function render(renderList, scene, camera, forceClear) {n var background = scene.background; // Ignore background in ARn // TODO: Reconsider this.nn var vr = renderer.vr;n var session = vr.getSession && vr.getSession();nn if (session && session.environmentBlendMode === 'additive') {n background = null;n }nn if (background === null) {n setClear(clearColor, clearAlpha);n currentBackground = null;n currentBackgroundVersion = 0;n } else if (background && background.isColor) {n setClear(background, 1);n forceClear = true;n currentBackground = null;n currentBackgroundVersion = 0;n }nn if (renderer.autoClear || forceClear) {n renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);n }nn if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {n if (boxMesh === undefined) {n boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({n type: 'BackgroundCubeMaterial',n uniforms: cloneUniforms(ShaderLib.cube.uniforms),n vertexShader: ShaderLib.cube.vertexShader,n fragmentShader: ShaderLib.cube.fragmentShader,n side: BackSide,n depthTest: false,n depthWrite: false,n fog: falsen }));n boxMesh.geometry.removeAttribute('normal');n boxMesh.geometry.removeAttribute('uv');nn boxMesh.onBeforeRender = function (renderer, scene, camera) {n this.matrixWorld.copyPosition(camera.matrixWorld);n }; // enable code injection for non-built-in materialnnn Object.defineProperty(boxMesh.material, 'map', {n get: function get() {n return this.uniforms.tCube.value;n }n });n objects.update(boxMesh);n }nn var texture = background.isWebGLRenderTargetCube ? background.texture : background;n boxMesh.material.uniforms.tCube.value = texture;n boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;nn if (currentBackground !== background || currentBackgroundVersion !== texture.version) {n boxMesh.material.needsUpdate = true;n currentBackground = background;n currentBackgroundVersion = texture.version;n } // push to the pre-sorted opaque render listnnn renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);n } else if (background && background.isTexture) {n if (planeMesh === undefined) {n planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({n type: 'BackgroundMaterial',n uniforms: cloneUniforms(ShaderLib.background.uniforms),n vertexShader: ShaderLib.background.vertexShader,n fragmentShader: ShaderLib.background.fragmentShader,n side: FrontSide,n depthTest: false,n depthWrite: false,n fog: falsen }));n planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in materialnn Object.defineProperty(planeMesh.material, 'map', {n get: function get() {n return this.uniforms.t2D.value;n }n });n objects.update(planeMesh);n }nn planeMesh.material.uniforms.t2D.value = background;nn if (background.matrixAutoUpdate === true) {n background.updateMatrix();n }nn planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);nn if (currentBackground !== background || currentBackgroundVersion !== background.version) {n planeMesh.material.needsUpdate = true;n currentBackground = background;n currentBackgroundVersion = background.version;n } // push to the pre-sorted opaque render listnnn renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);n }n }nn function setClear(color, alpha) {n state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);n }nn return {n getClearColor: function getClearColor() {n return clearColor;n },n setClearColor: function setClearColor(color, alpha) {n clearColor.set(color);n clearAlpha = alpha !== undefined ? alpha : 1;n setClear(clearColor, clearAlpha);n },n getClearAlpha: function getClearAlpha() {n return clearAlpha;n },n setClearAlpha: function setClearAlpha(alpha) {n clearAlpha = alpha;n setClear(clearColor, clearAlpha);n },n render: rendern };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLBufferRenderer(gl, extensions, info, capabilities) {n var mode;nn function setMode(value) {n mode = value;n }nn function render(start, count) {n gl.drawArrays(mode, start, count);n info.update(count, mode);n }nn function renderInstances(geometry, start, count) {n var extension, methodName;nn if (capabilities.isWebGL2) {n extension = gl;n methodName = 'drawArraysInstanced';n } else {n extension = extensions.get('ANGLE_instanced_arrays');n methodName = 'drawArraysInstancedANGLE';nn if (extension === null) {n console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');n return;n }n }nn extension(mode, start, count, geometry.maxInstancedCount);n info.update(count, mode, geometry.maxInstancedCount);n } //nnn this.setMode = setMode;n this.render = render;n this.renderInstances = renderInstances;n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLCapabilities(gl, extensions, parameters) {n var maxAnisotropy;nn function getMaxAnisotropy() {n if (maxAnisotropy !== undefined) return maxAnisotropy;n var extension = extensions.get('EXT_texture_filter_anisotropic');nn if (extension !== null) {n maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);n } else {n maxAnisotropy = 0;n }nn return maxAnisotropy;n }nn function getMaxPrecision(precision) {n if (precision === 'highp') {n if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {n return 'highp';n }nn precision = 'mediump';n }nn if (precision === 'mediump') {n if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {n return 'mediump';n }n }nn return 'lowp';n }nn var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;n var precision = parameters.precision !== undefined ? parameters.precision : 'highp';n var maxPrecision = getMaxPrecision(precision);nn if (maxPrecision !== precision) {n console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');n precision = maxPrecision;n }nn var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;n var maxTextures = gl.getParameter(34930);n var maxVertexTextures = gl.getParameter(35660);n var maxTextureSize = gl.getParameter(3379);n var maxCubemapSize = gl.getParameter(34076);n var maxAttributes = gl.getParameter(34921);n var maxVertexUniforms = gl.getParameter(36347);n var maxVaryings = gl.getParameter(36348);n var maxFragmentUniforms = gl.getParameter(36349);n var vertexTextures = maxVertexTextures > 0;n var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');n var floatVertexTextures = vertexTextures && floatFragmentTextures;n var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;n return {n isWebGL2: isWebGL2,n getMaxAnisotropy: getMaxAnisotropy,n getMaxPrecision: getMaxPrecision,n precision: precision,n logarithmicDepthBuffer: logarithmicDepthBuffer,n maxTextures: maxTextures,n maxVertexTextures: maxVertexTextures,n maxTextureSize: maxTextureSize,n maxCubemapSize: maxCubemapSize,n maxAttributes: maxAttributes,n maxVertexUniforms: maxVertexUniforms,n maxVaryings: maxVaryings,n maxFragmentUniforms: maxFragmentUniforms,n vertexTextures: vertexTextures,n floatFragmentTextures: floatFragmentTextures,n floatVertexTextures: floatVertexTextures,n maxSamples: maxSamplesn };n}n/**n * @author tschwn */nnnfunction WebGLClipping() {n var scope = this,n globalState = null,n numGlobalPlanes = 0,n localClippingEnabled = false,n renderingShadows = false,n plane = new Plane(),n viewNormalMatrix = new Matrix3(),n uniform = {n value: null,n needsUpdate: falsen };n this.uniform = uniform;n this.numPlanes = 0;n this.numIntersection = 0;nn this.init = function (planes, enableLocalClipping, camera) {n var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has ton // run another frame in order to reset the state:n numGlobalPlanes !== 0 || localClippingEnabled;n localClippingEnabled = enableLocalClipping;n globalState = projectPlanes(planes, camera, 0);n numGlobalPlanes = planes.length;n return enabled;n };nn this.beginShadows = function () {n renderingShadows = true;n projectPlanes(null);n };nn this.endShadows = function () {n renderingShadows = false;n resetGlobalState();n };nn this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {n if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {n // there's no local clippingn if (renderingShadows) {n // there's no global clippingn projectPlanes(null);n } else {n resetGlobalState();n }n } else {n var nGlobal = renderingShadows ? 0 : numGlobalPlanes,n lGlobal = nGlobal * 4,n dstArray = cache.clippingState || null;n uniform.value = dstArray; // ensure unique statenn dstArray = projectPlanes(planes, camera, lGlobal, fromCache);nn for (var i = 0; i !== lGlobal; ++i) {n dstArray = globalState;n }nn cache.clippingState = dstArray;n this.numIntersection = clipIntersection ? this.numPlanes : 0;n this.numPlanes += nGlobal;n }n };nn function resetGlobalState() {n if (uniform.value !== globalState) {n uniform.value = globalState;n uniform.needsUpdate = numGlobalPlanes > 0;n }nn scope.numPlanes = numGlobalPlanes;n scope.numIntersection = 0;n }nn function projectPlanes(planes, camera, dstOffset, skipTransform) {n var nPlanes = planes !== null ? planes.length : 0,n dstArray = null;nn if (nPlanes !== 0) {n dstArray = uniform.value;nn if (skipTransform !== true || dstArray === null) {n var flatSize = dstOffset + nPlanes * 4,n viewMatrix = camera.matrixWorldInverse;n viewNormalMatrix.getNormalMatrix(viewMatrix);nn if (dstArray === null || dstArray.length < flatSize) {n dstArray = new Float32Array(flatSize);n }nn for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {n plane.copy(planes).applyMatrix4(viewMatrix, viewNormalMatrix);n plane.normal.toArray(dstArray, i4);n dstArray[i4 + 3] = plane.constant;n }n }nn uniform.value = dstArray;n uniform.needsUpdate = true;n }nn scope.numPlanes = nPlanes;n return dstArray;n }n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLExtensions(gl) {n var extensions = {};n return {n get: function get(name) {n if (extensions !== undefined) {n return extensions;n }nn var extension;nn switch (name) {n case 'WEBGL_depth_texture':n extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');n break;nn case 'EXT_texture_filter_anisotropic':n extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');n break;nn case 'WEBGL_compressed_texture_s3tc':n extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');n break;nn case 'WEBGL_compressed_texture_pvrtc':n extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');n break;nn default:n extension = gl.getExtension(name);n }nn if (extension === null) {n console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');n }nn extensions = extension;n return extension;n }n };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLGeometries(gl, attributes, info) {n var geometries = new WeakMap();n var wireframeAttributes = new WeakMap();nn function onGeometryDispose(event) {n var geometry = event.target;n var buffergeometry = geometries.get(geometry);nn if (buffergeometry.index !== null) {n attributes.remove(buffergeometry.index);n }nn for (var name in buffergeometry.attributes) {n attributes.remove(buffergeometry.attributes);n }nn geometry.removeEventListener('dispose', onGeometryDispose);n geometries(geometry);n var attribute = wireframeAttributes.get(buffergeometry);nn if (attribute) {n attributes.remove(attribute);n wireframeAttributes(buffergeometry);n } //nnn info.memory.geometries–;n }nn function get(object, geometry) {n var buffergeometry = geometries.get(geometry);n if (buffergeometry) return buffergeometry;n geometry.addEventListener('dispose', onGeometryDispose);nn if (geometry.isBufferGeometry) {n buffergeometry = geometry;n } else if (geometry.isGeometry) {n if (geometry._bufferGeometry === undefined) {n geometry._bufferGeometry = new BufferGeometry().setFromObject(object);n }nn buffergeometry = geometry._bufferGeometry;n }nn geometries.set(geometry, buffergeometry);n info.memory.geometries++;n return buffergeometry;n }nn function update(geometry) {n var index = geometry.index;n var geometryAttributes = geometry.attributes;nn if (index !== null) {n attributes.update(index, 34963);n }nn for (var name in geometryAttributes) {n attributes.update(geometryAttributes, 34962);n } // morph targetsnnn var morphAttributes = geometry.morphAttributes;nn for (var name in morphAttributes) {n var array = morphAttributes;nn for (var i = 0, l = array.length; i < l; i++) {n attributes.update(array, 34962);n }n }n }nn function updateWireframeAttribute(geometry) {n var indices = [];n var geometryIndex = geometry.index;n var geometryPosition = geometry.attributes.position;n var version = 0;nn if (geometryIndex !== null) {n var array = geometryIndex.array;n version = geometryIndex.version;nn for (var i = 0, l = array.length; i < l; i += 3) {n var a = array[i + 0];n var b = array[i + 1];n var c = array[i + 2];n indices.push(a, b, b, c, c, a);n }n } else {n var array = geometryPosition.array;n version = geometryPosition.version;nn for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {n var a = i + 0;n var b = i + 1;n var c = i + 2;n indices.push(a, b, b, c, c, a);n }n }nn var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);n attribute.version = version;n attributes.update(attribute, 34963); //nn var previousAttribute = wireframeAttributes.get(geometry);n if (previousAttribute) attributes.remove(previousAttribute); //nn wireframeAttributes.set(geometry, attribute);n }nn function getWireframeAttribute(geometry) {n var currentAttribute = wireframeAttributes.get(geometry);nn if (currentAttribute) {n var geometryIndex = geometry.index;nn if (geometryIndex !== null) {n // if the attribute is obsolete, create a new onen if (currentAttribute.version < geometryIndex.version) {n updateWireframeAttribute(geometry);n }n }n } else {n updateWireframeAttribute(geometry);n }nn return wireframeAttributes.get(geometry);n }nn return {n get: get,n update: update,n getWireframeAttribute: getWireframeAttributen };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {n var mode;nn function setMode(value) {n mode = value;n }nn var type, bytesPerElement;nn function setIndex(value) {n type = value.type;n bytesPerElement = value.bytesPerElement;n }nn function render(start, count) {n gl.drawElements(mode, count, type, start * bytesPerElement);n info.update(count, mode);n }nn function renderInstances(geometry, start, count) {n var extension, methodName;nn if (capabilities.isWebGL2) {n extension = gl;n methodName = 'drawElementsInstanced';n } else {n extension = extensions.get('ANGLE_instanced_arrays');n methodName = 'drawElementsInstancedANGLE';nn if (extension === null) {n console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');n return;n }n }nn extension(mode, count, type, start * bytesPerElement, geometry.maxInstancedCount);n info.update(count, mode, geometry.maxInstancedCount);n } //nnn this.setMode = setMode;n this.setIndex = setIndex;n this.render = render;n this.renderInstances = renderInstances;n}n/**n * @author Mugen87 / github.com/Mugen87n */nnnfunction WebGLInfo(gl) {n var memory = {n geometries: 0,n textures: 0n };n var render = {n frame: 0,n calls: 0,n triangles: 0,n points: 0,n lines: 0n };nn function update(count, mode, instanceCount) {n instanceCount = instanceCount || 1;n render.calls++;nn switch (mode) {n case 4:n render.triangles += instanceCount * (count / 3);n break;nn case 5:n case 6:n render.triangles += instanceCount * (count - 2);n break;nn case 1:n render.lines += instanceCount * (count / 2);n break;nn case 3:n render.lines += instanceCount * (count - 1);n break;nn case 2:n render.lines += instanceCount * count;n break;nn case 0:n render.points += instanceCount * count;n break;nn default:n console.error('THREE.WebGLInfo: Unknown draw mode:', mode);n break;n }n }nn function reset() {n render.frame++;n render.calls = 0;n render.triangles = 0;n render.points = 0;n render.lines = 0;n }nn return {n memory: memory,n render: render,n programs: null,n autoReset: true,n reset: reset,n update: updaten };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction absNumericalSort(a, b) {n return Math.abs(b) - Math.abs(a);n}nnfunction WebGLMorphtargets(gl) {n var influencesList = {};n var morphInfluences = new Float32Array(8);nn function update(object, geometry, material, program) {n var objectInfluences = object.morphTargetInfluences;n var length = objectInfluences.length;n var influences = influencesList;nn if (influences === undefined) {n // initialise listn influences = [];nn for (var i = 0; i < length; i++) {n influences = [i, 0];n }nn influencesList = influences;n }nn var morphTargets = material.morphTargets && geometry.morphAttributes.position;n var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributesnn for (var i = 0; i < length; i++) {n var influence = influences;nn if (influence !== 0) {n if (morphTargets) geometry.removeAttribute('morphTarget' + i);n if (morphNormals) geometry.removeAttribute('morphNormal' + i);n }n } // Collect influencesnnn for (var i = 0; i < length; i++) {n var influence = influences;n influence = i;n influence = objectInfluences;n }nn influences.sort(absNumericalSort); // Add morphAttributesnn for (var i = 0; i < 8; i++) {n var influence = influences;nn if (influence) {n var index = influence;n var value = influence;nn if (value) {n if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets);n if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals);n morphInfluences = value;n continue;n }n }nn morphInfluences = 0;n }nn program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);n }nn return {n update: updaten };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLObjects(geometries, info) {n var updateList = {};nn function update(object) {n var frame = info.render.frame;n var geometry = object.geometry;n var buffergeometry = geometries.get(object, geometry); // Update once per framenn if (updateList !== frame) {n if (geometry.isGeometry) {n buffergeometry.updateFromObject(object);n }nn geometries.update(buffergeometry);n updateList = frame;n }nn return buffergeometry;n }nn function dispose() {n updateList = {};n }nn return {n update: update,n dispose: disposen };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {n images = images !== undefined ? images : [];n mapping = mapping !== undefined ? mapping : CubeReflectionMapping;n format = format !== undefined ? format : RGBFormat;n Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);n this.flipY = false;n}nnCubeTexture.prototype = Object.create(Texture.prototype);nCubeTexture.prototype.constructor = CubeTexture;nCubeTexture.prototype.isCubeTexture = true;nObject.defineProperty(CubeTexture.prototype, 'images', {n get: function get() {n return this.image;n },n set: function set(value) {n this.image = value;n }n});n/**n * @author Takahiro github.com/takahiroxn */nnfunction DataTexture2DArray(data, width, height, depth) {n Texture.call(this, null);n this.image = {n data: data,n width: width,n height: height,n depth: depthn };n this.magFilter = NearestFilter;n this.minFilter = NearestFilter;n this.wrapR = ClampToEdgeWrapping;n this.generateMipmaps = false;n this.flipY = false;n}nnDataTexture2DArray.prototype = Object.create(Texture.prototype);nDataTexture2DArray.prototype.constructor = DataTexture2DArray;nDataTexture2DArray.prototype.isDataTexture2DArray = true;n/**n * @author Artur Trzesiokn */nnfunction DataTexture3D(data, width, height, depth) {n // We're going to add .setXXX() methods for setting properties later.n // Users can still set in DataTexture3D directly.n //n //tvar texture = new THREE.DataTexture3D( data, width, height, depth );n // ttexture.anisotropy = 16;n //n // See #14839n Texture.call(this, null);n this.image = {n data: data,n width: width,n height: height,n depth: depthn };n this.magFilter = NearestFilter;n this.minFilter = NearestFilter;n this.wrapR = ClampToEdgeWrapping;n this.generateMipmaps = false;n this.flipY = false;n}nnDataTexture3D.prototype = Object.create(Texture.prototype);nDataTexture3D.prototype.constructor = DataTexture3D;nDataTexture3D.prototype.isDataTexture3D = true;n/**n * @author tschwn * @author Mugen87 / github.com/Mugen87n * @author mrdoob / mrdoob.com/n *n * Uniforms of a program.n * Those form a tree structure with a special top-level container for the root,n * which you get by calling 'new WebGLUniforms( gl, program )'.n *n *n * Properties of inner nodes including the top-level container:n *n * .seq - array of nested uniformsn * .map - nested uniforms by namen *n *n * Methods of all nodes except the top-level container:n *n * .setValue( gl, value, [textures] )n *n * ttuploads a uniform value(s)n * tthe 'textures' parameter is needed for sampler uniformsn *n *n * Static methods of the top-level container (textures factorizations):n *n * .upload( gl, seq, values, textures )n *n * ttsets uniforms in 'seq' to 'values.value'n *n * .seqWithValue( seq, values ) : filteredSeqn *n * ttfilters 'seq' entries with corresponding entry in valuesn *n *n * Methods of the top-level container (textures factorizations):n *n * .setValue( gl, name, value, textures )n *n * ttsets uniform with name 'name' to 'value'n *n * .setOptional( gl, obj, prop )n *n * ttlike .set for an optional property of the objectn *n */nnvar emptyTexture = new Texture();nvar emptyTexture2dArray = new DataTexture2DArray();nvar emptyTexture3d = new DataTexture3D();nvar emptyCubeTexture = new CubeTexture(); // — Utilities —n// Array Caches (provide typed arrays for temporary by size)nnvar arrayCacheF32 = [];nvar arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniformsnnvar mat4array = new Float32Array(16);nvar mat3array = new Float32Array(9);nvar mat2array = new Float32Array(4); // Flattening for arrays of vectors and matricesnnfunction flatten(array, nBlocks, blockSize) {n var firstElem = array;n if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )n // see jacksondunstan.com/articles/983nn var n = nBlocks * blockSize,n r = arrayCacheF32;nn if (r === undefined) {n r = new Float32Array(n);n arrayCacheF32 = r;n }nn if (nBlocks !== 0) {n firstElem.toArray(r, 0);nn for (var i = 1, offset = 0; i !== nBlocks; ++i) {n offset += blockSize;n array.toArray(r, offset);n }n }nn return r;n}nnfunction arraysEqual(a, b) {n if (a.length !== b.length) return false;nn for (var i = 0, l = a.length; i < l; i++) {n if (a !== b) return false;n }nn return true;n}nnfunction copyArray(a, b) {n for (var i = 0, l = b.length; i < l; i++) {n a = b;n }n} // Texture unit allocationnnnfunction allocTexUnits(textures, n) {n var r = arrayCacheI32;nn if (r === undefined) {n r = new Int32Array(n);n arrayCacheI32 = r;n }nn for (var i = 0; i !== n; ++i) {n r = textures.allocateTextureUnit();n }nn return r;n} // — Setters —n// Note: Defining these methods externally, because they come in a bunchn// and this way their names minify.n// Single scalarnnnfunction setValueV1f(gl, v) {n var cache = this.cache;n if (cache === v) return;n gl.uniform1f(this.addr, v);n cache = v;n} // Single float vector (from flat array or THREE.VectorN)nnnfunction setValueV2f(gl, v) {n var cache = this.cache;nn if (v.x !== undefined) {n if (cache !== v.x || cache !== v.y) {n gl.uniform2f(this.addr, v.x, v.y);n cache = v.x;n cache = v.y;n }n } else {n if (arraysEqual(cache, v)) return;n gl.uniform2fv(this.addr, v);n copyArray(cache, v);n }n}nnfunction setValueV3f(gl, v) {n var cache = this.cache;nn if (v.x !== undefined) {n if (cache !== v.x || cache !== v.y || cache !== v.z) {n gl.uniform3f(this.addr, v.x, v.y, v.z);n cache = v.x;n cache = v.y;n cache = v.z;n }n } else if (v.r !== undefined) {n if (cache !== v.r || cache !== v.g || cache !== v.b) {n gl.uniform3f(this.addr, v.r, v.g, v.b);n cache = v.r;n cache = v.g;n cache = v.b;n }n } else {n if (arraysEqual(cache, v)) return;n gl.uniform3fv(this.addr, v);n copyArray(cache, v);n }n}nnfunction setValueV4f(gl, v) {n var cache = this.cache;nn if (v.x !== undefined) {n if (cache !== v.x || cache !== v.y || cache !== v.z || cache !== v.w) {n gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);n cache = v.x;n cache = v.y;n cache = v.z;n cache = v.w;n }n } else {n if (arraysEqual(cache, v)) return;n gl.uniform4fv(this.addr, v);n copyArray(cache, v);n }n} // Single matrix (from flat array or MatrixN)nnnfunction setValueM2(gl, v) {n var cache = this.cache;n var elements = v.elements;nn if (elements === undefined) {n if (arraysEqual(cache, v)) return;n gl.uniformMatrix2fv(this.addr, false, v);n copyArray(cache, v);n } else {n if (arraysEqual(cache, elements)) return;n mat2array.set(elements);n gl.uniformMatrix2fv(this.addr, false, mat2array);n copyArray(cache, elements);n }n}nnfunction setValueM3(gl, v) {n var cache = this.cache;n var elements = v.elements;nn if (elements === undefined) {n if (arraysEqual(cache, v)) return;n gl.uniformMatrix3fv(this.addr, false, v);n copyArray(cache, v);n } else {n if (arraysEqual(cache, elements)) return;n mat3array.set(elements);n gl.uniformMatrix3fv(this.addr, false, mat3array);n copyArray(cache, elements);n }n}nnfunction setValueM4(gl, v) {n var cache = this.cache;n var elements = v.elements;nn if (elements === undefined) {n if (arraysEqual(cache, v)) return;n gl.uniformMatrix4fv(this.addr, false, v);n copyArray(cache, v);n } else {n if (arraysEqual(cache, elements)) return;n mat4array.set(elements);n gl.uniformMatrix4fv(this.addr, false, mat4array);n copyArray(cache, elements);n }n} // Single texture (2D / Cube
)nnnfunction setValueT1(gl, v, textures) {n var cache = this.cache;n var unit = textures.allocateTextureUnit();nn if (cache !== unit) {n gl.uniform1i(this.addr, unit);n cache = unit;n }nn textures.safeSetTexture2D(v || emptyTexture, unit);n}nnfunction setValueT2DArray1(gl, v, textures) {n var cache = this.cache;n var unit = textures.allocateTextureUnit();nn if (cache !== unit) {n gl.uniform1i(this.addr, unit);n cache = unit;n }nn textures.setTexture2DArray(v || emptyTexture2dArray, unit);n}nnfunction setValueT3D1(gl, v, textures) {n var cache = this.cache;n var unit = textures.allocateTextureUnit();nn if (cache !== unit) {n gl.uniform1i(this.addr, unit);n cache = unit;n }nn textures.setTexture3D(v || emptyTexture3d, unit);n}nnfunction setValueT6(gl, v, textures) {n var cache = this.cache;n var unit = textures.allocateTextureUnit();nn if (cache !== unit) {n gl.uniform1i(this.addr, unit);n cache = unit;n }nn textures.safeSetTextureCube(v || emptyCubeTexture, unit);n} // Integer
/ Boolean vectors or arrays thereof (always flat arrays)nnnfunction setValueV1i(gl, v) {n var cache = this.cache;n if (cache === v) return;n gl.uniform1i(this.addr, v);n cache = v;n}nnfunction setValueV2i(gl, v) {n var cache = this.cache;n if (arraysEqual(cache, v)) return;n gl.uniform2iv(this.addr, v);n copyArray(cache, v);n}nnfunction setValueV3i(gl, v) {n var cache = this.cache;n if (arraysEqual(cache, v)) return;n gl.uniform3iv(this.addr, v);n copyArray(cache, v);n}nnfunction setValueV4i(gl, v) {n var cache = this.cache;n if (arraysEqual(cache, v)) return;n gl.uniform4iv(this.addr, v);n copyArray(cache, v);n} // Helper to pick the right setter for the singular casennnfunction getSingularSetter(type) {n switch (type) {n case 0x1406:n return setValueV1f;n // FLOATnn case 0x8b50:n return setValueV2f;n // _VEC2nn case 0x8b51:n return setValueV3f;n // _VEC3nn case 0x8b52:n return setValueV4f;n // _VEC4nn case 0x8b5a:n return setValueM2;n // _MAT2nn case 0x8b5b:n return setValueM3;n // _MAT3nn case 0x8b5c:n return setValueM4;n // _MAT4nn case 0x8b5e:n case 0x8d66:n return setValueT1;n // SAMPLER_2D, SAMPLER_EXTERNAL_OESnn case 0x8b5f:n return setValueT3D1;n // SAMPLER_3Dnn case 0x8b60:n return setValueT6;n // SAMPLER_CUBEnn case 0x8DC1:n return setValueT2DArray1;n // SAMPLER_2D_ARRAYnn case 0x1404:n case 0x8b56:n return setValueV1i;n // INT, BOOLnn case 0x8b53:n case 0x8b57:n return setValueV2i;n // _VEC2nn case 0x8b54:n case 0x8b58:n return setValueV3i;n // _VEC3nn case 0x8b55:n case 0x8b59:n return setValueV4i;n // _VEC4n }n} // Array of scalarsnnnfunction setValueV1fArray(gl, v) {n gl.uniform1fv(this.addr, v);n} // Integer
/ Boolean vectors or arrays thereof (always flat arrays)nnnfunction setValueV1iArray(gl, v) {n gl.uniform1iv(this.addr, v);n}nnfunction setValueV2iArray(gl, v) {n gl.uniform2iv(this.addr, v);n}nnfunction setValueV3iArray(gl, v) {n gl.uniform3iv(this.addr, v);n}nnfunction setValueV4iArray(gl, v) {n gl.uniform4iv(this.addr, v);n} // Array of vectors (flat or from THREE classes)nnnfunction setValueV2fArray(gl, v) {n var data = flatten(v, this.size, 2);n gl.uniform2fv(this.addr, data);n}nnfunction setValueV3fArray(gl, v) {n var data = flatten(v, this.size, 3);n gl.uniform3fv(this.addr, data);n}nnfunction setValueV4fArray(gl, v) {n var data = flatten(v, this.size, 4);n gl.uniform4fv(this.addr, data);n} // Array of matrices (flat or from THREE clases)nnnfunction setValueM2Array(gl, v) {n var data = flatten(v, this.size, 4);n gl.uniformMatrix2fv(this.addr, false, data);n}nnfunction setValueM3Array(gl, v) {n var data = flatten(v, this.size, 9);n gl.uniformMatrix3fv(this.addr, false, data);n}nnfunction setValueM4Array(gl, v) {n var data = flatten(v, this.size, 16);n gl.uniformMatrix4fv(this.addr, false, data);n} // Array of textures (2D / Cube
)nnnfunction setValueT1Array(gl, v, textures) {n var n = v.length;n var units = allocTexUnits(textures, n);n gl.uniform1iv(this.addr, units);nn for (var i = 0; i !== n; ++i) {n textures.safeSetTexture2D(v || emptyTexture, units);n }n}nnfunction setValueT6Array(gl, v, textures) {n var n = v.length;n var units = allocTexUnits(textures, n);n gl.uniform1iv(this.addr, units);nn for (var i = 0; i !== n; ++i) {n textures.safeSetTextureCube(v || emptyCubeTexture, units);n }n} // Helper to pick the right setter for a pure (bottom-level) arraynnnfunction getPureArraySetter(type) {n switch (type) {n case 0x1406:n return setValueV1fArray;n // FLOATnn case 0x8b50:n return setValueV2fArray;n // _VEC2nn case 0x8b51:n return setValueV3fArray;n // _VEC3nn case 0x8b52:n return setValueV4fArray;n // _VEC4nn case 0x8b5a:n return setValueM2Array;n // _MAT2nn case 0x8b5b:n return setValueM3Array;n // _MAT3nn case 0x8b5c:n return setValueM4Array;n // _MAT4nn case 0x8b5e:n return setValueT1Array;n // SAMPLER_2Dnn case 0x8b60:n return setValueT6Array;n // SAMPLER_CUBEnn case 0x1404:n case 0x8b56:n return setValueV1iArray;n // INT, BOOLnn case 0x8b53:n case 0x8b57:n return setValueV2iArray;n // _VEC2nn case 0x8b54:n case 0x8b58:n return setValueV3iArray;n // _VEC3nn case 0x8b55:n case 0x8b59:n return setValueV4iArray;n // _VEC4n }n} // — Uniform Classes —nnnfunction SingleUniform(id, activeInfo, addr) {n this.id = id;n this.addr = addr;n this.cache = [];n this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUGn}nnfunction PureArrayUniform(id, activeInfo, addr) {n this.id = id;n this.addr = addr;n this.cache = [];n this.size = activeInfo.size;n this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUGn}nnPureArrayUniform.prototype.updateCache = function (data) {n var cache = this.cache;nn if (data instanceof Float32Array && cache.length !== data.length) {n this.cache = new Float32Array(data.length);n }nn copyArray(cache, data);n};nnfunction StructuredUniform(id) {n this.id = id;n this.seq = [];n this.map = {};n}nnStructuredUniform.prototype.setValue = function (gl, value, textures) {n var seq = this.seq;nn for (var i = 0, n = seq.length; i !== n; ++i) {n var u = seq;n u.setValue(gl, value, textures);n }n}; // — Top-level —n// Parser - builds up the property tree from the path stringsnnnvar RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extractsn// t- the identifier (member name or array index)n// - followed by an optional right bracket (found when array index)n// - followed by an optional left bracket or dot (type of subscript)n//n// Note: These portions can be read in a non-overlapping fashion andn// allow straightforward parsing of the hierarchy that WebGL encodesn// in the uniform names.nnfunction addUniform(container, uniformObject) {n container.seq.push(uniformObject);n container.map = uniformObject;n}nnfunction parseUniform(activeInfo, addr, container) {n var path = activeInfo.name,n pathLength = path.length; // reset RegExp object, because of the early exit of a previous runnn RePathPart.lastIndex = 0;nn while (true) {n var match = RePathPart.exec(path),n matchEnd = RePathPart.lastIndex,n id = match,n idIsIndex = match === ']',n subscript = match;n if (idIsIndex) id = id | 0; // convert to integernn if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {n // bare name or "pure" bottom-level array "[0]" suffixn addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));n break;n } else {n // step into inner node / create it in case it doesn't existn var map = container.map,n next = map;nn if (next === undefined) {n next = new StructuredUniform(id);n addUniform(container, next);n }nn container = next;n }n }n} // Root Containernnnfunction WebGLUniforms(gl, program) {n this.seq = [];n this.map = {};n var n = gl.getProgramParameter(program, 35718);nn for (var i = 0; i < n; ++i) {n var info = gl.getActiveUniform(program, i),n addr = gl.getUniformLocation(program, info.name);n parseUniform(info, addr, this);n }n}nnWebGLUniforms.prototype.setValue = function (gl, name, value, textures) {n var u = this.map;n if (u !== undefined) u.setValue(gl, value, textures);n};nnWebGLUniforms.prototype.setOptional = function (gl, object, name) {n var v = object;n if (v !== undefined) this.setValue(gl, name, v);n}; // Static interfacennnWebGLUniforms.upload = function (gl, seq, values, textures) {n for (var i = 0, n = seq.length; i !== n; ++i) {n var u = seq,n v = values;nn if (v.needsUpdate !== false) {n // note: always updating when .needsUpdate is undefinedn u.setValue(gl, v.value, textures);n }n }n};nnWebGLUniforms.seqWithValue = function (seq, values) {n var r = [];nn for (var i = 0, n = seq.length; i !== n; ++i) {n var u = seq;n if (u.id in values) r.push(u);n }nn return r;n};n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLShader(gl, type, string) {n var shader = gl.createShader(type);n gl.shaderSource(shader, string);n gl.compileShader(shader);n return shader;n}n/**n * @author mrdoob / mrdoob.com/n */nnnvar programIdCount = 0;nnfunction addLineNumbers(string) {n var lines = string.split('\n');nn for (var i = 0; i < lines.length; i++) {n lines = i + 1 + ': ' + lines;n }nn return lines.join('\n');n}nnfunction getEncodingComponents(encoding) {n switch (encoding) {n case LinearEncoding:n return ['Linear', '( value )'];nn case sRGBEncoding:n return ['sRGB', '( value )'];nn case RGBEEncoding:n return ['RGBE', '( value )'];nn case RGBM7Encoding:n return ['RGBM', '( value, 7.0 )'];nn case RGBM16Encoding:n return ['RGBM', '( value, 16.0 )'];nn case RGBDEncoding:n return ['RGBD', '( value, 256.0 )'];nn case GammaEncoding:n return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];nn case LogLuvEncoding:n return ['LogLuv', '( value )'];nn default:n throw new Error('unsupported encoding: ' + encoding);n }n}nnfunction getShaderErrors(gl, shader, type) {n var status = gl.getShaderParameter(shader, 35713);n var log = gl.getShaderInfoLog(shader).trim();n if (status && log === '') return ''; // –enable-privileged-webgl-extensionn // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );nn var source = gl.getShaderSource(shader);n return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);n}nnfunction getTexelDecodingFunction(functionName, encoding) {n var components = getEncodingComponents(encoding);n return 'vec4 ' + functionName + '( vec4 value ) { return ' + components + 'ToLinear' + components + '; }';n}nnfunction getTexelEncodingFunction(functionName, encoding) {n var components = getEncodingComponents(encoding);n return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components + components + '; }';n}nnfunction getToneMappingFunction(functionName, toneMapping) {n var toneMappingName;nn switch (toneMapping) {n case LinearToneMapping:n toneMappingName = 'Linear';n break;nn case ReinhardToneMapping:n toneMappingName = 'Reinhard';n break;nn case Uncharted2ToneMapping:n toneMappingName = 'Uncharted2';n break;nn case CineonToneMapping:n toneMappingName = 'OptimizedCineon';n break;nn case ACESFilmicToneMapping:n toneMappingName = 'ACESFilmic';n break;nn default:n throw new Error('unsupported toneMapping: ' + toneMapping);n }nn return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';n}nnfunction generateExtensions(extensions, parameters, rendererExtensions) {n extensions = extensions || {};n var chunks = [extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading ? '#extension GL_OES_standard_derivatives : enable' : '', (extensions.fragDepth || parameters.logarithmicDepthBuffer) && rendererExtensions.get('EXT_frag_depth') ? '#extension GL_EXT_frag_depth : enable' : '', extensions.drawBuffers && rendererExtensions.get('WEBGL_draw_buffers') ? '#extension GL_EXT_draw_buffers : require' : '', (extensions.shaderTextureLOD || parameters.envMap) && rendererExtensions.get('EXT_shader_texture_lod') ? '#extension GL_EXT_shader_texture_lod : enable' : ''];n return chunks.filter(filterEmptyLine).join('\n');n}nnfunction generateDefines(defines) {n var chunks = [];nn for (var name in defines) {n var value = defines;n if (value === false) continue;n chunks.push('#define ' + name + ' ' + value);n }nn return chunks.join('\n');n}nnfunction fetchAttributeLocations(gl, program) {n var attributes = {};n var n = gl.getProgramParameter(program, 35721);nn for (var i = 0; i < n; i++) {n var info = gl.getActiveAttrib(program, i);n var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );nn attributes = gl.getAttribLocation(program, name);n }nn return attributes;n}nnfunction filterEmptyLine(string) {n return string !== '';n}nnfunction replaceLightNums(string, parameters) {n 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);n}nnfunction replaceClippingPlaneNums(string, parameters) {n return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);n}nnfunction parseIncludes(string) {n var pattern = /^[ \t]*#include +<([\w\d./]+)>/gm;nn function replace(match, include) {n var replace = ShaderChunk;nn if (replace === undefined) {n throw new Error('Can not resolve include <' + include + '>');n }nn return parseIncludes(replace);n }nn return string.replace(pattern, replace);n}nnfunction unrollLoops(string) {n var pattern = /#pragma unroll_loop+?for \( int i \= (\d+)\; i < (\d+)\; i ++ \) \{([\s\S]+?)(?=\})\}/g;nn function replace(match, start, end, snippet) {n var unroll = '';nn for (var i = parseInt(start); i < parseInt(end); i++) {n unroll += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);n }nn return unroll;n }nn return string.replace(pattern, replace);n}nnfunction WebGLProgram(renderer, extensions, code, material, shader, parameters, capabilities) {n var gl = renderer.getContext();n var defines = material.defines;n var vertexShader = shader.vertexShader;n var fragmentShader = shader.fragmentShader;n var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';nn if (parameters.shadowMapType === PCFShadowMap) {n shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';n } else if (parameters.shadowMapType === PCFSoftShadowMap) {n shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';n } else if (parameters.shadowMapType === VSMShadowMap) {n shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';n }nn var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';n var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';n var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';nn if (parameters.envMap) {n switch (material.envMap.mapping) {n case CubeReflectionMapping:n case CubeRefractionMapping:n envMapTypeDefine = 'ENVMAP_TYPE_CUBE';n break;nn case CubeUVReflectionMapping:n case CubeUVRefractionMapping:n envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';n break;nn case EquirectangularReflectionMapping:n case EquirectangularRefractionMapping:n envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';n break;nn case SphericalReflectionMapping:n envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';n break;n }nn switch (material.envMap.mapping) {n case CubeRefractionMapping:n case EquirectangularRefractionMapping:n envMapModeDefine = 'ENVMAP_MODE_REFRACTION';n break;n }nn switch (material.combine) {n case MultiplyOperation:n envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';n break;nn case MixOperation:n envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';n break;nn case AddOperation:n envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';n break;n }n }nn var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0; // console.log( 'building new program ' );n //nn var customExtensions = capabilities.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);n var customDefines = generateDefines(defines); //nn var program = gl.createProgram();n var prefixVertex, prefixFragment;nn if (material.isRawShaderMaterial) {n prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');nn if (prefixVertex.length > 0) {n prefixVertex += '\n';n }nn prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');nn if (prefixFragment.length > 0) {n prefixFragment += '\n';n }n } else {n prefixVertex = ['precision ' + parameters.precision + ' float;', 'precision ' + parameters.precision + ' int;', parameters.precision === 'highp' ? '#define HIGH_PRECISION' : '', '#define SHADER_NAME ' + shader.name, customDefines, parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, 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.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.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && (capabilities.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_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', 'ttattribute vec3 morphNormal0;', 'ttattribute vec3 morphNormal1;', 'ttattribute vec3 morphNormal2;', 'ttattribute vec3 morphNormal3;', 't#else', 'ttattribute vec3 morphTarget4;', 'ttattribute vec3 morphTarget5;', 'ttattribute vec3 morphTarget6;', 'ttattribute vec3 morphTarget7;', 't#endif', '#endif', '#ifdef USE_SKINNING', 'tattribute vec4 skinIndex;', 'tattribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');n prefixFragment = [customExtensions, 'precision ' + parameters.precision + ' float;', 'precision ' + parameters.precision + ' int;', parameters.precision === 'highp' ? '#define HIGH_PRECISION' : '', '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integern '#define GAMMA_FACTOR ' + gammaFactorDefine, 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 : '', 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.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' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', 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 && (capabilities.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', ((material.extensions ? material.extensions.shaderTextureLOD : false) || parameters.envMap) && (capabilities.isWebGL2 || extensions.get('EXT_shader_texture_lod')) ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk : '', // this code is required here because it is used by the toneMapping() function defined belown parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ? ShaderChunk : '', // this code is required here because it is used by the various encoding/decoding function defined belown parameters.mapEncoding ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcapEncoding ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMapEncoding ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.outputEncoding ? getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');n }nn vertexShader = parseIncludes(vertexShader);n vertexShader = replaceLightNums(vertexShader, parameters);n vertexShader = replaceClippingPlaneNums(vertexShader, parameters);n fragmentShader = parseIncludes(fragmentShader);n fragmentShader = replaceLightNums(fragmentShader, parameters);n fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);n vertexShader = unrollLoops(vertexShader);n fragmentShader = unrollLoops(fragmentShader);nn if (capabilities.isWebGL2 && !material.isRawShaderMaterial) {n var isGLSL3ShaderMaterial = false;n var versionRegex = /^\s*#version\s+300\s+es\s*\n/;nn if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {n isGLSL3ShaderMaterial = true;n vertexShader = vertexShader.replace(versionRegex, '');n fragmentShader = fragmentShader.replace(versionRegex, '');n } // GLSL 3.0 conversionnnn prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;n prefixFragment = ['#version 300 es\n', '#define varying in', isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', isGLSL3ShaderMaterial ? '' : '#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;n }nn var vertexGlsl = prefixVertex + vertexShader;n var fragmentGlsl = prefixFragment + fragmentShader; // console.log( 'VERTEX', vertexGlsl );n // console.log( 'FRAGMENT', fragmentGlsl );nn var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);n var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);n gl.attachShader(program, glVertexShader);n gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.nn if (material.index0AttributeName !== undefined) {n gl.bindAttribLocation(program, 0, material.index0AttributeName);n } else if (parameters.morphTargets === true) {n // programs with morphTargets displace position out of attribute 0n gl.bindAttribLocation(program, 0, 'position');n }nn gl.linkProgram(program); // check for link errorsnn if (renderer.debug.checkShaderErrors) {n var programLog = gl.getProgramInfoLog(program).trim();n var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();n var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();n var runnable = true;n var haveDiagnostics = true;nn if (gl.getProgramParameter(program, 35714) === false) {n runnable = false;n var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');n var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');n console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);n } else if (programLog !== '') {n console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);n } else if (vertexLog === '' || fragmentLog === '') {n haveDiagnostics = false;n }nn if (haveDiagnostics) {n this.diagnostics = {n runnable: runnable,n material: material,n programLog: programLog,n vertexShader: {n log: vertexLog,n prefix: prefixVertexn },n fragmentShader: {n log: fragmentLog,n prefix: prefixFragmentn }n };n }n } // clean upnnn gl.deleteShader(glVertexShader);n gl.deleteShader(glFragmentShader); // set up caching for uniform locationsnn var cachedUniforms;nn this.getUniforms = function () {n if (cachedUniforms === undefined) {n cachedUniforms = new WebGLUniforms(gl, program);n }nn return cachedUniforms;n }; // set up caching for attribute locationsnnn var cachedAttributes;nn this.getAttributes = function () {n if (cachedAttributes === undefined) {n cachedAttributes = fetchAttributeLocations(gl, program);n }nn return cachedAttributes;n }; // free resourcennn this.destroy = function () {n gl.deleteProgram(program);n this.program = undefined;n }; //nnn this.name = shader.name;n this.id = programIdCount++;n this.code = code;n this.usedTimes = 1;n this.program = program;n this.vertexShader = glVertexShader;n this.fragmentShader = glFragmentShader;n return this;n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLPrograms(renderer, extensions, capabilities) {n var programs = [];n var shaderIDs = {n MeshDepthMaterial: 'depth',n MeshDistanceMaterial: 'distanceRGBA',n MeshNormalMaterial: 'normal',n MeshBasicMaterial: 'basic',n MeshLambertMaterial: 'lambert',n MeshPhongMaterial: 'phong',n MeshToonMaterial: 'phong',n MeshStandardMaterial: 'physical',n MeshPhysicalMaterial: 'physical',n MeshMatcapMaterial: 'matcap',n LineBasicMaterial: 'basic',n LineDashedMaterial: 'dashed',n PointsMaterial: 'points',n ShadowMaterial: 'shadow',n SpriteMaterial: 'sprite'n };n var parameterNames = ["precision", "supportsVertexTextures", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen"];nn function allocateBones(object) {n var skeleton = object.skeleton;n var bones = skeleton.bones;nn if (capabilities.floatVertexTextures) {n return 1024;n } else {n // default for when object is not specifiedn // ( for example when prebuilding shader to be used with multiple objects )n //n // - leave some extra space for other uniformsn // - limit here is ANGLE's 254 max uniform vectorsn // (up to 54 should be safe)n var nVertexUniforms = capabilities.maxVertexUniforms;n var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);n var maxBones = Math.min(nVertexMatrices, bones.length);nn if (maxBones < bones.length) {n console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');n return 0;n }nn return maxBones;n }n }nn function getTextureEncodingFromMap(map, gammaOverrideLinear) {n var encoding;nn if (!map) {n encoding = LinearEncoding;n } else if (map.isTexture) {n encoding = map.encoding;n } else if (map.isWebGLRenderTarget) {n console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");n encoding = map.texture.encoding;n } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.nnn if (encoding === LinearEncoding && gammaOverrideLinear) {n encoding = GammaEncoding;n }nn return encoding;n }nn this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {n var shaderID = shaderIDs; // heuristics to create shader parameters according to lights in the scenen // (not to blow over maxLights budget)nn var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;n var precision = capabilities.precision;nn if (material.precision !== null) {n precision = capabilities.getMaxPrecision(material.precision);nn if (precision !== material.precision) {n console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');n }n }nn var currentRenderTarget = renderer.getRenderTarget();n var parameters = {n shaderID: shaderID,n precision: precision,n supportsVertexTextures: capabilities.vertexTextures,n outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),n map: !!material.map,n mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),n matcap: !!material.matcap,n matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),n envMap: !!material.envMap,n envMapMode: material.envMap && material.envMap.mapping,n envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),n envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),n lightMap: !!material.lightMap,n aoMap: !!material.aoMap,n emissiveMap: !!material.emissiveMap,n emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),n bumpMap: !!material.bumpMap,n normalMap: !!material.normalMap,n objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,n tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,n clearcoatNormalMap: !!material.clearcoatNormalMap,n displacementMap: !!material.displacementMap,n roughnessMap: !!material.roughnessMap,n metalnessMap: !!material.metalnessMap,n specularMap: !!material.specularMap,n alphaMap: !!material.alphaMap,n gradientMap: !!material.gradientMap,n sheen: !!material.sheen,n combine: material.combine,n vertexTangents: material.normalMap && material.vertexTangents,n vertexColors: material.vertexColors,n vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,n fog: !!fog,n useFog: material.fog,n fogExp2: fog && fog.isFogExp2,n flatShading: material.flatShading,n sizeAttenuation: material.sizeAttenuation,n logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,n skinning: material.skinning && maxBones > 0,n maxBones: maxBones,n useVertexTexture: capabilities.floatVertexTextures,n morphTargets: material.morphTargets,n morphNormals: material.morphNormals,n maxMorphTargets: renderer.maxMorphTargets,n maxMorphNormals: renderer.maxMorphNormals,n numDirLights: lights.directional.length,n numPointLights: lights.point.length,n numSpotLights: lights.spot.length,n numRectAreaLights: lights.rectArea.length,n numHemiLights: lights.hemi.length,n numDirLightShadows: lights.directionalShadowMap.length,n numPointLightShadows: lights.pointShadowMap.length,n numSpotLightShadows: lights.spotShadowMap.length,n numClippingPlanes: nClipPlanes,n numClipIntersection: nClipIntersection,n dithering: material.dithering,n shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,n shadowMapType: renderer.shadowMap.type,n toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,n physicallyCorrectLights: renderer.physicallyCorrectLights,n premultipliedAlpha: material.premultipliedAlpha,n alphaTest: material.alphaTest,n doubleSided: material.side === DoubleSide,n flipSided: material.side === BackSide,n depthPacking: material.depthPacking !== undefined ? material.depthPacking : falsen };n return parameters;n };nn this.getProgramCode = function (material, parameters) {n var array = [];nn if (parameters.shaderID) {n array.push(parameters.shaderID);n } else {n array.push(material.fragmentShader);n array.push(material.vertexShader);n }nn if (material.defines !== undefined) {n for (var name in material.defines) {n array.push(name);n array.push(material.defines);n }n }nn for (var i = 0; i < parameterNames.length; i++) {n array.push(parameters[parameterNames]);n }nn array.push(material.onBeforeCompile.toString());n array.push(renderer.gammaOutput);n array.push(renderer.gammaFactor);n return array.join();n };nn this.acquireProgram = function (material, shader, parameters, code) {n var program; // Check if code has been already compilednn for (var p = 0, pl = programs.length; p < pl; p++) {n var programInfo = programs;nn if (programInfo.code === code) {n program = programInfo;n ++program.usedTimes;n break;n }n }nn if (program === undefined) {n program = new WebGLProgram(renderer, extensions, code, material, shader, parameters, capabilities);n programs.push(program);n }nn return program;n };nn this.releaseProgram = function (program) {n if (–program.usedTimes === 0) {n // Remove from unordered setn var i = programs.indexOf(program);n programs = programs[programs.length - 1];n programs.pop(); // Free WebGL resourcesnn program.destroy();n }n }; // Exposed for resource monitoring & error feedback via renderer.info:nnn this.programs = programs;n}n/**n * @author fordacious / fordacious.github.ion */nnnfunction WebGLProperties() {n var properties = new WeakMap();nn function get(object) {n var map = properties.get(object);nn if (map === undefined) {n map = {};n properties.set(object, map);n }nn return map;n }nn function remove(object) {n properties(object);n }nn function update(object, key, value) {n properties.get(object) = value;n }nn function dispose() {n properties = new WeakMap();n }nn return {n get: get,n remove: remove,n update: update,n dispose: disposen };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction painterSortStable(a, b) {n if (a.groupOrder !== b.groupOrder) {n return a.groupOrder - b.groupOrder;n } else if (a.renderOrder !== b.renderOrder) {n return a.renderOrder - b.renderOrder;n } else if (a.program !== b.program) {n return a.program.id - b.program.id;n } else if (a.material.id !== b.material.id) {n return a.material.id - b.material.id;n } else if (a.z !== b.z) {n return a.z - b.z;n } else {n return a.id - b.id;n }n}nnfunction reversePainterSortStable(a, b) {n if (a.groupOrder !== b.groupOrder) {n return a.groupOrder - b.groupOrder;n } else if (a.renderOrder !== b.renderOrder) {n return a.renderOrder - b.renderOrder;n } else if (a.z !== b.z) {n return b.z - a.z;n } else {n return a.id - b.id;n }n}nnfunction WebGLRenderList() {n var renderItems = [];n var renderItemsIndex = 0;n var opaque = [];n var transparent = [];n var defaultProgram = {n id: -1n };nn function init() {n renderItemsIndex = 0;n opaque.length = 0;n transparent.length = 0;n }nn function getNextRenderItem(object, geometry, material, groupOrder, z, group) {n var renderItem = renderItems;nn if (renderItem === undefined) {n renderItem = {n id: object.id,n object: object,n geometry: geometry,n material: material,n program: material.program || defaultProgram,n groupOrder: groupOrder,n renderOrder: object.renderOrder,n z: z,n group: groupn };n renderItems = renderItem;n } else {n renderItem.id = object.id;n renderItem.object = object;n renderItem.geometry = geometry;n renderItem.material = material;n renderItem.program = material.program || defaultProgram;n renderItem.groupOrder = groupOrder;n renderItem.renderOrder = object.renderOrder;n renderItem.z = z;n renderItem.group = group;n }nn renderItemsIndex++;n return renderItem;n }nn function push(object, geometry, material, groupOrder, z, group) {n var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);n (material.transparent === true ? transparent : opaque).push(renderItem);n }nn function unshift(object, geometry, material, groupOrder, z, group) {n var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);n (material.transparent === true ? transparent : opaque).unshift(renderItem);n }nn function sort() {n if (opaque.length > 1) opaque.sort(painterSortStable);n if (transparent.length > 1) transparent.sort(reversePainterSortStable);n }nn return {n opaque: opaque,n transparent: transparent,n init: init,n push: push,n unshift: unshift,n sort: sortn };n}nnfunction WebGLRenderLists() {n var lists = new WeakMap();nn function onSceneDispose(event) {n var scene = event.target;n scene.removeEventListener('dispose', onSceneDispose);n lists(scene);n }nn function get(scene, camera) {n var cameras = lists.get(scene);n var list;nn if (cameras === undefined) {n list = new WebGLRenderList();n lists.set(scene, new WeakMap());n lists.get(scene).set(camera, list);n scene.addEventListener('dispose', onSceneDispose);n } else {n list = cameras.get(camera);nn if (list === undefined) {n list = new WebGLRenderList();n cameras.set(camera, list);n }n }nn return list;n }nn function dispose() {n lists = new WeakMap();n }nn return {n get: get,n dispose: disposen };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction UniformsCache() {n var lights = {};n return {n get: function get(light) {n if (lights !== undefined) {n return lights;n }nn var uniforms;nn switch (light.type) {n case 'DirectionalLight':n uniforms = {n direction: new Vector3(),n color: new Color(),n shadow: false,n shadowBias: 0,n shadowRadius: 1,n shadowMapSize: new Vector2()n };n break;nn case 'SpotLight':n uniforms = {n position: new Vector3(),n direction: new Vector3(),n color: new Color(),n distance: 0,n coneCos: 0,n penumbraCos: 0,n decay: 0,n shadow: false,n shadowBias: 0,n shadowRadius: 1,n shadowMapSize: new Vector2()n };n break;nn case 'PointLight':n uniforms = {n position: new Vector3(),n color: new Color(),n distance: 0,n decay: 0,n shadow: false,n shadowBias: 0,n shadowRadius: 1,n shadowMapSize: new Vector2(),n shadowCameraNear: 1,n shadowCameraFar: 1000n };n break;nn case 'HemisphereLight':n uniforms = {n direction: new Vector3(),n skyColor: new Color(),n groundColor: new Color()n };n break;nn case 'RectAreaLight':n uniforms = {n color: new Color(),n position: new Vector3(),n halfWidth: new Vector3(),n halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniformsnn };n break;n }nn lights = uniforms;n return uniforms;n }n };n}nnvar nextVersion = 0;nnfunction shadowCastingLightsFirst(lightA, lightB) {n return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);n}nnfunction WebGLLights() {n var cache = new UniformsCache();n var state = {n version: 0,n hash: {n directionalLength: -1,n pointLength: -1,n spotLength: -1,n rectAreaLength: -1,n hemiLength: -1,n numDirectionalShadows: -1,n numPointShadows: -1,n numSpotShadows: -1n },n ambient: [0, 0, 0],n probe: [],n directional: [],n directionalShadowMap: [],n directionalShadowMatrix: [],n spot: [],n spotShadowMap: [],n spotShadowMatrix: [],n rectArea: [],n point: [],n pointShadowMap: [],n pointShadowMatrix: [],n hemi: [],n numDirectionalShadows: -1,n numPointShadows: -1,n numSpotShadows: -1n };nn for (var i = 0; i < 9; i++) {n state.probe.push(new Vector3());n }nn var vector3 = new Vector3();n var matrix4 = new Matrix4();n var matrix42 = new Matrix4();nn function setup(lights, shadows, camera) {n var r = 0,n g = 0,n b = 0;nn for (var i = 0; i < 9; i++) {n state.probe.set(0, 0, 0);n }nn var directionalLength = 0;n var pointLength = 0;n var spotLength = 0;n var rectAreaLength = 0;n var hemiLength = 0;n var numDirectionalShadows = 0;n var numPointShadows = 0;n var numSpotShadows = 0;n var viewMatrix = camera.matrixWorldInverse;n lights.sort(shadowCastingLightsFirst);nn for (var i = 0, l = lights.length; i < l; i++) {n var light = lights;n var color = light.color;n var intensity = light.intensity;n var distance = light.distance;n var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;nn if (light.isAmbientLight) {n r += color.r * intensity;n g += color.g * intensity;n b += color.b * intensity;n } else if (light.isLightProbe) {n for (var j = 0; j < 9; j++) {n state.probe.addScaledVector(light.sh.coefficients, intensity);n }n } else if (light.isDirectionalLight) {n var uniforms = cache.get(light);n uniforms.color.copy(light.color).multiplyScalar(light.intensity);n uniforms.direction.setFromMatrixPosition(light.matrixWorld);n vector3.setFromMatrixPosition(light.target.matrixWorld);n uniforms.direction.sub(vector3);n uniforms.direction.transformDirection(viewMatrix);n uniforms.shadow = light.castShadow;nn if (light.castShadow) {n var shadow = light.shadow;n uniforms.shadowBias = shadow.bias;n uniforms.shadowRadius = shadow.radius;n uniforms.shadowMapSize = shadow.mapSize;n state.directionalShadowMap = shadowMap;n state.directionalShadowMatrix = light.shadow.matrix;n numDirectionalShadows++;n }nn state.directional = uniforms;n directionalLength++;n } else if (light.isSpotLight) {n var uniforms = cache.get(light);n uniforms.position.setFromMatrixPosition(light.matrixWorld);n uniforms.position.applyMatrix4(viewMatrix);n uniforms.color.copy(color).multiplyScalar(intensity);n uniforms.distance = distance;n uniforms.direction.setFromMatrixPosition(light.matrixWorld);n vector3.setFromMatrixPosition(light.target.matrixWorld);n uniforms.direction.sub(vector3);n uniforms.direction.transformDirection(viewMatrix);n uniforms.coneCos = Math.cos(light.angle);n uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));n uniforms.decay = light.decay;n uniforms.shadow = light.castShadow;nn if (light.castShadow) {n var shadow = light.shadow;n uniforms.shadowBias = shadow.bias;n uniforms.shadowRadius = shadow.radius;n uniforms.shadowMapSize = shadow.mapSize;n state.spotShadowMap = shadowMap;n state.spotShadowMatrix = light.shadow.matrix;n numSpotShadows++;n }nn state.spot = uniforms;n spotLength++;n } else if (light.isRectAreaLight) {n var uniforms = cache.get(light); // (a) intensity is the total visible light emittedn //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );n // (b) intensity is the brightness of the lightnn uniforms.color.copy(color).multiplyScalar(intensity);n uniforms.position.setFromMatrixPosition(light.matrixWorld);n uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectorsnn matrix42.identity();n matrix4.copy(light.matrixWorld);n matrix4.premultiply(viewMatrix);n matrix42.extractRotation(matrix4);n uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);n uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);n uniforms.halfWidth.applyMatrix4(matrix42);n uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?n // uniforms.distance = distance;nn state.rectArea = uniforms;n rectAreaLength++;n } else if (light.isPointLight) {n var uniforms = cache.get(light);n uniforms.position.setFromMatrixPosition(light.matrixWorld);n uniforms.position.applyMatrix4(viewMatrix);n uniforms.color.copy(light.color).multiplyScalar(light.intensity);n uniforms.distance = light.distance;n uniforms.decay = light.decay;n uniforms.shadow = light.castShadow;nn if (light.castShadow) {n var shadow = light.shadow;n uniforms.shadowBias = shadow.bias;n uniforms.shadowRadius = shadow.radius;n uniforms.shadowMapSize = shadow.mapSize;n uniforms.shadowCameraNear = shadow.camera.near;n uniforms.shadowCameraFar = shadow.camera.far;n state.pointShadowMap = shadowMap;n state.pointShadowMatrix = light.shadow.matrix;n numPointShadows++;n }nn state.point = uniforms;n pointLength++;n } else if (light.isHemisphereLight) {n var uniforms = cache.get(light);n uniforms.direction.setFromMatrixPosition(light.matrixWorld);n uniforms.direction.transformDirection(viewMatrix);n uniforms.direction.normalize();n uniforms.skyColor.copy(light.color).multiplyScalar(intensity);n uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);n state.hemi = uniforms;n hemiLength++;n }n }nn state.ambient = r;n state.ambient = g;n state.ambient = b;n var hash = state.hash;nn if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {n state.directional.length = directionalLength;n state.spot.length = spotLength;n state.rectArea.length = rectAreaLength;n state.point.length = pointLength;n state.hemi.length = hemiLength;n state.directionalShadowMap.length = numDirectionalShadows;n state.pointShadowMap.length = numPointShadows;n state.spotShadowMap.length = numSpotShadows;n state.directionalShadowMatrix.length = numDirectionalShadows;n state.pointShadowMatrix.length = numPointShadows;n state.spotShadowMatrix.length = numSpotShadows;n hash.directionalLength = directionalLength;n hash.pointLength = pointLength;n hash.spotLength = spotLength;n hash.rectAreaLength = rectAreaLength;n hash.hemiLength = hemiLength;n hash.numDirectionalShadows = numDirectionalShadows;n hash.numPointShadows = numPointShadows;n hash.numSpotShadows = numSpotShadows;n state.version = nextVersion++;n }n }nn return {n setup: setup,n state: staten };n}n/**n * @author Mugen87 / github.com/Mugen87n */nnnfunction WebGLRenderState() {n var lights = new WebGLLights();n var lightsArray = [];n var shadowsArray = [];nn function init() {n lightsArray.length = 0;n shadowsArray.length = 0;n }nn function pushLight(light) {n lightsArray.push(light);n }nn function pushShadow(shadowLight) {n shadowsArray.push(shadowLight);n }nn function setupLights(camera) {n lights.setup(lightsArray, shadowsArray, camera);n }nn var state = {n lightsArray: lightsArray,n shadowsArray: shadowsArray,n lights: lightsn };n return {n init: init,n state: state,n setupLights: setupLights,n pushLight: pushLight,n pushShadow: pushShadown };n}nnfunction WebGLRenderStates() {n var renderStates = new WeakMap();nn function onSceneDispose(event) {n var scene = event.target;n scene.removeEventListener('dispose', onSceneDispose);n renderStates(scene);n }nn function get(scene, camera) {n var renderState;nn if (renderStates.has(scene) === false) {n renderState = new WebGLRenderState();n renderStates.set(scene, new WeakMap());n renderStates.get(scene).set(camera, renderState);n scene.addEventListener('dispose', onSceneDispose);n } else {n if (renderStates.get(scene).has(camera) === false) {n renderState = new WebGLRenderState();n renderStates.get(scene).set(camera, renderState);n } else {n renderState = renderStates.get(scene).get(camera);n }n }nn return renderState;n }nn function dispose() {n renderStates = new WeakMap();n }nn return {n get: get,n dispose: disposen };n}n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n * @author bhouston / clara.ion * @author WestLangley / github.com/WestLangleyn *n * parameters = {n *n * opacity: <float>,n *n * map: new THREE.Texture( <Image> ),n *n * alphaMap: new THREE.Texture( <Image> ),n *n * displacementMap: new THREE.Texture( <Image> ),n * displacementScale: <float>,n * displacementBias: <float>,n *n * wireframe: <boolean>,n * wireframeLinewidth: <float>n * }n */nnnfunction MeshDepthMaterial(parameters) {n Material.call(this);n this.type = 'MeshDepthMaterial';n this.depthPacking = BasicDepthPacking;n this.skinning = false;n this.morphTargets = false;n this.map = null;n this.alphaMap = null;n this.displacementMap = null;n this.displacementScale = 1;n this.displacementBias = 0;n this.wireframe = false;n this.wireframeLinewidth = 1;n this.fog = false;n this.lights = false;n this.setValues(parameters);n}nnMeshDepthMaterial.prototype = Object.create(Material.prototype);nMeshDepthMaterial.prototype.constructor = MeshDepthMaterial;nMeshDepthMaterial.prototype.isMeshDepthMaterial = true;nnMeshDepthMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.depthPacking = source.depthPacking;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.map = source.map;n this.alphaMap = source.alphaMap;n this.displacementMap = source.displacementMap;n this.displacementScale = source.displacementScale;n this.displacementBias = source.displacementBias;n this.wireframe = source.wireframe;n this.wireframeLinewidth = source.wireframeLinewidth;n return this;n};n/**n * @author WestLangley / github.com/WestLangleyn *n * parameters = {n *n * referencePosition: <float>,n * nearDistance: <float>,n * farDistance: <float>,n *n * skinning: <bool>,n * morphTargets: <bool>,n *n * map: new THREE.Texture( <Image> ),n *n * alphaMap: new THREE.Texture( <Image> ),n *n * displacementMap: new THREE.Texture( <Image> ),n * displacementScale: <float>,n * displacementBias: <float>n *n * }n */nnnfunction MeshDistanceMaterial(parameters) {n Material.call(this);n this.type = 'MeshDistanceMaterial';n this.referencePosition = new Vector3();n this.nearDistance = 1;n this.farDistance = 1000;n this.skinning = false;n this.morphTargets = false;n this.map = null;n this.alphaMap = null;n this.displacementMap = null;n this.displacementScale = 1;n this.displacementBias = 0;n this.fog = false;n this.lights = false;n this.setValues(parameters);n}nnMeshDistanceMaterial.prototype = Object.create(Material.prototype);nMeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;nMeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;nnMeshDistanceMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.referencePosition.copy(source.referencePosition);n this.nearDistance = source.nearDistance;n this.farDistance = source.farDistance;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.map = source.map;n this.alphaMap = source.alphaMap;n this.displacementMap = source.displacementMap;n this.displacementScale = source.displacementScale;n this.displacementBias = source.displacementBias;n return this;n};nnvar vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n \n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n ifdef HORIZONAL_PASS\n vec2 distribution = decodeHalfRGBA ( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = pow( squared_mean - mean * mean, 0.5 );\n gl_FragColor = encodeHalfRGBA( vec2( mean, std_dev ) );\n}";nvar vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n */nnfunction WebGLShadowMap(_renderer, _objects, maxTextureSize) {n var _frustum = new Frustum(),n _shadowMapSize = new Vector2(),n _viewportSize = new Vector2(),n _viewport = new Vector4(),n _MorphingFlag = 1,n _SkinningFlag = 2,n _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,n _depthMaterials = new Array(_NumberOfMaterialVariants),n _distanceMaterials = new Array(_NumberOfMaterialVariants),n _materialCache = {};nn var shadowSide = {n 0: BackSide,n 1: FrontSide,n 2: DoubleSiden };n var shadowMaterialVertical = new ShaderMaterial({n defines: {n SAMPLE_RATE: 2.0 / 8.0,n HALF_SAMPLE_RATE: 1.0 / 8.0n },n uniforms: {n shadow_pass: {n value: nulln },n resolution: {n value: new Vector2()n },n radius: {n value: 4.0n }n },n vertexShader: vsm_vert,n fragmentShader: vsm_fragn });n var shadowMaterialHorizonal = shadowMaterialVertical.clone();n shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;n var fullScreenTri = new BufferGeometry();n fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));n var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // initnn for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {n var useMorphing = (i & _MorphingFlag) !== 0;n var useSkinning = (i & _SkinningFlag) !== 0;n var depthMaterial = new MeshDepthMaterial({n depthPacking: RGBADepthPacking,n morphTargets: useMorphing,n skinning: useSkinningn });n _depthMaterials = depthMaterial;n var distanceMaterial = new MeshDistanceMaterial({n morphTargets: useMorphing,n skinning: useSkinningn });n _distanceMaterials = distanceMaterial;n }nn var scope = this;n this.enabled = false;n this.autoUpdate = true;n this.needsUpdate = false;n this.type = PCFShadowMap;nn this.render = function (lights, scene, camera) {n if (scope.enabled === false) return;n if (scope.autoUpdate === false && scope.needsUpdate === false) return;n if (lights.length === 0) return;nn var currentRenderTarget = _renderer.getRenderTarget();nn var activeCubeFace = _renderer.getActiveCubeFace();nn var activeMipmapLevel = _renderer.getActiveMipmapLevel();nn var _state = _renderer.state; // Set GL state for depth map.nn _state.setBlending(NoBlending);nn _state.buffers.color.setClear(1, 1, 1, 1);nn _state.buffers.depth.setTest(true);nn _state.setScissorTest(false); // render depth mapnnn for (var i = 0, il = lights.length; i < il; i++) {n var light = lights;n var shadow = light.shadow;nn if (shadow === undefined) {n console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');n continue;n }nn _shadowMapSize.copy(shadow.mapSize);nn var shadowFrameExtents = shadow.getFrameExtents();nn _shadowMapSize.multiply(shadowFrameExtents);nn _viewportSize.copy(shadow.mapSize);nn if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {n console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');nn if (_shadowMapSize.x > maxTextureSize) {n _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);n _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;n shadow.mapSize.x = _viewportSize.x;n }nn if (_shadowMapSize.y > maxTextureSize) {n _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);n _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;n shadow.mapSize.y = _viewportSize.y;n }n }nn if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {n var pars = {n minFilter: LinearFilter,n magFilter: LinearFilter,n format: RGBAFormatn };n shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);n shadow.map.texture.name = light.name + ".shadowMap";n shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);n shadow.camera.updateProjectionMatrix();n }nn if (shadow.map === null) {n var pars = {n minFilter: NearestFilter,n magFilter: NearestFilter,n format: RGBAFormatn };n shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);n shadow.map.texture.name = light.name + ".shadowMap";n shadow.camera.updateProjectionMatrix();n }nn _renderer.setRenderTarget(shadow.map);nn _renderer.clear();nn var viewportCount = shadow.getViewportCount();nn for (var vp = 0; vp < viewportCount; vp++) {n var viewport = shadow.getViewport(vp);nn _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);nn _state.viewport(_viewport);nn shadow.updateMatrices(light, camera, vp);n _frustum = shadow.getFrustum();n renderObject(scene, camera, shadow.camera, light, this.type);n } // do blur pass for VSMnnn if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {n VSMPass(shadow, camera);n }n }nn scope.needsUpdate = false;nn _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);n };nn function VSMPass(shadow, camera) {n var geometry = _objects.update(fullScreenMesh); // vertical passnnn shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;n shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;n shadowMaterialVertical.uniforms.radius.value = shadow.radius;nn _renderer.setRenderTarget(shadow.mapPass);nn _renderer.clear();nn _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal passnnn shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;n shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;n shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;nn _renderer.setRenderTarget(shadow.map);nn _renderer.clear();nn _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);n }nn function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {n var geometry = object.geometry;n var result = null;n var materialVariants = _depthMaterials;n var customMaterial = object.customDepthMaterial;nn if (light.isPointLight) {n materialVariants = _distanceMaterials;n customMaterial = object.customDistanceMaterial;n }nn if (!customMaterial) {n var useMorphing = false;nn if (material.morphTargets) {n if (geometry && geometry.isBufferGeometry) {n useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;n } else if (geometry && geometry.isGeometry) {n useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;n }n }nn if (object.isSkinnedMesh && material.skinning === false) {n console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);n }nn var useSkinning = object.isSkinnedMesh && material.skinning;n var variantIndex = 0;n if (useMorphing) variantIndex |= _MorphingFlag;n if (useSkinning) variantIndex |= _SkinningFlag;n result = materialVariants;n } else {n result = customMaterial;n }nn if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {n // in this case we need a unique material instance reflecting then // appropriate staten var keyA = result.uuid,n keyB = material.uuid;n var materialsForVariant = _materialCache;nn if (materialsForVariant === undefined) {n materialsForVariant = {};n _materialCache = materialsForVariant;n }nn var cachedMaterial = materialsForVariant;nn if (cachedMaterial === undefined) {n cachedMaterial = result.clone();n materialsForVariant = cachedMaterial;n }nn result = cachedMaterial;n }nn result.visible = material.visible;n result.wireframe = material.wireframe;nn if (type === VSMShadowMap) {n result.side = material.shadowSide != null ? material.shadowSide : material.side;n } else {n result.side = material.shadowSide != null ? material.shadowSide : shadowSide;n }nn result.clipShadows = material.clipShadows;n result.clippingPlanes = material.clippingPlanes;n result.clipIntersection = material.clipIntersection;n result.wireframeLinewidth = material.wireframeLinewidth;n result.linewidth = material.linewidth;nn if (light.isPointLight && result.isMeshDistanceMaterial) {n result.referencePosition.setFromMatrixPosition(light.matrixWorld);n result.nearDistance = shadowCameraNear;n result.farDistance = shadowCameraFar;n }nn return result;n }nn function renderObject(object, camera, shadowCamera, light, type) {n if (object.visible === false) return;n var visible = object.layers.test(camera.layers);nn if (visible && (object.isMesh || object.isLine || object.isPoints)) {n if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {n object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);nn var geometry = _objects.update(object);nn var material = object.material;nn if (Array.isArray(material)) {n var groups = geometry.groups;nn for (var k = 0, kl = groups.length; k < kl; k++) {n var group = groups;n var groupMaterial = material;nn if (groupMaterial && groupMaterial.visible) {n var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);nn _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);n }n }n } else if (material.visible) {n var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);nn _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);n }n }n }nn var children = object.children;nn for (var i = 0, l = children.length; i < l; i++) {n renderObject(children, camera, shadowCamera, light, type);n }n }n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLState(gl, extensions, utils, capabilities) {n function ColorBuffer() {n var locked = false;n var color = new Vector4();n var currentColorMask = null;n var currentColorClear = new Vector4(0, 0, 0, 0);n return {n setMask: function setMask(colorMask) {n if (currentColorMask !== colorMask && !locked) {n gl.colorMask(colorMask, colorMask, colorMask, colorMask);n currentColorMask = colorMask;n }n },n setLocked: function setLocked(lock) {n locked = lock;n },n setClear: function setClear(r, g, b, a, premultipliedAlpha) {n if (premultipliedAlpha === true) {n r *= a;n g *= a;n b *= a;n }nn color.set(r, g, b, a);nn if (currentColorClear.equals(color) === false) {n gl.clearColor(r, g, b, a);n currentColorClear.copy(color);n }n },n reset: function reset() {n locked = false;n currentColorMask = null;n currentColorClear.set(-1, 0, 0, 0); // set to invalid staten }n };n }nn function DepthBuffer() {n var locked = false;n var currentDepthMask = null;n var currentDepthFunc = null;n var currentDepthClear = null;n return {n setTest: function setTest(depthTest) {n if (depthTest) {n enable(2929);n } else {n disable(2929);n }n },n setMask: function setMask(depthMask) {n if (currentDepthMask !== depthMask && !locked) {n gl.depthMask(depthMask);n currentDepthMask = depthMask;n }n },n setFunc: function setFunc(depthFunc) {n if (currentDepthFunc !== depthFunc) {n if (depthFunc) {n switch (depthFunc) {n case NeverDepth:n gl.depthFunc(512);n break;nn case AlwaysDepth:n gl.depthFunc(519);n break;nn case LessDepth:n gl.depthFunc(513);n break;nn case LessEqualDepth:n gl.depthFunc(515);n break;nn case EqualDepth:n gl.depthFunc(514);n break;nn case GreaterEqualDepth:n gl.depthFunc(518);n break;nn case GreaterDepth:n gl.depthFunc(516);n break;nn case NotEqualDepth:n gl.depthFunc(517);n break;nn default:n gl.depthFunc(515);n }n } else {n gl.depthFunc(515);n }nn currentDepthFunc = depthFunc;n }n },n setLocked: function setLocked(lock) {n locked = lock;n },n setClear: function setClear(depth) {n if (currentDepthClear !== depth) {n gl.clearDepth(depth);n currentDepthClear = depth;n }n },n reset: function reset() {n locked = false;n currentDepthMask = null;n currentDepthFunc = null;n currentDepthClear = null;n }n };n }nn function StencilBuffer() {n var locked = false;n var currentStencilMask = null;n var currentStencilFunc = null;n var currentStencilRef = null;n var currentStencilFuncMask = null;n var currentStencilFail = null;n var currentStencilZFail = null;n var currentStencilZPass = null;n var currentStencilClear = null;n return {n setTest: function setTest(stencilTest) {n if (!locked) {n if (stencilTest) {n enable(2960);n } else {n disable(2960);n }n }n },n setMask: function setMask(stencilMask) {n if (currentStencilMask !== stencilMask && !locked) {n gl.stencilMask(stencilMask);n currentStencilMask = stencilMask;n }n },n setFunc: function setFunc(stencilFunc, stencilRef, stencilMask) {n if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {n gl.stencilFunc(stencilFunc, stencilRef, stencilMask);n currentStencilFunc = stencilFunc;n currentStencilRef = stencilRef;n currentStencilFuncMask = stencilMask;n }n },n setOp: function setOp(stencilFail, stencilZFail, stencilZPass) {n if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {n gl.stencilOp(stencilFail, stencilZFail, stencilZPass);n currentStencilFail = stencilFail;n currentStencilZFail = stencilZFail;n currentStencilZPass = stencilZPass;n }n },n setLocked: function setLocked(lock) {n locked = lock;n },n setClear: function setClear(stencil) {n if (currentStencilClear !== stencil) {n gl.clearStencil(stencil);n currentStencilClear = stencil;n }n },n reset: function reset() {n locked = false;n currentStencilMask = null;n currentStencilFunc = null;n currentStencilRef = null;n currentStencilFuncMask = null;n currentStencilFail = null;n currentStencilZFail = null;n currentStencilZPass = null;n currentStencilClear = null;n }n };n } //nnn var colorBuffer = new ColorBuffer();n var depthBuffer = new DepthBuffer();n var stencilBuffer = new StencilBuffer();n var maxVertexAttributes = gl.getParameter(34921);n var newAttributes = new Uint8Array(maxVertexAttributes);n var enabledAttributes = new Uint8Array(maxVertexAttributes);n var attributeDivisors = new Uint8Array(maxVertexAttributes);n var enabledCapabilities = {};n var compressedTextureFormats = null;n var currentProgram = null;n var currentBlendingEnabled = null;n var currentBlending = null;n var currentBlendEquation = null;n var currentBlendSrc = null;n var currentBlendDst = null;n var currentBlendEquationAlpha = null;n var currentBlendSrcAlpha = null;n var currentBlendDstAlpha = null;n var currentPremultipledAlpha = false;n var currentFlipSided = null;n var currentCullFace = null;n var currentLineWidth = null;n var currentPolygonOffsetFactor = null;n var currentPolygonOffsetUnits = null;n var maxTextures = gl.getParameter(35661);n var lineWidthAvailable = false;n var version = 0;n var glVersion = gl.getParameter(7938);nn if (glVersion.indexOf('WebGL') !== -1) {n version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion));n lineWidthAvailable = version >= 1.0;n } else if (glVersion.indexOf('OpenGL ES') !== -1) {n version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion));n lineWidthAvailable = version >= 2.0;n }nn var currentTextureSlot = null;n var currentBoundTextures = {};n var currentScissor = new Vector4();n var currentViewport = new Vector4();nn function createTexture(type, target, count) {n var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.nn var texture = gl.createTexture();n gl.bindTexture(type, texture);n gl.texParameteri(type, 10241, 9728);n gl.texParameteri(type, 10240, 9728);nn for (var i = 0; i < count; i++) {n gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);n }nn return texture;n }nn var emptyTextures = {};n emptyTextures = createTexture(3553, 3553, 1);n emptyTextures = createTexture(34067, 34069, 6); // initnn colorBuffer.setClear(0, 0, 0, 1);n depthBuffer.setClear(1);n stencilBuffer.setClear(0);n enable(2929);n depthBuffer.setFunc(LessEqualDepth);n setFlipSided(false);n setCullFace(CullFaceBack);n enable(2884);n setBlending(NoBlending); //nn function initAttributes() {n for (var i = 0, l = newAttributes.length; i < l; i++) {n newAttributes = 0;n }n }nn function enableAttribute(attribute) {n enableAttributeAndDivisor(attribute, 0);n }nn function enableAttributeAndDivisor(attribute, meshPerAttribute) {n newAttributes = 1;nn if (enabledAttributes === 0) {n gl.enableVertexAttribArray(attribute);n enabledAttributes = 1;n }nn if (attributeDivisors !== meshPerAttribute) {n var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');n extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);n attributeDivisors = meshPerAttribute;n }n }nn function disableUnusedAttributes() {n for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {n if (enabledAttributes !== newAttributes) {n gl.disableVertexAttribArray(i);n enabledAttributes = 0;n }n }n }nn function enable(id) {n if (enabledCapabilities !== true) {n gl.enable(id);n enabledCapabilities = true;n }n }nn function disable(id) {n if (enabledCapabilities !== false) {n gl.disable(id);n enabledCapabilities = false;n }n }nn function getCompressedTextureFormats() {n if (compressedTextureFormats === null) {n compressedTextureFormats = [];nn if (extensions.get('WEBGL_compressed_texture_pvrtc') || extensions.get('WEBGL_compressed_texture_s3tc') || extensions.get('WEBGL_compressed_texture_etc1') || extensions.get('WEBGL_compressed_texture_astc')) {n var formats = gl.getParameter(34467);nn for (var i = 0; i < formats.length; i++) {n compressedTextureFormats.push(formats);n }n }n }nn return compressedTextureFormats;n }nn function useProgram(program) {n if (currentProgram !== program) {n gl.useProgram(program);n currentProgram = program;n return true;n }nn return false;n }nn function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {n if (blending === NoBlending) {n if (currentBlendingEnabled) {n disable(3042);n currentBlendingEnabled = false;n }nn return;n }nn if (!currentBlendingEnabled) {n enable(3042);n currentBlendingEnabled = true;n }nn if (blending !== CustomBlending) {n if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {n if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {n gl.blendEquation(32774);n currentBlendEquation = AddEquation;n currentBlendEquationAlpha = AddEquation;n }nn if (premultipliedAlpha) {n switch (blending) {n case NormalBlending:n gl.blendFuncSeparate(1, 771, 1, 771);n break;nn case AdditiveBlending:n gl.blendFunc(1, 1);n break;nn case SubtractiveBlending:n gl.blendFuncSeparate(0, 0, 769, 771);n break;nn case MultiplyBlending:n gl.blendFuncSeparate(0, 768, 0, 770);n break;nn default:n console.error('THREE.WebGLState: Invalid blending: ', blending);n break;n }n } else {n switch (blending) {n case NormalBlending:n gl.blendFuncSeparate(770, 771, 1, 771);n break;nn case AdditiveBlending:n gl.blendFunc(770, 1);n break;nn case SubtractiveBlending:n gl.blendFunc(0, 769);n break;nn case MultiplyBlending:n gl.blendFunc(0, 768);n break;nn default:n console.error('THREE.WebGLState: Invalid blending: ', blending);n break;n }n }nn currentBlendSrc = null;n currentBlendDst = null;n currentBlendSrcAlpha = null;n currentBlendDstAlpha = null;n currentBlending = blending;n currentPremultipledAlpha = premultipliedAlpha;n }nn return;n } // custom blendingnnn blendEquationAlpha = blendEquationAlpha || blendEquation;n blendSrcAlpha = blendSrcAlpha || blendSrc;n blendDstAlpha = blendDstAlpha || blendDst;nn if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {n gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));n currentBlendEquation = blendEquation;n currentBlendEquationAlpha = blendEquationAlpha;n }nn if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {n gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));n currentBlendSrc = blendSrc;n currentBlendDst = blendDst;n currentBlendSrcAlpha = blendSrcAlpha;n currentBlendDstAlpha = blendDstAlpha;n }nn currentBlending = blending;n currentPremultipledAlpha = null;n }nn function setMaterial(material, frontFaceCW) {n material.side === DoubleSide ? disable(2884) : enable(2884);n var flipSided = material.side === BackSide;n if (frontFaceCW) flipSided = !flipSided;n setFlipSided(flipSided);n material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);n depthBuffer.setFunc(material.depthFunc);n depthBuffer.setTest(material.depthTest);n depthBuffer.setMask(material.depthWrite);n colorBuffer.setMask(material.colorWrite);n var stencilWrite = material.stencilWrite;n stencilBuffer.setTest(stencilWrite);nn if (stencilWrite) {n stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilMask);n stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);n }nn setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);n } //nnn function setFlipSided(flipSided) {n if (currentFlipSided !== flipSided) {n if (flipSided) {n gl.frontFace(2304);n } else {n gl.frontFace(2305);n }nn currentFlipSided = flipSided;n }n }nn function setCullFace(cullFace) {n if (cullFace !== CullFaceNone) {n enable(2884);nn if (cullFace !== currentCullFace) {n if (cullFace === CullFaceBack) {n gl.cullFace(1029);n } else if (cullFace === CullFaceFront) {n gl.cullFace(1028);n } else {n gl.cullFace(1032);n }n }n } else {n disable(2884);n }nn currentCullFace = cullFace;n }nn function setLineWidth(width) {n if (width !== currentLineWidth) {n if (lineWidthAvailable) gl.lineWidth(width);n currentLineWidth = width;n }n }nn function setPolygonOffset(polygonOffset, factor, units) {n if (polygonOffset) {n enable(32823);nn if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {n gl.polygonOffset(factor, units);n currentPolygonOffsetFactor = factor;n currentPolygonOffsetUnits = units;n }n } else {n disable(32823);n }n }nn function setScissorTest(scissorTest) {n if (scissorTest) {n enable(3089);n } else {n disable(3089);n }n } // texturennn function activeTexture(webglSlot) {n if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;nn if (currentTextureSlot !== webglSlot) {n gl.activeTexture(webglSlot);n currentTextureSlot = webglSlot;n }n }nn function bindTexture(webglType, webglTexture) {n if (currentTextureSlot === null) {n activeTexture();n }nn var boundTexture = currentBoundTextures;nn if (boundTexture === undefined) {n boundTexture = {n type: undefined,n texture: undefinedn };n currentBoundTextures = boundTexture;n }nn if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {n gl.bindTexture(webglType, webglTexture || emptyTextures);n boundTexture.type = webglType;n boundTexture.texture = webglTexture;n }n }nn function compressedTexImage2D() {n try {n gl.compressedTexImage2D.apply(gl, arguments);n } catch (error) {n console.error('THREE.WebGLState:', error);n }n }nn function texImage2D() {n try {n gl.texImage2D.apply(gl, arguments);n } catch (error) {n console.error('THREE.WebGLState:', error);n }n }nn function texImage3D() {n try {n gl.texImage3D.apply(gl, arguments);n } catch (error) {n console.error('THREE.WebGLState:', error);n }n } //nnn function scissor(scissor) {n if (currentScissor.equals(scissor) === false) {n gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);n currentScissor.copy(scissor);n }n }nn function viewport(viewport) {n if (currentViewport.equals(viewport) === false) {n gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);n currentViewport.copy(viewport);n }n } //nnn function reset() {n for (var i = 0; i < enabledAttributes.length; i++) {n if (enabledAttributes === 1) {n gl.disableVertexAttribArray(i);n enabledAttributes = 0;n }n }nn enabledCapabilities = {};n compressedTextureFormats = null;n currentTextureSlot = null;n currentBoundTextures = {};n currentProgram = null;n currentBlending = null;n currentFlipSided = null;n currentCullFace = null;n colorBuffer.reset();n depthBuffer.reset();n stencilBuffer.reset();n }nn return {n buffers: {n color: colorBuffer,n depth: depthBuffer,n stencil: stencilBuffern },n initAttributes: initAttributes,n enableAttribute: enableAttribute,n enableAttributeAndDivisor: enableAttributeAndDivisor,n disableUnusedAttributes: disableUnusedAttributes,n enable: enable,n disable: disable,n getCompressedTextureFormats: getCompressedTextureFormats,n useProgram: useProgram,n setBlending: setBlending,n setMaterial: setMaterial,n setFlipSided: setFlipSided,n setCullFace: setCullFace,n setLineWidth: setLineWidth,n setPolygonOffset: setPolygonOffset,n setScissorTest: setScissorTest,n activeTexture: activeTexture,n bindTexture: bindTexture,n compressedTexImage2D: compressedTexImage2D,n texImage2D: texImage2D,n texImage3D: texImage3D,n scissor: scissor,n viewport: viewport,n reset: resetn };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {n var _videoTextures = new WeakMap();nn var _canvas; //nnn var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined';nn function createCanvas(width, height) {n // Use OffscreenCanvas when available. Specially needed in web workersn return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('www.w3.org/1999/xhtml', 'canvas');n }nn function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {n var scale = 1; // handle case if texture exceeds max sizenn if (image.width > maxSize || image.height > maxSize) {n scale = maxSize / Math.max(image.width, image.height);n } // only perform resize if necessarynnn if (scale < 1 || needsPowerOfTwo === true) {n // only perform resize for certain image typesn if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {n var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;n var width = floor(scale * image.width);n var height = floor(scale * image.height);n if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvasnn var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;n canvas.width = width;n canvas.height = height;n var context = canvas.getContext('2d');n context.drawImage(image, 0, 0, width, height);n console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');n return canvas;n } else {n if ('data' in image) {n console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');n }nn return image;n }n }nn return image;n }nn function isPowerOfTwo(image) {n return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);n }nn function textureNeedsPowerOfTwo(texture) {n if (capabilities.isWebGL2) return false;n return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;n }nn function textureNeedsGenerateMipmaps(texture, supportsMips) {n return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;n }nn function generateMipmap(target, texture, width, height) {n _gl.generateMipmap(target);nn var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11nn textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;n }nn function getInternalFormat(glFormat, glType) {n if (!capabilities.isWebGL2) return glFormat;n var internalFormat = glFormat;nn if (glFormat === 6403) {n if (glType === 5126) internalFormat = 33326;n if (glType === 5131) internalFormat = 33325;n if (glType === 5121) internalFormat = 33321;n }nn if (glFormat === 6407) {n if (glType === 5126) internalFormat = 34837;n if (glType === 5131) internalFormat = 34843;n if (glType === 5121) internalFormat = 32849;n }nn if (glFormat === 6408) {n if (glType === 5126) internalFormat = 34836;n if (glType === 5131) internalFormat = 34842;n if (glType === 5121) internalFormat = 32856;n }nn if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {n extensions.get('EXT_color_buffer_float');n } else if (internalFormat === 34843 || internalFormat === 34837) {n console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');n }nn return internalFormat;n } // Fallback filters for non-power-of-2 texturesnnn function filterFallback(f) {n if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {n return 9728;n }nn return 9729;n } //nnn function onTextureDispose(event) {n var texture = event.target;n texture.removeEventListener('dispose', onTextureDispose);n deallocateTexture(texture);nn if (texture.isVideoTexture) {n _videoTextures(texture);n }nn info.memory.textures–;n }nn function onRenderTargetDispose(event) {n var renderTarget = event.target;n renderTarget.removeEventListener('dispose', onRenderTargetDispose);n deallocateRenderTarget(renderTarget);n info.memory.textures–;n } //nnn function deallocateTexture(texture) {n var textureProperties = properties.get(texture);n if (textureProperties.__webglInit === undefined) return;nn _gl.deleteTexture(textureProperties.__webglTexture);nn properties.remove(texture);n }nn function deallocateRenderTarget(renderTarget) {n var renderTargetProperties = properties.get(renderTarget);n var textureProperties = properties.get(renderTarget.texture);n if (!renderTarget) return;nn if (textureProperties.__webglTexture !== undefined) {n _gl.deleteTexture(textureProperties.__webglTexture);n }nn if (renderTarget.depthTexture) {n renderTarget.depthTexture.dispose();n }nn if (renderTarget.isWebGLRenderTargetCube) {n for (var i = 0; i < 6; i++) {n _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);nn if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);n }n } else {n _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);nn if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);n }nn properties.remove(renderTarget.texture);n properties.remove(renderTarget);n } //nnn var textureUnits = 0;nn function resetTextureUnits() {n textureUnits = 0;n }nn function allocateTextureUnit() {n var textureUnit = textureUnits;nn if (textureUnit >= capabilities.maxTextures) {n console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);n }nn textureUnits += 1;n return textureUnit;n } //nnn function setTexture2D(texture, slot) {n var textureProperties = properties.get(texture);n if (texture.isVideoTexture) updateVideoTexture(texture);nn if (texture.version > 0 && textureProperties.__version !== texture.version) {n var image = texture.image;nn if (image === undefined) {n console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');n } else if (image.complete === false) {n console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');n } else {n uploadTexture(textureProperties, texture, slot);n return;n }n }nn state.activeTexture(33984 + slot);n state.bindTexture(3553, textureProperties.__webglTexture);n }nn function setTexture2DArray(texture, slot) {n var textureProperties = properties.get(texture);nn if (texture.version > 0 && textureProperties.__version !== texture.version) {n uploadTexture(textureProperties, texture, slot);n return;n }nn state.activeTexture(33984 + slot);n state.bindTexture(35866, textureProperties.__webglTexture);n }nn function setTexture3D(texture, slot) {n var textureProperties = properties.get(texture);nn if (texture.version > 0 && textureProperties.__version !== texture.version) {n uploadTexture(textureProperties, texture, slot);n return;n }nn state.activeTexture(33984 + slot);n state.bindTexture(32879, textureProperties.__webglTexture);n }nn function setTextureCube(texture, slot) {n if (texture.image.length !== 6) return;n var textureProperties = properties.get(texture);nn if (texture.version > 0 && textureProperties.__version !== texture.version) {n initTexture(textureProperties, texture);n state.activeTexture(33984 + slot);n state.bindTexture(34067, textureProperties.__webglTexture);nn _gl.pixelStorei(37440, texture.flipY);nn var isCompressed = texture && texture.isCompressedTexture;n var isDataTexture = texture.image && texture.image.isDataTexture;n var cubeImage = [];nn for (var i = 0; i < 6; i++) {n if (!isCompressed && !isDataTexture) {n cubeImage = resizeImage(texture.image, false, true, capabilities.maxCubemapSize);n } else {n cubeImage = isDataTexture ? texture.image.image : texture.image;n }n }nn var image = cubeImage,n supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,n glFormat = utils.convert(texture.format),n glType = utils.convert(texture.type),n glInternalFormat = getInternalFormat(glFormat, glType);n setTextureParameters(34067, texture, supportsMips);n var mipmaps;nn if (isCompressed) {n for (var i = 0; i < 6; i++) {n mipmaps = cubeImage.mipmaps;nn for (var j = 0; j < mipmaps.length; j++) {n var mipmap = mipmaps;nn if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {n if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {n state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);n } else {n console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');n }n } else {n state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);n }n }n }nn textureProperties.__maxMipLevel = mipmaps.length - 1;n } else {n mipmaps = texture.mipmaps;nn for (var i = 0; i < 6; i++) {n if (isDataTexture) {n state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage.width, cubeImage.height, 0, glFormat, glType, cubeImage.data);nn for (var j = 0; j < mipmaps.length; j++) {n var mipmap = mipmaps;n var mipmapImage = mipmap.image.image;n state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);n }n } else {n state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage);nn for (var j = 0; j < mipmaps.length; j++) {n var mipmap = mipmaps;n state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image);n }n }n }nn textureProperties.__maxMipLevel = mipmaps.length;n }nn if (textureNeedsGenerateMipmaps(texture, supportsMips)) {n // We assume images for cube map have the same size.n generateMipmap(34067, texture, image.width, image.height);n }nn textureProperties.__version = texture.version;n if (texture.onUpdate) texture.onUpdate(texture);n } else {n state.activeTexture(33984 + slot);n state.bindTexture(34067, textureProperties.__webglTexture);n }n }nn function setTextureCubeDynamic(texture, slot) {n state.activeTexture(33984 + slot);n state.bindTexture(34067, properties.get(texture).__webglTexture);n }nn function setTextureParameters(textureType, texture, supportsMips) {n var extension;nn if (supportsMips) {n _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));nn _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));nn if (textureType === 32879 || textureType === 35866) {n _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));n }nn _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));nn _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));n } else {n _gl.texParameteri(textureType, 10242, 33071);nn _gl.texParameteri(textureType, 10243, 33071);nn if (textureType === 32879 || textureType === 35866) {n _gl.texParameteri(textureType, 32882, 33071);n }nn if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {n console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');n }nn _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));nn _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));nn if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {n console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');n }n }nn extension = extensions.get('EXT_texture_filter_anisotropic');nn if (extension) {n if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;n if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;nn if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {n _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));nn properties.get(texture).__currentAnisotropy = texture.anisotropy;n }n }n }nn function initTexture(textureProperties, texture) {n if (textureProperties.__webglInit === undefined) {n textureProperties.__webglInit = true;n texture.addEventListener('dispose', onTextureDispose);n textureProperties.__webglTexture = _gl.createTexture();n info.memory.textures++;n }n }nn function uploadTexture(textureProperties, texture, slot) {n var textureType = 3553;n if (texture.isDataTexture2DArray) textureType = 35866;n if (texture.isDataTexture3D) textureType = 32879;n initTexture(textureProperties, texture);n state.activeTexture(33984 + slot);n state.bindTexture(textureType, textureProperties.__webglTexture);nn _gl.pixelStorei(37440, texture.flipY);nn _gl.pixelStorei(37441, texture.premultiplyAlpha);nn _gl.pixelStorei(3317, texture.unpackAlignment);nn var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;n var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);n var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,n glFormat = utils.convert(texture.format),n glType = utils.convert(texture.type),n glInternalFormat = getInternalFormat(glFormat, glType);n setTextureParameters(textureType, texture, supportsMips);n var mipmap,n mipmaps = texture.mipmaps;nn if (texture.isDepthTexture) {n // populate depth texture with dummy datan glInternalFormat = 6402;nn if (texture.type === FloatType) {n if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');n glInternalFormat = 36012;n } else if (capabilities.isWebGL2) {n // WebGL 2.0 requires signed internalformat for glTexImage2Dn glInternalFormat = 33189;n }nn if (texture.format === DepthFormat && glInternalFormat === 6402) {n // The error INVALID_OPERATION is generated by texImage2D if format and internalformat aren // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INTn // (www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)n if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {n console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');n texture.type = UnsignedShortType;n glType = utils.convert(texture.type);n }n } // Depth stencil textures need the DEPTH_STENCIL internal formatn // (www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)nnn if (texture.format === DepthStencilFormat) {n glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat aren // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.n // (www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)nn if (texture.type !== UnsignedInt248Type) {n console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');n texture.type = UnsignedInt248Type;n glType = utils.convert(texture.type);n }n }nn state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);n } else if (texture.isDataTexture) {n // use manually created mipmaps if availablen // if there are no manual mipmapsn // set 0 level mipmap and then use GL to generate other mipmap levelsn if (mipmaps.length > 0 && supportsMips) {n for (var i = 0, il = mipmaps.length; i < il; i++) {n mipmap = mipmaps;n state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);n }nn texture.generateMipmaps = false;n textureProperties.__maxMipLevel = mipmaps.length - 1;n } else {n state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);n textureProperties.__maxMipLevel = 0;n }n } else if (texture.isCompressedTexture) {n for (var i = 0, il = mipmaps.length; i < il; i++) {n mipmap = mipmaps;nn if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {n if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {n state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);n } else {n console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');n }n } else {n state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);n }n }nn textureProperties.__maxMipLevel = mipmaps.length - 1;n } else if (texture.isDataTexture2DArray) {n state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);n textureProperties.__maxMipLevel = 0;n } else if (texture.isDataTexture3D) {n state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);n textureProperties.__maxMipLevel = 0;n } else {n // regular Texture (image, video, canvas)n // use manually created mipmaps if availablen // if there are no manual mipmapsn // set 0 level mipmap and then use GL to generate other mipmap levelsn if (mipmaps.length > 0 && supportsMips) {n for (var i = 0, il = mipmaps.length; i < il; i++) {n mipmap = mipmaps;n state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);n }nn texture.generateMipmaps = false;n textureProperties.__maxMipLevel = mipmaps.length - 1;n } else {n state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);n textureProperties.__maxMipLevel = 0;n }n }nn if (textureNeedsGenerateMipmaps(texture, supportsMips)) {n generateMipmap(3553, texture, image.width, image.height);n }nn textureProperties.__version = texture.version;n if (texture.onUpdate) texture.onUpdate(texture);n } // Render targetsn // Setup storage for target texture and bind it to correct framebuffernnn function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {n var glFormat = utils.convert(renderTarget.texture.format);n var glType = utils.convert(renderTarget.texture.type);n var glInternalFormat = getInternalFormat(glFormat, glType);n state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);nn _gl.bindFramebuffer(36160, framebuffer);nn _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);nn _gl.bindFramebuffer(36160, null);n } // Setup storage for internal depth/stencil buffers and bind to correct framebuffernnn function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {n _gl.bindRenderbuffer(36161, renderbuffer);nn if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {n if (isMultisample) {n var samples = getRenderTargetSamples(renderTarget);nn _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);n } else {n _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);n }nn _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);n } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {n if (isMultisample) {n var samples = getRenderTargetSamples(renderTarget);nn _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);n } else {n _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);n }nn _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);n } else {n var glFormat = utils.convert(renderTarget.texture.format);n var glType = utils.convert(renderTarget.texture.type);n var glInternalFormat = getInternalFormat(glFormat, glType);nn if (isMultisample) {n var samples = getRenderTargetSamples(renderTarget);nn _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);n } else {n _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);n }n }nn _gl.bindRenderbuffer(36161, null);n } // Setup resources for a Depth Texture for a FBO (needs an extension)nnn function setupDepthTexture(framebuffer, renderTarget) {n var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;n if (isCube) throw new Error('Depth Texture with cube render targets is not supported');nn _gl.bindFramebuffer(36160, framebuffer);nn if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {n throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');n } // upload an empty depth texture with framebuffer sizennn if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {n renderTarget.depthTexture.image.width = renderTarget.width;n renderTarget.depthTexture.image.height = renderTarget.height;n renderTarget.depthTexture.needsUpdate = true;n }nn setTexture2D(renderTarget.depthTexture, 0);nn var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;nn if (renderTarget.depthTexture.format === DepthFormat) {n _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);n } else if (renderTarget.depthTexture.format === DepthStencilFormat) {n _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);n } else {n throw new Error('Unknown depthTexture format');n }n } // Setup GL resources for a non-texture depth buffernnn function setupDepthRenderbuffer(renderTarget) {n var renderTargetProperties = properties.get(renderTarget);n var isCube = renderTarget.isWebGLRenderTargetCube === true;nn if (renderTarget.depthTexture) {n if (isCube) throw new Error('target.depthTexture not supported in Cube
render targets');n setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);n } else {n if (isCube) {n renderTargetProperties.__webglDepthbuffer = [];nn for (var i = 0; i < 6; i++) {n _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);nn renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();n setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);n }n } else {n _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);nn renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();n setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);n }n }nn _gl.bindFramebuffer(36160, null);n } // Set up GL resources for the render targetnnn function setupRenderTarget(renderTarget) {n var renderTargetProperties = properties.get(renderTarget);n var textureProperties = properties.get(renderTarget.texture);n renderTarget.addEventListener('dispose', onRenderTargetDispose);n textureProperties.__webglTexture = _gl.createTexture();n info.memory.textures++;n var isCube = renderTarget.isWebGLRenderTargetCube === true;n var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;n var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffernn if (isCube) {n renderTargetProperties.__webglFramebuffer = [];nn for (var i = 0; i < 6; i++) {n renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();n }n } else {n renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();nn if (isMultisample) {n if (capabilities.isWebGL2) {n renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();n renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();nn _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);nn var glFormat = utils.convert(renderTarget.texture.format);n var glType = utils.convert(renderTarget.texture.type);n var glInternalFormat = getInternalFormat(glFormat, glType);n var samples = getRenderTargetSamples(renderTarget);nn _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);nn _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);nn _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);nn _gl.bindRenderbuffer(36161, null);nn if (renderTarget.depthBuffer) {n renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();n setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);n }nn _gl.bindFramebuffer(36160, null);n } else {n console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');n }n }n } // Setup color buffernnn if (isCube) {n state.bindTexture(34067, textureProperties.__webglTexture);n setTextureParameters(34067, renderTarget.texture, supportsMips);nn for (var i = 0; i < 6; i++) {n setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 34069 + i);n }nn if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {n generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);n }nn state.bindTexture(34067, null);n } else {n state.bindTexture(3553, textureProperties.__webglTexture);n setTextureParameters(3553, renderTarget.texture, supportsMips);n setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);nn if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {n generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);n }nn state.bindTexture(3553, null);n } // Setup depth and stencil buffersnnn if (renderTarget.depthBuffer) {n setupDepthRenderbuffer(renderTarget);n }n }nn function updateRenderTargetMipmap(renderTarget) {n var texture = renderTarget.texture;n var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;nn if (textureNeedsGenerateMipmaps(texture, supportsMips)) {n var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;nn var webglTexture = properties.get(texture).__webglTexture;nn state.bindTexture(target, webglTexture);n generateMipmap(target, texture, renderTarget.width, renderTarget.height);n state.bindTexture(target, null);n }n }nn function updateMultisampleRenderTarget(renderTarget) {n if (renderTarget.isWebGLMultisampleRenderTarget) {n if (capabilities.isWebGL2) {n var renderTargetProperties = properties.get(renderTarget);nn _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);nn _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);nn var width = renderTarget.width;n var height = renderTarget.height;n var mask = 16384;n if (renderTarget.depthBuffer) mask |= 256;n if (renderTarget.stencilBuffer) mask |= 1024;nn _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);n } else {n console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');n }n }n }nn function getRenderTargetSamples(renderTarget) {n return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;n }nn function updateVideoTexture(texture) {n var frame = info.render.frame; // Check the last frame we updated the VideoTexturenn if (_videoTextures.get(texture) !== frame) {n _videoTextures.set(texture, frame);nn texture.update();n }n } // backwards compatibilitynnn var warnedTexture2D = false;n var warnedTextureCube = false;nn function safeSetTexture2D(texture, slot) {n if (texture && texture.isWebGLRenderTarget) {n if (warnedTexture2D === false) {n console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");n warnedTexture2D = true;n }nn texture = texture.texture;n }nn setTexture2D(texture, slot);n }nn function safeSetTextureCube(texture, slot) {n if (texture && texture.isWebGLRenderTargetCube) {n if (warnedTextureCube === false) {n console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");n warnedTextureCube = true;n }nn texture = texture.texture;n } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexturen // TODO: unify these code pathsnnn if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {n // CompressedTexture can have Array in image :/n // this function alone should take care of cube texturesn setTextureCube(texture, slot);n } else {n // assumed: texture property of THREE.WebGLRenderTargetCuben setTextureCubeDynamic(texture, slot);n }n } //nnn this.allocateTextureUnit = allocateTextureUnit;n this.resetTextureUnits = resetTextureUnits;n this.setTexture2D = setTexture2D;n this.setTexture2DArray = setTexture2DArray;n this.setTexture3D = setTexture3D;n this.setTextureCube = setTextureCube;n this.setTextureCubeDynamic = setTextureCubeDynamic;n this.setupRenderTarget = setupRenderTarget;n this.updateRenderTargetMipmap = updateRenderTargetMipmap;n this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;n this.safeSetTexture2D = safeSetTexture2D;n this.safeSetTextureCube = safeSetTextureCube;n}n/**n * @author thespite / www.twitter.com/thespiten */nnnfunction WebGLUtils(gl, extensions, capabilities) {n function convert(p) {n var extension;n if (p === RepeatWrapping) return 10497;n if (p === ClampToEdgeWrapping) return 33071;n if (p === MirroredRepeatWrapping) return 33648;n if (p === NearestFilter) return 9728;n if (p === NearestMipmapNearestFilter) return 9984;n if (p === NearestMipmapLinearFilter) return 9986;n if (p === LinearFilter) return 9729;n if (p === LinearMipmapNearestFilter) return 9985;n if (p === LinearMipmapLinearFilter) return 9987;n if (p === UnsignedByteType) return 5121;n if (p === UnsignedShort4444Type) return 32819;n if (p === UnsignedShort5551Type) return 32820;n if (p === UnsignedShort565Type) return 33635;n if (p === ByteType) return 5120;n if (p === ShortType) return 5122;n if (p === UnsignedShortType) return 5123;n if (p === IntType) return 5124;n if (p === UnsignedIntType) return 5125;n if (p === FloatType) return 5126;nn if (p === HalfFloatType) {n if (capabilities.isWebGL2) return 5131;n extension = extensions.get('OES_texture_half_float');n if (extension !== null) return extension.HALF_FLOAT_OES;n }nn if (p === AlphaFormat) return 6406;n if (p === RGBFormat) return 6407;n if (p === RGBAFormat) return 6408;n if (p === LuminanceFormat) return 6409;n if (p === LuminanceAlphaFormat) return 6410;n if (p === DepthFormat) return 6402;n if (p === DepthStencilFormat) return 34041;n if (p === RedFormat) return 6403;n if (p === AddEquation) return 32774;n if (p === SubtractEquation) return 32778;n if (p === ReverseSubtractEquation) return 32779;n if (p === ZeroFactor) return 0;n if (p === OneFactor) return 1;n if (p === SrcColorFactor) return 768;n if (p === OneMinusSrcColorFactor) return 769;n if (p === SrcAlphaFactor) return 770;n if (p === OneMinusSrcAlphaFactor) return 771;n if (p === DstAlphaFactor) return 772;n if (p === OneMinusDstAlphaFactor) return 773;n if (p === DstColorFactor) return 774;n if (p === OneMinusDstColorFactor) return 775;n if (p === SrcAlphaSaturateFactor) return 776;nn if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {n extension = extensions.get('WEBGL_compressed_texture_s3tc');nn if (extension !== null) {n if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;n if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;n if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;n if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;n }n }nn if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {n extension = extensions.get('WEBGL_compressed_texture_pvrtc');nn if (extension !== null) {n if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;n if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;n if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;n if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;n }n }nn if (p === RGB_ETC1_Format) {n extension = extensions.get('WEBGL_compressed_texture_etc1');n if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;n }nn 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) {n extension = extensions.get('WEBGL_compressed_texture_astc');nn if (extension !== null) {n return p;n }n }nn if (p === MinEquation || p === MaxEquation) {n if (capabilities.isWebGL2) {n if (p === MinEquation) return 32775;n if (p === MaxEquation) return 32776;n }nn extension = extensions.get('EXT_blend_minmax');nn if (extension !== null) {n if (p === MinEquation) return extension.MIN_EXT;n if (p === MaxEquation) return extension.MAX_EXT;n }n }nn if (p === UnsignedInt248Type) {n if (capabilities.isWebGL2) return 34042;n extension = extensions.get('WEBGL_depth_texture');n if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;n }nn return 0;n }nn return {n convert: convertn };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction Group() {n Object3D.call(this);n this.type = 'Group';n}nnGroup.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Group,n isGroup: truen});n/**n * @author mrdoob / mrdoob.com/n */nnfunction ArrayCamera(array) {n PerspectiveCamera.call(this);n this.cameras = array || [];n}nnArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {n constructor: ArrayCamera,n isArrayCamera: truen});n/**n * @author jsantell / www.jsantell.com/n * @author mrdoob / mrdoob.com/n */nnvar cameraLPos = new Vector3();nvar cameraRPos = new Vector3();n/**n * Assumes 2 cameras that are parallel and share an X-axis, and thatn * the cameras' projection and world matrices have already been set.n * And that near and far planes are identical for both cameras.n * Visualization
of this technique: computergraphics.stackexchange.com/a/4765n */nnfunction setProjectionFromUnion(camera, cameraL, cameraR) {n cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);n cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);n var ipd = cameraLPos.distanceTo(cameraRPos);n var projL = cameraL.projectionMatrix.elements;n var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, andn // most likely identical top and bottom frustum extents.n // Use the left camera for these values.nn var near = projL / (projL - 1);n var far = projL / (projL + 1);n var topFov = (projL + 1) / projL;n var bottomFov = (projL - 1) / projL;n var leftFov = (projL - 1) / projL;n var rightFov = (projR + 1) / projR;n var left = near * leftFov;n var right = near * rightFov; // Calculate the new camera's position offset from then // left camera. xOffset should be roughly half `ipd`.nn var zOffset = ipd / (-leftFov + rightFov);n var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?nn cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);n camera.translateX(xOffset);n camera.translateZ(zOffset);n camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);n camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scalen // the values so that the near plane's position does not change in world space,n // although must now be relative to the new union camera.nn var near2 = near + zOffset;n var far2 = far + zOffset;n var left2 = left - xOffset;n var right2 = right + (ipd - xOffset);n var top2 = topFov * far / far2 * near2;n var bottom2 = bottomFov * far / far2 * near2;n camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction WebVRManager(renderer) {n var renderWidth, renderHeight;n var scope = this;n var device = null;n var frameData = null;n var poseTarget = null;n var controllers = [];n var standingMatrix = new Matrix4();n var standingMatrixInverse = new Matrix4();n var framebufferScaleFactor = 1.0;n var referenceSpaceType = 'local-floor';nn if (typeof window !== 'undefined' && 'VRFrameData' in window) {n frameData = new window.VRFrameData();n window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);n }nn var matrixWorldInverse = new Matrix4();n var tempQuaternion = new Quaternion();n var tempPosition = new Vector3();n var cameraL = new PerspectiveCamera();n cameraL.viewport = new Vector4();n cameraL.layers.enable(1);n var cameraR = new PerspectiveCamera();n cameraR.viewport = new Vector4();n cameraR.layers.enable(2);n var cameraVR = new ArrayCamera([cameraL, cameraR]);n cameraVR.layers.enable(1);n cameraVR.layers.enable(2); //nn function isPresenting() {n return device !== null && device.isPresenting === true;n }nn var currentSize = new Vector2(),n currentPixelRatio;nn function onVRDisplayPresentChange() {n if (isPresenting()) {n var eyeParameters = device.getEyeParameters('left');n renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;n renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;n currentPixelRatio = renderer.getPixelRatio();n renderer.getSize(currentSize);n renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);n cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);n cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);n animation.start();n scope.dispatchEvent({n type: 'sessionstart'n });n } else {n if (scope.enabled) {n renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);n }nn animation.stop();n scope.dispatchEvent({n type: 'sessionend'n });n }n } //nnn var triggers = [];nn function findGamepad(id) {n var gamepads = navigator.getGamepads && navigator.getGamepads();nn for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {n var gamepad = gamepads;nn if (gamepad && (gamepad.id === 'Daydream Controller' || gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' || gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith('Oculus Touch') || gamepad.id.startsWith('HTC Vive Focus') || gamepad.id.startsWith('Spatial Controller'))) {n if (j === id) return gamepad;n j++;n }n }n }nn function updateControllers() {n for (var i = 0; i < controllers.length; i++) {n var controller = controllers;n var gamepad = findGamepad(i);nn if (gamepad !== undefined && gamepad.pose !== undefined) {n if (gamepad.pose === null) return; // Posenn var pose = gamepad.pose;n if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);n if (pose.position !== null) controller.position.fromArray(pose.position);n if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);n controller.matrix.compose(controller.position, controller.quaternion, controller.scale);n controller.matrix.premultiply(standingMatrix);n controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);n controller.matrixWorldNeedsUpdate = true;n controller.visible = true; // Triggernn var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;n if (triggers === undefined) triggers = false;nn if (triggers !== gamepad.buttons.pressed) {n triggers = gamepad.buttons.pressed;nn if (triggers === true) {n controller.dispatchEvent({n type: 'selectstart'n });n } else {n controller.dispatchEvent({n type: 'selectend'n });n controller.dispatchEvent({n type: 'select'n });n }n }n } else {n controller.visible = false;n }n }n }nn function updateViewportFromBounds(viewport, bounds) {n if (bounds !== null && bounds.length === 4) {n viewport.set(bounds * renderWidth, bounds * renderHeight, bounds * renderWidth, bounds * renderHeight);n }n } //nnn this.enabled = false;nn this.getController = function (id) {n var controller = controllers;nn if (controller === undefined) {n controller = new Group();n controller.matrixAutoUpdate = false;n controller.visible = false;n controllers = controller;n }nn return controller;n };nn this.getDevice = function () {n return device;n };nn this.setDevice = function (value) {n if (value !== undefined) device = value;n animation.setContext(value);n };nn this.setFramebufferScaleFactor = function (value) {n framebufferScaleFactor = value;n };nn this.setReferenceSpaceType = function (value) {n referenceSpaceType = value;n };nn this.setPoseTarget = function (object) {n if (object !== undefined) poseTarget = object;n };nn this.getCamera = function (camera) {n var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;nn if (isPresenting() === false) {n camera.position.set(0, userHeight, 0);n camera.rotation.set(0, 0, 0);n return camera;n }nn device.depthNear = camera.near;n device.depthFar = camera.far;n device.getFrameData(frameData); //nn if (referenceSpaceType === 'local-floor') {n var stageParameters = device.stageParameters;nn if (stageParameters) {n standingMatrix.fromArray(stageParameters.sittingToStandingTransform);n } else {n standingMatrix.makeTranslation(0, userHeight, 0);n }n }nn var pose = frameData.pose;n var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.nn poseObject.matrix.copy(standingMatrix);n poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);nn if (pose.orientation !== null) {n tempQuaternion.fromArray(pose.orientation);n poseObject.quaternion.multiply(tempQuaternion);n }nn if (pose.position !== null) {n tempQuaternion.setFromRotationMatrix(standingMatrix);n tempPosition.fromArray(pose.position);n tempPosition.applyQuaternion(tempQuaternion);n poseObject.position.add(tempPosition);n }nn poseObject.updateMatrixWorld(); //nn cameraL.near = camera.near;n cameraR.near = camera.near;n cameraL.far = camera.far;n cameraR.far = camera.far;n cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);n cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this codenn standingMatrixInverse.getInverse(standingMatrix);nn if (referenceSpaceType === 'local-floor') {n cameraL.matrixWorldInverse.multiply(standingMatrixInverse);n cameraR.matrixWorldInverse.multiply(standingMatrixInverse);n }nn var parent = poseObject.parent;nn if (parent !== null) {n matrixWorldInverse.getInverse(parent.matrixWorld);n cameraL.matrixWorldInverse.multiply(matrixWorldInverse);n cameraR.matrixWorldInverse.multiply(matrixWorldInverse);n } // envMap and Mirror needs camera.matrixWorldnnn cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);n cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);n cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);n cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);n setProjectionFromUnion(cameraVR, cameraL, cameraR); //nn var layers = device.getLayers();nn if (layers.length) {n var layer = layers;n updateViewportFromBounds(cameraL.viewport, layer.leftBounds);n updateViewportFromBounds(cameraR.viewport, layer.rightBounds);n }nn updateControllers();n return cameraVR;n };nn this.getStandingMatrix = function () {n return standingMatrix;n };nn this.isPresenting = isPresenting; // Animation Loopnn var animation = new WebGLAnimation();nn this.setAnimationLoop = function (callback) {n animation.setAnimationLoop(callback);n if (isPresenting()) animation.start();n };nn this.submitFrame = function () {n if (isPresenting()) device.submitFrame();n };nn this.dispose = function () {n if (typeof window !== 'undefined') {n window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);n }n }; // DEPRECATEDnnn this.setFrameOfReferenceType = function () {n console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');n };n}nnObject.assign(WebVRManager.prototype, EventDispatcher.prototype);n/**n * @author mrdoob / mrdoob.com/n */nnfunction WebXRManager(renderer, gl) {n var scope = this;n var session = null;n var referenceSpace = null;n var referenceSpaceType = 'local-floor';n var pose = null;n var controllers = [];n var inputSources = [];nn function isPresenting() {n return session !== null && referenceSpace !== null;n } //nnn var cameraL = new PerspectiveCamera();n cameraL.layers.enable(1);n cameraL.viewport = new Vector4();n var cameraR = new PerspectiveCamera();n cameraR.layers.enable(2);n cameraR.viewport = new Vector4();n var cameraVR = new ArrayCamera([cameraL, cameraR]);n cameraVR.layers.enable(1);n cameraVR.layers.enable(2); //nn this.enabled = false;nn this.getController = function (id) {n var controller = controllers;nn if (controller === undefined) {n controller = new Group();n controller.matrixAutoUpdate = false;n controller.visible = false;n controllers = controller;n }nn return controller;n }; //nnn function onSessionEvent(event) {n for (var i = 0; i < controllers.length; i++) {n if (inputSources === event.inputSource) {n controllers.dispatchEvent({n type: event.typen });n }n }n }nn function onSessionEnd() {n renderer.setFramebuffer(null);n renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830nn animation.stop();n scope.dispatchEvent({n type: 'sessionend'n });n }nn function onRequestReferenceSpace(value) {n referenceSpace = value;n animation.setContext(session);n animation.start();n scope.dispatchEvent({n type: 'sessionstart'n });n }nn this.setFramebufferScaleFactor = function (value) {};nn this.setReferenceSpaceType = function (value) {n referenceSpaceType = value;n };nn this.getSession = function () {n return session;n };nn this.setSession = function (value) {n session = value;nn if (session !== null) {n session.addEventListener('select', onSessionEvent);n session.addEventListener('selectstart', onSessionEvent);n session.addEventListener('selectend', onSessionEvent);n session.addEventListener('end', onSessionEnd);n session.updateRenderState({n baseLayer: new XRWebGLLayer(session, gl)n });n session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //nn inputSources = session.inputSources;n session.addEventListener('inputsourceschange', function () {n inputSources = session.inputSources;n console.log(inputSources);nn for (var i = 0; i < controllers.length; i++) {n var controller = controllers;n controller.userData.inputSource = inputSources;n }n });n }n };nn function updateCamera(camera, parent) {n if (parent === null) {n camera.matrixWorld.copy(camera.matrix);n } else {n camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);n }nn camera.matrixWorldInverse.getInverse(camera.matrixWorld);n }nn this.getCamera = function (camera) {n if (isPresenting()) {n var parent = camera.parent;n var cameras = cameraVR.cameras;n updateCamera(cameraVR, parent);nn for (var i = 0; i < cameras.length; i++) {n updateCamera(cameras, parent);n } // update camera and its childrennnn camera.matrixWorld.copy(cameraVR.matrixWorld);n var children = camera.children;nn for (var i = 0, l = children.length; i < l; i++) {n children.updateMatrixWorld(true);n }nn setProjectionFromUnion(cameraVR, cameraL, cameraR);n return cameraVR;n }nn return camera;n };nn this.isPresenting = isPresenting; // Animation Loopnn var onAnimationFrameCallback = null;nn function onAnimationFrame(time, frame) {n pose = frame.getViewerPose(referenceSpace);nn if (pose !== null) {n var views = pose.views;n var baseLayer = session.renderState.baseLayer;n renderer.setFramebuffer(baseLayer.framebuffer);nn for (var i = 0; i < views.length; i++) {n var view = views;n var viewport = baseLayer.getViewport(view);n var viewMatrix = view.transform.inverse.matrix;n var camera = cameraVR.cameras;n camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);n camera.projectionMatrix.fromArray(view.projectionMatrix);n camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);nn if (i === 0) {n cameraVR.matrix.copy(camera.matrix);n }n }n } //nnn for (var i = 0; i < controllers.length; i++) {n var controller = controllers;n var inputSource = inputSources;nn if (inputSource) {n var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);nn if (inputPose !== null) {n controller.matrix.fromArray(inputPose.transform.matrix);n controller.matrix.decompose(controller.position, controller.rotation, controller.scale);n controller.visible = true;n continue;n }n }nn controller.visible = false;n }nn if (onAnimationFrameCallback) onAnimationFrameCallback(time);n }nn var animation = new WebGLAnimation();n animation.setAnimationLoop(onAnimationFrame);nn this.setAnimationLoop = function (callback) {n onAnimationFrameCallback = callback;n };nn this.dispose = function () {}; // DEPRECATEDnnn this.getStandingMatrix = function () {n console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');n return new Matrix4();n };nn this.getDevice = function () {n console.warn('THREE.WebXRManager: getDevice() has been deprecated.');n };nn this.setDevice = function () {n console.warn('THREE.WebXRManager: setDevice() has been deprecated.');n };nn this.setFrameOfReferenceType = function () {n console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');n };nn this.submitFrame = function () {};n}nnObject.assign(WebXRManager.prototype, EventDispatcher.prototype);n/**n * @author supereggbert / www.paulbrunt.co.uk/n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n * @author szimek / github.com/szimek/n * @author tschwn */nnfunction WebGLRenderer(parameters) {n parameters = parameters || {};nn var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('www.w3.org/1999/xhtml', 'canvas'),n _context = parameters.context !== undefined ? parameters.context : null,n _alpha = parameters.alpha !== undefined ? parameters.alpha : false,n _depth = parameters.depth !== undefined ? parameters.depth : true,n _stencil = parameters.stencil !== undefined ? parameters.stencil : true,n _antialias = parameters.antialias !== undefined ? parameters.antialias : false,n _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,n _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,n _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',n _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;nn var currentRenderList = null;n var currentRenderState = null; // public propertiesnn this.domElement = _canvas; // Debug configuration containernn this.debug = {n /**n * Enables error checking and reporting when shader programs are being compiledn * @type {boolean}n */n checkShaderErrors: truen }; // clearingnn this.autoClear = true;n this.autoClearColor = true;n this.autoClearDepth = true;n this.autoClearStencil = true; // scene graphnn this.sortObjects = true; // user-defined clippingnn this.clippingPlanes = [];n this.localClippingEnabled = false; // physically based shadingnn this.gammaFactor = 2.0; // for backwards compatibilitynn this.gammaInput = false;n this.gammaOutput = false; // physical lightsnn this.physicallyCorrectLights = false; // tone mappingnn this.toneMapping = LinearToneMapping;n this.toneMappingExposure = 1.0;n this.toneMappingWhitePoint = 1.0; // morphsnn this.maxMorphTargets = 8;n this.maxMorphNormals = 4; // internal propertiesnn var _this = this,n _isContextLost = false,n // internal state cachen _framebuffer = null,n _currentActiveCubeFace = 0,n _currentActiveMipmapLevel = 0,n _currentRenderTarget = null,n _currentFramebuffer = null,n _currentMaterialId = -1,n // geometry and program cachingn _currentGeometryProgram = {n geometry: null,n program: null,n wireframe: falsen },n _currentCamera = null,n _currentArrayCamera = null,n _currentViewport = new Vector4(),n _currentScissor = new Vector4(),n _currentScissorTest = null,n //n _width = _canvas.width,n _height = _canvas.height,n _pixelRatio = 1,n _viewport = new Vector4(0, 0, _width, _height),n _scissor = new Vector4(0, 0, _width, _height),n _scissorTest = false,n // frustumn _frustum = new Frustum(),n // clippingn _clipping = new WebGLClipping(),n _clippingEnabled = false,n _localClippingEnabled = false,n // camera matrices cachen _projScreenMatrix = new Matrix4(),n _vector3 = new Vector3();nn function getTargetPixelRatio() {n return _currentRenderTarget === null ? _pixelRatio : 1;n } // initializennn var _gl;nn try {n var contextAttributes = {n alpha: _alpha,n depth: _depth,n stencil: _stencil,n antialias: _antialias,n premultipliedAlpha: _premultipliedAlpha,n preserveDrawingBuffer: _preserveDrawingBuffer,n powerPreference: _powerPreference,n failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,n xrCompatible: truen }; // event listeners must be registered before WebGL context is created, see #12753nn _canvas.addEventListener('webglcontextlost', onContextLost, false);nn _canvas.addEventListener('webglcontextrestored', onContextRestore, false);nn _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);nn if (_gl === null) {n if (_canvas.getContext('webgl') !== null) {n throw new Error('Error creating WebGL context with your selected attributes.');n } else {n throw new Error('Error creating WebGL context.');n }n } // Some experimental-webgl implementations do not have getShaderPrecisionFormatnnn if (_gl.getShaderPrecisionFormat === undefined) {n _gl.getShaderPrecisionFormat = function () {n return {n 'rangeMin': 1,n 'rangeMax': 1,n 'precision': 1n };n };n }n } catch (error) {n console.error('THREE.WebGLRenderer: ' + error.message);n throw error;n }nn var extensions, capabilities, state, info;n var properties, textures, attributes, geometries, objects;n var programCache, renderLists, renderStates;n var background, morphtargets, bufferRenderer, indexedBufferRenderer;n var utils;nn function initGLContext() {n extensions = new WebGLExtensions(_gl);n capabilities = new WebGLCapabilities(_gl, extensions, parameters);nn if (!capabilities.isWebGL2) {n extensions.get('WEBGL_depth_texture');n extensions.get('OES_texture_float');n extensions.get('OES_texture_half_float');n extensions.get('OES_texture_half_float_linear');n extensions.get('OES_standard_derivatives');n extensions.get('OES_element_index_uint');n extensions.get('ANGLE_instanced_arrays');n }nn extensions.get('OES_texture_float_linear');n utils = new WebGLUtils(_gl, extensions, capabilities);n state = new WebGLState(_gl, extensions, utils, capabilities);n state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());n state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());n info = new WebGLInfo(_gl);n properties = new WebGLProperties();n textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);n attributes = new WebGLAttributes(_gl);n geometries = new WebGLGeometries(_gl, attributes, info);n objects = new WebGLObjects(geometries, info);n morphtargets = new WebGLMorphtargets(_gl);n programCache = new WebGLPrograms(_this, extensions, capabilities);n renderLists = new WebGLRenderLists();n renderStates = new WebGLRenderStates();n background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);n bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);n indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);n info.programs = programCache.programs;n _this.capabilities = capabilities;n _this.extensions = extensions;n _this.properties = properties;n _this.renderLists = renderLists;n _this.state = state;n _this.info = info;n }nn initGLContext(); // vrnn var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);n this.vr = vr; // shadow mapnn var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);n this.shadowMap = shadowMap; // APInn this.getContext = function () {n return _gl;n };nn this.getContextAttributes = function () {n return _gl.getContextAttributes();n };nn this.forceContextLoss = function () {n var extension = extensions.get('WEBGL_lose_context');n if (extension) extension.loseContext();n };nn this.forceContextRestore = function () {n var extension = extensions.get('WEBGL_lose_context');n if (extension) extension.restoreContext();n };nn this.getPixelRatio = function () {n return _pixelRatio;n };nn this.setPixelRatio = function (value) {n if (value === undefined) return;n _pixelRatio = value;n this.setSize(_width, _height, false);n };nn this.getSize = function (target) {n if (target === undefined) {n console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');n target = new Vector2();n }nn return target.set(_width, _height);n };nn this.setSize = function (width, height, updateStyle) {n if (vr.isPresenting()) {n console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');n return;n }nn _width = width;n _height = height;n _canvas.width = Math.floor(width * _pixelRatio);n _canvas.height = Math.floor(height * _pixelRatio);nn if (updateStyle !== false) {n _canvas.style.width = width + 'px';n _canvas.style.height = height + 'px';n }nn this.setViewport(0, 0, width, height);n };nn this.getDrawingBufferSize = function (target) {n if (target === undefined) {n console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');n target = new Vector2();n }nn return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();n };nn this.setDrawingBufferSize = function (width, height, pixelRatio) {n _width = width;n _height = height;n _pixelRatio = pixelRatio;n _canvas.width = Math.floor(width * pixelRatio);n _canvas.height = Math.floor(height * pixelRatio);n this.setViewport(0, 0, width, height);n };nn this.getCurrentViewport = function (target) {n if (target === undefined) {n console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');n target = new Vector4();n }nn return target.copy(_currentViewport);n };nn this.getViewport = function (target) {n return target.copy(_viewport);n };nn this.setViewport = function (x, y, width, height) {n if (x.isVector4) {n _viewport.set(x.x, x.y, x.z, x.w);n } else {n _viewport.set(x, y, width, height);n }nn state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());n };nn this.getScissor = function (target) {n return target.copy(_scissor);n };nn this.setScissor = function (x, y, width, height) {n if (x.isVector4) {n _scissor.set(x.x, x.y, x.z, x.w);n } else {n _scissor.set(x, y, width, height);n }nn state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());n };nn this.getScissorTest = function () {n return _scissorTest;n };nn this.setScissorTest = function (_boolean) {n state.setScissorTest(_scissorTest = _boolean);n }; // Clearingnnn this.getClearColor = function () {n return background.getClearColor();n };nn this.setClearColor = function () {n background.setClearColor.apply(background, arguments);n };nn this.getClearAlpha = function () {n return background.getClearAlpha();n };nn this.setClearAlpha = function () {n background.setClearAlpha.apply(background, arguments);n };nn this.clear = function (color, depth, stencil) {n var bits = 0;n if (color === undefined || color) bits |= 16384;n if (depth === undefined || depth) bits |= 256;n if (stencil === undefined || stencil) bits |= 1024;nn _gl.clear(bits);n };nn this.clearColor = function () {n this.clear(true, false, false);n };nn this.clearDepth = function () {n this.clear(false, true, false);n };nn this.clearStencil = function () {n this.clear(false, false, true);n }; //nnn this.dispose = function () {n _canvas.removeEventListener('webglcontextlost', onContextLost, false);nn _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);nn renderLists.dispose();n renderStates.dispose();n properties.dispose();n objects.dispose();n vr.dispose();n animation.stop();n }; // Eventsnnn function onContextLost(event) {n event.preventDefault();n console.log('THREE.WebGLRenderer: Context Lost.');n _isContextLost = true;n }nn function onContextRestore()n /* event */n {n console.log('THREE.WebGLRenderer: Context Restored.');n _isContextLost = false;n initGLContext();n }nn function onMaterialDispose(event) {n var material = event.target;n material.removeEventListener('dispose', onMaterialDispose);n deallocateMaterial(material);n } // Buffer deallocationnnn function deallocateMaterial(material) {n releaseMaterialProgramReference(material);n properties.remove(material);n }nn function releaseMaterialProgramReference(material) {n var programInfo = properties.get(material).program;n material.program = undefined;nn if (programInfo !== undefined) {n programCache.releaseProgram(programInfo);n }n } // Buffer renderingnnn function renderObjectImmediate(object, program) {n object.render(function (object) {n _this.renderBufferImmediate(object, program);n });n }nn this.renderBufferImmediate = function (object, program) {n state.initAttributes();n var buffers = properties.get(object);n if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();n if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();n if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();n if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();n var programAttributes = program.getAttributes();nn if (object.hasPositions) {n _gl.bindBuffer(34962, buffers.position);nn _gl.bufferData(34962, object.positionArray, 35048);nn state.enableAttribute(programAttributes.position);nn _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);n }nn if (object.hasNormals) {n _gl.bindBuffer(34962, buffers.normal);nn _gl.bufferData(34962, object.normalArray, 35048);nn state.enableAttribute(programAttributes.normal);nn _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);n }nn if (object.hasUvs) {n _gl.bindBuffer(34962, buffers.uv);nn _gl.bufferData(34962, object.uvArray, 35048);nn state.enableAttribute(programAttributes.uv);nn _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);n }nn if (object.hasColors) {n _gl.bindBuffer(34962, buffers.color);nn _gl.bufferData(34962, object.colorArray, 35048);nn state.enableAttribute(programAttributes.color);nn _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);n }nn state.disableUnusedAttributes();nn _gl.drawArrays(4, 0, object.count);nn object.count = 0;n };nn this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {n var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;n state.setMaterial(material, frontFaceCW);n var program = setProgram(camera, fog, material, object);n var updateBuffers = false;nn if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {n _currentGeometryProgram.geometry = geometry.id;n _currentGeometryProgram.program = program.id;n _currentGeometryProgram.wireframe = material.wireframe === true;n updateBuffers = true;n }nn if (object.morphTargetInfluences) {n morphtargets.update(object, geometry, material, program);n updateBuffers = true;n } //nnn var index = geometry.index;n var position = geometry.attributes.position;n var rangeFactor = 1;nn if (material.wireframe === true) {n index = geometries.getWireframeAttribute(geometry);n rangeFactor = 2;n }nn var attribute;n var renderer = bufferRenderer;nn if (index !== null) {n attribute = attributes.get(index);n renderer = indexedBufferRenderer;n renderer.setIndex(attribute);n }nn if (updateBuffers) {n setupVertexAttributes(material, program, geometry);nn if (index !== null) {n _gl.bindBuffer(34963, attribute.buffer);n }n } //nnn var dataCount = Infinity;nn if (index !== null) {n dataCount = index.count;n } else if (position !== undefined) {n dataCount = position.count;n }nn var rangeStart = geometry.drawRange.start * rangeFactor;n var rangeCount = geometry.drawRange.count * rangeFactor;n var groupStart = group !== null ? group.start * rangeFactor : 0;n var groupCount = group !== null ? group.count * rangeFactor : Infinity;n var drawStart = Math.max(rangeStart, groupStart);n var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;n var drawCount = Math.max(0, drawEnd - drawStart + 1);n if (drawCount === 0) return; //nn if (object.isMesh) {n if (material.wireframe === true) {n state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());n renderer.setMode(1);n } else {n switch (object.drawMode) {n case TrianglesDrawMode:n renderer.setMode(4);n break;nn case TriangleStripDrawMode:n renderer.setMode(5);n break;nn case TriangleFanDrawMode:n renderer.setMode(6);n break;n }n }n } else if (object.isLine) {n var lineWidth = material.linewidth;n if (lineWidth === undefined) lineWidth = 1; // Not using Line*Materialnn state.setLineWidth(lineWidth * getTargetPixelRatio());nn if (object.isLineSegments) {n renderer.setMode(1);n } else if (object.isLineLoop) {n renderer.setMode(2);n } else {n renderer.setMode(3);n }n } else if (object.isPoints) {n renderer.setMode(0);n } else if (object.isSprite) {n renderer.setMode(4);n }nn if (geometry && geometry.isInstancedBufferGeometry) {n if (geometry.maxInstancedCount > 0) {n renderer.renderInstances(geometry, drawStart, drawCount);n }n } else {n renderer.render(drawStart, drawCount);n }n };nn function setupVertexAttributes(material, program, geometry) {n if (geometry && geometry.isInstancedBufferGeometry && !capabilities.isWebGL2) {n if (extensions.get('ANGLE_instanced_arrays') === null) {n console.error('THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');n return;n }n }nn state.initAttributes();n var geometryAttributes = geometry.attributes;n var programAttributes = program.getAttributes();n var materialDefaultAttributeValues = material.defaultAttributeValues;nn for (var name in programAttributes) {n var programAttribute = programAttributes;nn if (programAttribute >= 0) {n var geometryAttribute = geometryAttributes;nn if (geometryAttribute !== undefined) {n var normalized = geometryAttribute.normalized;n var size = geometryAttribute.itemSize;n var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restorenn if (attribute === undefined) continue;n var buffer = attribute.buffer;n var type = attribute.type;n var bytesPerElement = attribute.bytesPerElement;nn if (geometryAttribute.isInterleavedBufferAttribute) {n var data = geometryAttribute.data;n var stride = data.stride;n var offset = geometryAttribute.offset;nn if (data && data.isInstancedInterleavedBuffer) {n state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);nn if (geometry.maxInstancedCount === undefined) {n geometry.maxInstancedCount = data.meshPerAttribute * data.count;n }n } else {n state.enableAttribute(programAttribute);n }nn _gl.bindBuffer(34962, buffer);nn _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);n } else {n if (geometryAttribute.isInstancedBufferAttribute) {n state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);nn if (geometry.maxInstancedCount === undefined) {n geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;n }n } else {n state.enableAttribute(programAttribute);n }nn _gl.bindBuffer(34962, buffer);nn _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);n }n } else if (materialDefaultAttributeValues !== undefined) {n var value = materialDefaultAttributeValues;nn if (value !== undefined) {n switch (value.length) {n case 2:n _gl.vertexAttrib2fv(programAttribute, value);nn break;nn case 3:n _gl.vertexAttrib3fv(programAttribute, value);nn break;nn case 4:n _gl.vertexAttrib4fv(programAttribute, value);nn break;nn default:n _gl.vertexAttrib1fv(programAttribute, value);nn }n }n }n }n }nn state.disableUnusedAttributes();n } // Compilennn this.compile = function (scene, camera) {n currentRenderState = renderStates.get(scene, camera);n currentRenderState.init();n scene.traverse(function (object) {n if (object.isLight) {n currentRenderState.pushLight(object);nn if (object.castShadow) {n currentRenderState.pushShadow(object);n }n }n });n currentRenderState.setupLights(camera);n scene.traverse(function (object) {n if (object.material) {n if (Array.isArray(object.material)) {n for (var i = 0; i < object.material.length; i++) {n initMaterial(object.material, scene.fog, object);n }n } else {n initMaterial(object.material, scene.fog, object);n }n }n });n }; // Animation Loopnnn var onAnimationFrameCallback = null;nn function onAnimationFrame(time) {n if (vr.isPresenting()) return;n if (onAnimationFrameCallback) onAnimationFrameCallback(time);n }nn var animation = new WebGLAnimation();n animation.setAnimationLoop(onAnimationFrame);n if (typeof window !== 'undefined') animation.setContext(window);nn this.setAnimationLoop = function (callback) {n onAnimationFrameCallback = callback;n vr.setAnimationLoop(callback);n animation.start();n }; // Renderingnnn this.render = function (scene, camera) {n var renderTarget, forceClear;nn if (arguments !== undefined) {n console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');n renderTarget = arguments;n }nn if (arguments !== undefined) {n console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');n forceClear = arguments;n }nn if (!(camera && camera.isCamera)) {n console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');n return;n }nn if (_isContextLost) return; // reset caching for this framenn _currentGeometryProgram.geometry = null;n _currentGeometryProgram.program = null;n _currentGeometryProgram.wireframe = false;n _currentMaterialId = -1;n _currentCamera = null; // update scene graphnn if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustumnn if (camera.parent === null) camera.updateMatrixWorld();nn if (vr.enabled) {n camera = vr.getCamera(camera);n } //nnn currentRenderState = renderStates.get(scene, camera);n currentRenderState.init();n scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);nn _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);nn _frustum.setFromMatrix(_projScreenMatrix);nn _localClippingEnabled = this.localClippingEnabled;n _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);n currentRenderList = renderLists.get(scene, camera);n currentRenderList.init();n projectObject(scene, camera, 0, _this.sortObjects);nn if (_this.sortObjects === true) {n currentRenderList.sort();n } //nnn if (_clippingEnabled) _clipping.beginShadows();n var shadowsArray = currentRenderState.state.shadowsArray;n shadowMap.render(shadowsArray, scene, camera);n currentRenderState.setupLights(camera);n if (_clippingEnabled) _clipping.endShadows(); //nn if (this.info.autoReset) this.info.reset();nn if (renderTarget !== undefined) {n this.setRenderTarget(renderTarget);n } //nnn background.render(currentRenderList, scene, camera, forceClear); // render scenenn var opaqueObjects = currentRenderList.opaque;n var transparentObjects = currentRenderList.transparent;nn if (scene.overrideMaterial) {n var overrideMaterial = scene.overrideMaterial;n if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);n if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);n } else {n // opaque pass (front-to-back order)n if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)nn if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);n } //nnn scene.onAfterRender(_this, scene, camera); //nn if (_currentRenderTarget !== null) {n // Generate mipmap if we're using any kind of mipmap filteringn textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessarynn textures.updateMultisampleRenderTarget(_currentRenderTarget);n } // Ensure depth buffer writing is enabled so it can be cleared on next rendernnn state.buffers.depth.setTest(true);n state.buffers.depth.setMask(true);n state.buffers.color.setMask(true);n state.setPolygonOffset(false);nn if (vr.enabled) {n vr.submitFrame();n } // _gl.finish();nnn currentRenderList = null;n currentRenderState = null;n };nn function projectObject(object, camera, groupOrder, sortObjects) {n if (object.visible === false) return;n var visible = object.layers.test(camera.layers);nn if (visible) {n if (object.isGroup) {n groupOrder = object.renderOrder;n } else if (object.isLOD) {n if (object.autoUpdate === true) object.update(camera);n } else if (object.isLight) {n currentRenderState.pushLight(object);nn if (object.castShadow) {n currentRenderState.pushShadow(object);n }n } else if (object.isSprite) {n if (!object.frustumCulled || _frustum.intersectsSprite(object)) {n if (sortObjects) {n _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);n }nn var geometry = objects.update(object);n var material = object.material;nn if (material.visible) {n currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);n }n }n } else if (object.isImmediateRenderObject) {n if (sortObjects) {n _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);n }nn currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);n } else if (object.isMesh || object.isLine || object.isPoints) {n if (object.isSkinnedMesh) {n object.skeleton.update();n }nn if (!object.frustumCulled || _frustum.intersectsObject(object)) {n if (sortObjects) {n _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);n }nn var geometry = objects.update(object);n var material = object.material;nn if (Array.isArray(material)) {n var groups = geometry.groups;nn for (var i = 0, l = groups.length; i < l; i++) {n var group = groups;n var groupMaterial = material;nn if (groupMaterial && groupMaterial.visible) {n currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);n }n }n } else if (material.visible) {n currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);n }n }n }n }nn var children = object.children;nn for (var i = 0, l = children.length; i < l; i++) {n projectObject(children, camera, groupOrder, sortObjects);n }n }nn function renderObjects(renderList, scene, camera, overrideMaterial) {n for (var i = 0, l = renderList.length; i < l; i++) {n var renderItem = renderList;n var object = renderItem.object;n var geometry = renderItem.geometry;n var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;n var group = renderItem.group;nn if (camera.isArrayCamera) {n _currentArrayCamera = camera;n var cameras = camera.cameras;nn for (var j = 0, jl = cameras.length; j < jl; j++) {n var camera2 = cameras;nn if (object.layers.test(camera2.layers)) {n state.viewport(_currentViewport.copy(camera2.viewport));n currentRenderState.setupLights(camera2);n renderObject(object, scene, camera2, geometry, material, group);n }n }n } else {n _currentArrayCamera = null;n renderObject(object, scene, camera, geometry, material, group);n }n }n }nn function renderObject(object, scene, camera, geometry, material, group) {n object.onBeforeRender(_this, scene, camera, geometry, material, group);n currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);n object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);n object.normalMatrix.getNormalMatrix(object.modelViewMatrix);nn if (object.isImmediateRenderObject) {n state.setMaterial(material);n var program = setProgram(camera, scene.fog, material, object);n _currentGeometryProgram.geometry = null;n _currentGeometryProgram.program = null;n _currentGeometryProgram.wireframe = false;n renderObjectImmediate(object, program);n } else {n _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);n }nn object.onAfterRender(_this, scene, camera, geometry, material, group);n currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);n }nn function initMaterial(material, fog, object) {n var materialProperties = properties.get(material);n var lights = currentRenderState.state.lights;n var shadowsArray = currentRenderState.state.shadowsArray;n var lightsStateVersion = lights.state.version;n var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);n var code = programCache.getProgramCode(material, parameters);n var program = materialProperties.program;n var programChange = true;nn if (program === undefined) {n // new materialn material.addEventListener('dispose', onMaterialDispose);n } else if (program.code !== code) {n // changed glsl or parametersn releaseMaterialProgramReference(material);n } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {n materialProperties.lightsStateVersion = lightsStateVersion;n programChange = false;n } else if (parameters.shaderID !== undefined) {n // same glsl and uniform listn return;n } else {n // only rebuild uniform listn programChange = false;n }nn if (programChange) {n if (parameters.shaderID) {n var shader = ShaderLib;n materialProperties.shader = {n name: material.type,n uniforms: cloneUniforms(shader.uniforms),n vertexShader: shader.vertexShader,n fragmentShader: shader.fragmentShadern };n } else {n materialProperties.shader = {n name: material.type,n uniforms: material.uniforms,n vertexShader: material.vertexShader,n fragmentShader: material.fragmentShadern };n }nn material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shadersnn code = programCache.getProgramCode(material, parameters);n program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);n materialProperties.program = program;n material.program = program;n }nn var programAttributes = program.getAttributes();nn if (material.morphTargets) {n material.numSupportedMorphTargets = 0;nn for (var i = 0; i < _this.maxMorphTargets; i++) {n if (programAttributes['morphTarget' + i] >= 0) {n material.numSupportedMorphTargets++;n }n }n }nn if (material.morphNormals) {n material.numSupportedMorphNormals = 0;nn for (var i = 0; i < _this.maxMorphNormals; i++) {n if (programAttributes['morphNormal' + i] >= 0) {n material.numSupportedMorphNormals++;n }n }n }nn var uniforms = materialProperties.shader.uniforms;nn if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {n materialProperties.numClippingPlanes = _clipping.numPlanes;n materialProperties.numIntersection = _clipping.numIntersection;n uniforms.clippingPlanes = _clipping.uniform;n }nn materialProperties.fog = fog; // store the light setup it was created fornn materialProperties.lightsStateVersion = lightsStateVersion;nn if (material.lights) {n // wire up the material to this renderer's lighting staten uniforms.ambientLightColor.value = lights.state.ambient;n uniforms.lightProbe.value = lights.state.probe;n uniforms.directionalLights.value = lights.state.directional;n uniforms.spotLights.value = lights.state.spot;n uniforms.rectAreaLights.value = lights.state.rectArea;n uniforms.pointLights.value = lights.state.point;n uniforms.hemisphereLights.value = lights.state.hemi;n uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;n uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;n uniforms.spotShadowMap.value = lights.state.spotShadowMap;n uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;n uniforms.pointShadowMap.value = lights.state.pointShadowMap;n uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniformsn }nn var progUniforms = materialProperties.program.getUniforms(),n uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);n materialProperties.uniformsList = uniformsList;n }nn function setProgram(camera, fog, material, object) {n textures.resetTextureUnits();n var materialProperties = properties.get(material);n var lights = currentRenderState.state.lights;nn if (_clippingEnabled) {n if (_localClippingEnabled || camera !== _currentCamera) {n var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroupn // object instead of the material, once it becomes feasiblen // (#8465, #8379)nn _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);n }n }nn if (material.needsUpdate === false) {n if (materialProperties.program === undefined) {n material.needsUpdate = true;n } else if (material.fog && materialProperties.fog !== fog) {n material.needsUpdate = true;n } else if (material.lights && materialProperties.lightsStateVersion !== lights.state.version) {n material.needsUpdate = true;n } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {n material.needsUpdate = true;n }n }nn if (material.needsUpdate) {n initMaterial(material, fog, object);n material.needsUpdate = false;n }nn var refreshProgram = false;n var refreshMaterial = false;n var refreshLights = false;n var program = materialProperties.program,n p_uniforms = program.getUniforms(),n m_uniforms = materialProperties.shader.uniforms;nn if (state.useProgram(program.program)) {n refreshProgram = true;n refreshMaterial = true;n refreshLights = true;n }nn if (material.id !== _currentMaterialId) {n _currentMaterialId = material.id;n refreshMaterial = true;n }nn if (refreshProgram || _currentCamera !== camera) {n p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);nn if (capabilities.logarithmicDepthBuffer) {n p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));n }nn if (_currentCamera !== camera) {n _currentCamera = camera; // lighting uniforms depend on the camera so enforce an updaten // now, in case this material supports lights - or later, whenn // the next material that does gets activated:nn refreshMaterial = true; // set to true on material changenn refreshLights = true; // remains set until update donen } // load material specific uniformsn // (shader material also gets them for the sake of genericity)nnn if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {n var uCamPos = p_uniforms.map.cameraPosition;nn if (uCamPos !== undefined) {n uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));n }n }nn if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {n p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);n }n } // skinning uniforms must be set even if material didn't changen // auto-setting of texture unit for bone texture must go before other texturesn // not sure why, but otherwise weird things happennnn if (material.skinning) {n p_uniforms.setOptional(_gl, object, 'bindMatrix');n p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');n var skeleton = object.skeleton;nn if (skeleton) {n var bones = skeleton.bones;nn if (capabilities.floatVertexTextures) {n if (skeleton.boneTexture === undefined) {n // layout (1 matrix = 4 pixels)n // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)n // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)n // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)n // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)n // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)n var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrixnn size = _Math.ceilPowerOfTwo(size);n size = Math.max(size, 4);n var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixelnn boneMatrices.set(skeleton.boneMatrices); // copy current valuesnn var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);n boneTexture.needsUpdate = true;n skeleton.boneMatrices = boneMatrices;n skeleton.boneTexture = boneTexture;n skeleton.boneTextureSize = size;n }nn p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);n p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);n } else {n p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');n }n }n }nn if (refreshMaterial) {n p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);n p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);nn if (material.lights) {n // the current material requires lighting infon // note: all lighting uniforms are always set correctlyn // they simply reference the renderer's state for theirn // valuesn //n // use the current material's .needsUpdate flags to setn // the GL state when requiredn markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);n } // refresh uniforms common to several materialsnnn if (fog && material.fog) {n refreshUniformsFog(m_uniforms, fog);n }nn if (material.isMeshBasicMaterial) {n refreshUniformsCommon(m_uniforms, material);n } else if (material.isMeshLambertMaterial) {n refreshUniformsCommon(m_uniforms, material);n refreshUniformsLambert(m_uniforms, material);n } else if (material.isMeshPhongMaterial) {n refreshUniformsCommon(m_uniforms, material);nn if (material.isMeshToonMaterial) {n refreshUniformsToon(m_uniforms, material);n } else {n refreshUniformsPhong(m_uniforms, material);n }n } else if (material.isMeshStandardMaterial) {n refreshUniformsCommon(m_uniforms, material);nn if (material.isMeshPhysicalMaterial) {n refreshUniformsPhysical(m_uniforms, material);n } else {n refreshUniformsStandard(m_uniforms, material);n }n } else if (material.isMeshMatcapMaterial) {n refreshUniformsCommon(m_uniforms, material);n refreshUniformsMatcap(m_uniforms, material);n } else if (material.isMeshDepthMaterial) {n refreshUniformsCommon(m_uniforms, material);n refreshUniformsDepth(m_uniforms, material);n } else if (material.isMeshDistanceMaterial) {n refreshUniformsCommon(m_uniforms, material);n refreshUniformsDistance(m_uniforms, material);n } else if (material.isMeshNormalMaterial) {n refreshUniformsCommon(m_uniforms, material);n refreshUniformsNormal(m_uniforms, material);n } else if (material.isLineBasicMaterial) {n refreshUniformsLine(m_uniforms, material);nn if (material.isLineDashedMaterial) {n refreshUniformsDash(m_uniforms, material);n }n } else if (material.isPointsMaterial) {n refreshUniformsPoints(m_uniforms, material);n } else if (material.isSpriteMaterial) {n refreshUniformsSprites(m_uniforms, material);n } else if (material.isShadowMaterial) {n m_uniforms.color.value.copy(material.color);n m_uniforms.opacity.value = material.opacity;n } // RectAreaLight Texturen // TODO (mrdoob): Find a nicer implementationnnn if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;n if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;n WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);n }nn if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {n WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);n material.uniformsNeedUpdate = false;n }nn if (material.isSpriteMaterial) {n p_uniforms.setValue(_gl, 'center', object.center);n } // common matricesnnn p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);n p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);n p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);n return program;n } // Uniforms (refresh uniforms objects)nnn function refreshUniformsCommon(uniforms, material) {n uniforms.opacity.value = material.opacity;nn if (material.color) {n uniforms.diffuse.value.copy(material.color);n }nn if (material.emissive) {n uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);n }nn if (material.map) {n uniforms.map.value = material.map;n }nn if (material.alphaMap) {n uniforms.alphaMap.value = material.alphaMap;n }nn if (material.specularMap) {n uniforms.specularMap.value = material.specularMap;n }nn if (material.envMap) {n uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:n // WebGLRenderTargetCube will be flipped for backwards compatibilityn // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexturen // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the futurenn uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;n uniforms.reflectivity.value = material.reflectivity;n uniforms.refractionRatio.value = material.refractionRatio;n uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;n }nn if (material.lightMap) {n uniforms.lightMap.value = material.lightMap;n uniforms.lightMapIntensity.value = material.lightMapIntensity;n }nn if (material.aoMap) {n uniforms.aoMap.value = material.aoMap;n uniforms.aoMapIntensity.value = material.aoMapIntensity;n } // uv repeat and offset setting prioritiesn // 1. color mapn // 2. specular mapn // 3. normal mapn // 4. bump mapn // 5. alpha mapn // 6. emissive mapnnn var uvScaleMap;nn if (material.map) {n uvScaleMap = material.map;n } else if (material.specularMap) {n uvScaleMap = material.specularMap;n } else if (material.displacementMap) {n uvScaleMap = material.displacementMap;n } else if (material.normalMap) {n uvScaleMap = material.normalMap;n } else if (material.bumpMap) {n uvScaleMap = material.bumpMap;n } else if (material.roughnessMap) {n uvScaleMap = material.roughnessMap;n } else if (material.metalnessMap) {n uvScaleMap = material.metalnessMap;n } else if (material.alphaMap) {n uvScaleMap = material.alphaMap;n } else if (material.emissiveMap) {n uvScaleMap = material.emissiveMap;n }nn if (uvScaleMap !== undefined) {n // backwards compatibilityn if (uvScaleMap.isWebGLRenderTarget) {n uvScaleMap = uvScaleMap.texture;n }nn if (uvScaleMap.matrixAutoUpdate === true) {n uvScaleMap.updateMatrix();n }nn uniforms.uvTransform.value.copy(uvScaleMap.matrix);n }n }nn function refreshUniformsLine(uniforms, material) {n uniforms.diffuse.value.copy(material.color);n uniforms.opacity.value = material.opacity;n }nn function refreshUniformsDash(uniforms, material) {n uniforms.dashSize.value = material.dashSize;n uniforms.totalSize.value = material.dashSize + material.gapSize;n uniforms.scale.value = material.scale;n }nn function refreshUniformsPoints(uniforms, material) {n uniforms.diffuse.value.copy(material.color);n uniforms.opacity.value = material.opacity;n uniforms.size.value = material.size * _pixelRatio;n uniforms.scale.value = _height * 0.5;n uniforms.map.value = material.map;nn if (material.map !== null) {n if (material.map.matrixAutoUpdate === true) {n material.map.updateMatrix();n }nn uniforms.uvTransform.value.copy(material.map.matrix);n }n }nn function refreshUniformsSprites(uniforms, material) {n uniforms.diffuse.value.copy(material.color);n uniforms.opacity.value = material.opacity;n uniforms.rotation.value = material.rotation;n uniforms.map.value = material.map;nn if (material.map !== null) {n if (material.map.matrixAutoUpdate === true) {n material.map.updateMatrix();n }nn uniforms.uvTransform.value.copy(material.map.matrix);n }n }nn function refreshUniformsFog(uniforms, fog) {n uniforms.fogColor.value.copy(fog.color);nn if (fog.isFog) {n uniforms.fogNear.value = fog.near;n uniforms.fogFar.value = fog.far;n } else if (fog.isFogExp2) {n uniforms.fogDensity.value = fog.density;n }n }nn function refreshUniformsLambert(uniforms, material) {n if (material.emissiveMap) {n uniforms.emissiveMap.value = material.emissiveMap;n }n }nn function refreshUniformsPhong(uniforms, material) {n uniforms.specular.value.copy(material.specular);n uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )nn if (material.emissiveMap) {n uniforms.emissiveMap.value = material.emissiveMap;n }nn if (material.bumpMap) {n uniforms.bumpMap.value = material.bumpMap;n uniforms.bumpScale.value = material.bumpScale;n if (material.side === BackSide) uniforms.bumpScale.value *= -1;n }nn if (material.normalMap) {n uniforms.normalMap.value = material.normalMap;n uniforms.normalScale.value.copy(material.normalScale);n if (material.side === BackSide) uniforms.normalScale.value.negate();n }nn if (material.displacementMap) {n uniforms.displacementMap.value = material.displacementMap;n uniforms.displacementScale.value = material.displacementScale;n uniforms.displacementBias.value = material.displacementBias;n }n }nn function refreshUniformsToon(uniforms, material) {n refreshUniformsPhong(uniforms, material);nn if (material.gradientMap) {n uniforms.gradientMap.value = material.gradientMap;n }n }nn function refreshUniformsStandard(uniforms, material) {n uniforms.roughness.value = material.roughness;n uniforms.metalness.value = material.metalness;nn if (material.roughnessMap) {n uniforms.roughnessMap.value = material.roughnessMap;n }nn if (material.metalnessMap) {n uniforms.metalnessMap.value = material.metalnessMap;n }nn if (material.emissiveMap) {n uniforms.emissiveMap.value = material.emissiveMap;n }nn if (material.bumpMap) {n uniforms.bumpMap.value = material.bumpMap;n uniforms.bumpScale.value = material.bumpScale;n if (material.side === BackSide) uniforms.bumpScale.value *= -1;n }nn if (material.normalMap) {n uniforms.normalMap.value = material.normalMap;n uniforms.normalScale.value.copy(material.normalScale);n if (material.side === BackSide) uniforms.normalScale.value.negate();n }nn if (material.displacementMap) {n uniforms.displacementMap.value = material.displacementMap;n uniforms.displacementScale.value = material.displacementScale;n uniforms.displacementBias.value = material.displacementBias;n }nn if (material.envMap) {n //uniforms.envMap.value = material.envMap; // part of uniforms commonn uniforms.envMapIntensity.value = material.envMapIntensity;n }n }nn function refreshUniformsPhysical(uniforms, material) {n refreshUniformsStandard(uniforms, material);n uniforms.reflectivity.value = material.reflectivity; // also part of uniforms commonnn uniforms.clearcoat.value = material.clearcoat;n uniforms.clearcoatRoughness.value = material.clearcoatRoughness;n if (material.sheen) uniforms.sheen.value.copy(material.sheen);nn if (material.clearcoatNormalMap) {n uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);n uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;nn if (material.side === BackSide) {n uniforms.clearcoatNormalScale.value.negate();n }n }nn uniforms.transparency.value = material.transparency;n }nn function refreshUniformsMatcap(uniforms, material) {n if (material.matcap) {n uniforms.matcap.value = material.matcap;n }nn if (material.bumpMap) {n uniforms.bumpMap.value = material.bumpMap;n uniforms.bumpScale.value = material.bumpScale;n if (material.side === BackSide) uniforms.bumpScale.value *= -1;n }nn if (material.normalMap) {n uniforms.normalMap.value = material.normalMap;n uniforms.normalScale.value.copy(material.normalScale);n if (material.side === BackSide) uniforms.normalScale.value.negate();n }nn if (material.displacementMap) {n uniforms.displacementMap.value = material.displacementMap;n uniforms.displacementScale.value = material.displacementScale;n uniforms.displacementBias.value = material.displacementBias;n }n }nn function refreshUniformsDepth(uniforms, material) {n if (material.displacementMap) {n uniforms.displacementMap.value = material.displacementMap;n uniforms.displacementScale.value = material.displacementScale;n uniforms.displacementBias.value = material.displacementBias;n }n }nn function refreshUniformsDistance(uniforms, material) {n if (material.displacementMap) {n uniforms.displacementMap.value = material.displacementMap;n uniforms.displacementScale.value = material.displacementScale;n uniforms.displacementBias.value = material.displacementBias;n }nn uniforms.referencePosition.value.copy(material.referencePosition);n uniforms.nearDistance.value = material.nearDistance;n uniforms.farDistance.value = material.farDistance;n }nn function refreshUniformsNormal(uniforms, material) {n if (material.bumpMap) {n uniforms.bumpMap.value = material.bumpMap;n uniforms.bumpScale.value = material.bumpScale;n if (material.side === BackSide) uniforms.bumpScale.value *= -1;n }nn if (material.normalMap) {n uniforms.normalMap.value = material.normalMap;n uniforms.normalScale.value.copy(material.normalScale);n if (material.side === BackSide) uniforms.normalScale.value.negate();n }nn if (material.displacementMap) {n uniforms.displacementMap.value = material.displacementMap;n uniforms.displacementScale.value = material.displacementScale;n uniforms.displacementBias.value = material.displacementBias;n }n } // If uniforms are marked as clean, they don't need to be loaded to the GPU.nnn function markUniformsLightsNeedsUpdate(uniforms, value) {n uniforms.ambientLightColor.needsUpdate = value;n uniforms.lightProbe.needsUpdate = value;n uniforms.directionalLights.needsUpdate = value;n uniforms.pointLights.needsUpdate = value;n uniforms.spotLights.needsUpdate = value;n uniforms.rectAreaLights.needsUpdate = value;n uniforms.hemisphereLights.needsUpdate = value;n } //nnn this.setFramebuffer = function (value) {n if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);n _framebuffer = value;n };nn this.getActiveCubeFace = function () {n return _currentActiveCubeFace;n };nn this.getActiveMipmapLevel = function () {n return _currentActiveMipmapLevel;n };nn this.getRenderTarget = function () {n return _currentRenderTarget;n };nn this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {n _currentRenderTarget = renderTarget;n _currentActiveCubeFace = activeCubeFace;n _currentActiveMipmapLevel = activeMipmapLevel;nn if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {n textures.setupRenderTarget(renderTarget);n }nn var framebuffer = _framebuffer;n var isCube = false;nn if (renderTarget) {n var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;nn if (renderTarget.isWebGLRenderTargetCube) {n framebuffer = __webglFramebuffer[activeCubeFace || 0];n isCube = true;n } else if (renderTarget.isWebGLMultisampleRenderTarget) {n framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;n } else {n framebuffer = __webglFramebuffer;n }nn _currentViewport.copy(renderTarget.viewport);nn _currentScissor.copy(renderTarget.scissor);nn _currentScissorTest = renderTarget.scissorTest;n } else {n _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();nn _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();nn _currentScissorTest = _scissorTest;n }nn if (_currentFramebuffer !== framebuffer) {n _gl.bindFramebuffer(36160, framebuffer);nn _currentFramebuffer = framebuffer;n }nn state.viewport(_currentViewport);n state.scissor(_currentScissor);n state.setScissorTest(_currentScissorTest);nn if (isCube) {n var textureProperties = properties.get(renderTarget.texture);nn _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);n }n };nn this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {n if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {n console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');n return;n }nn var framebuffer = properties.get(renderTarget).__webglFramebuffer;nn if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {n framebuffer = framebuffer;n }nn if (framebuffer) {n var restore = false;nn if (framebuffer !== _currentFramebuffer) {n _gl.bindFramebuffer(36160, framebuffer);nn restore = true;n }nn try {n var texture = renderTarget.texture;n var textureFormat = texture.format;n var textureType = texture.type;nn if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {n console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');n return;n }nn if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)n !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefoxn !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {n console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');n return;n }nn if (_gl.checkFramebufferStatus(36160) === 36053) {n // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)n if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {n _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);n }n } else {n console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');n }n } finally {n if (restore) {n _gl.bindFramebuffer(36160, _currentFramebuffer);n }n }n }n };nn this.copyFramebufferToTexture = function (position, texture, level) {n var width = texture.image.width;n var height = texture.image.height;n var glFormat = utils.convert(texture.format);n textures.setTexture2D(texture, 0);nn _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);n };nn this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {n var width = srcTexture.image.width;n var height = srcTexture.image.height;n var glFormat = utils.convert(dstTexture.format);n var glType = utils.convert(dstTexture.type);n textures.setTexture2D(dstTexture, 0);nn if (srcTexture.isDataTexture) {n _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);n } else {n _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);n }n };nn if (typeof THREE_DEVTOOLS !== 'undefined') {n THREE_DEVTOOLS.dispatchEvent(new CustomEvent('observe', {n detail: thisn })); // eslint-disable-line no-undefnn }n}n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n */nnnfunction FogExp2(color, density) {n this.name = '';n this.color = new Color(color);n this.density = density !== undefined ? density : 0.00025;n}nnObject.assign(FogExp2.prototype, {n isFogExp2: true,n clone: function clone() {n return new FogExp2(this.color, this.density);n },n toJSON: function toJSON()n /* meta */n {n return {n type: 'FogExp2',n color: this.color.getHex(),n density: this.densityn };n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n */nnfunction Fog(color, near, far) {n this.name = '';n this.color = new Color(color);n this.near = near !== undefined ? near : 1;n this.far = far !== undefined ? far : 1000;n}nnObject.assign(Fog.prototype, {n isFog: true,n clone: function clone() {n return new Fog(this.color, this.near, this.far);n },n toJSON: function toJSON()n /* meta */n {n return {n type: 'Fog',n color: this.color.getHex(),n near: this.near,n far: this.farn };n }n});n/**n * @author benaadams / twitter.com/ben_a_adamsn */nnfunction InterleavedBuffer(array, stride) {n this.array = array;n this.stride = stride;n this.count = array !== undefined ? array.length / stride : 0;n this.dynamic = false;n this.updateRange = {n offset: 0,n count: -1n };n this.version = 0;n}nnObject.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {n set: function set(value) {n if (value === true) this.version++;n }n});nObject.assign(InterleavedBuffer.prototype, {n isInterleavedBuffer: true,n onUploadCallback: function onUploadCallback() {},n setArray: function setArray(array) {n if (Array.isArray(array)) {n throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');n }nn this.count = array !== undefined ? array.length / this.stride : 0;n this.array = array;n return this;n },n setDynamic: function setDynamic(value) {n this.dynamic = value;n return this;n },n copy: function copy(source) {n this.array = new source.array.constructor(source.array);n this.count = source.count;n this.stride = source.stride;n this.dynamic = source.dynamic;n return this;n },n copyAt: function copyAt(index1, attribute, index2) {n index1 *= this.stride;n index2 *= attribute.stride;nn for (var i = 0, l = this.stride; i < l; i++) {n this.array[index1 + i] = attribute.array[index2 + i];n }nn return this;n },n set: function set(value, offset) {n if (offset === undefined) offset = 0;n this.array.set(value, offset);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n onUpload: function onUpload(callback) {n this.onUploadCallback = callback;n return this;n }n});n/**n * @author benaadams / twitter.com/ben_a_adamsn */nnfunction InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {n this.data = interleavedBuffer;n this.itemSize = itemSize;n this.offset = offset;n this.normalized = normalized === true;n}nnObject.defineProperties(InterleavedBufferAttribute.prototype, {n count: {n get: function get() {n return this.data.count;n }n },n array: {n get: function get() {n return this.data.array;n }n }n});nObject.assign(InterleavedBufferAttribute.prototype, {n isInterleavedBufferAttribute: true,n setX: function setX(index, x) {n this.data.array[index * this.data.stride + this.offset] = x;n return this;n },n setY: function setY(index, y) {n this.data.array[index * this.data.stride + this.offset + 1] = y;n return this;n },n setZ: function setZ(index, z) {n this.data.array[index * this.data.stride + this.offset + 2] = z;n return this;n },n setW: function setW(index, w) {n this.data.array[index * this.data.stride + this.offset + 3] = w;n return this;n },n getX: function getX(index) {n return this.data.array[index * this.data.stride + this.offset];n },n getY: function getY(index) {n return this.data.array[index * this.data.stride + this.offset + 1];n },n getZ: function getZ(index) {n return this.data.array[index * this.data.stride + this.offset + 2];n },n getW: function getW(index) {n return this.data.array[index * this.data.stride + this.offset + 3];n },n setXY: function setXY(index, x, y) {n index = index * this.data.stride + this.offset;n this.data.array[index + 0] = x;n this.data.array[index + 1] = y;n return this;n },n setXYZ: function setXYZ(index, x, y, z) {n index = index * this.data.stride + this.offset;n this.data.array[index + 0] = x;n this.data.array[index + 1] = y;n this.data.array[index + 2] = z;n return this;n },n setXYZW: function setXYZW(index, x, y, z, w) {n index = index * this.data.stride + this.offset;n this.data.array[index + 0] = x;n this.data.array[index + 1] = y;n this.data.array[index + 2] = z;n this.data.array[index + 3] = w;n return this;n }n});n/**n * @author alteredq / alteredqualia.com/n *n * parameters = {n * color: <hex>,n * map: new THREE.Texture( <Image> ),n * rotation: <float>,n * sizeAttenuation: <bool>n * }n */nnfunction SpriteMaterial(parameters) {n Material.call(this);n this.type = 'SpriteMaterial';n this.color = new Color(0xffffff);n this.map = null;n this.rotation = 0;n this.sizeAttenuation = true;n this.lights = false;n this.transparent = true;n this.setValues(parameters);n}nnSpriteMaterial.prototype = Object.create(Material.prototype);nSpriteMaterial.prototype.constructor = SpriteMaterial;nSpriteMaterial.prototype.isSpriteMaterial = true;nnSpriteMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.color.copy(source.color);n this.map = source.map;n this.rotation = source.rotation;n this.sizeAttenuation = source.sizeAttenuation;n return this;n};n/**n * @author mikael emtinger / gomo.se/n * @author alteredq / alteredqualia.com/n */nnnvar _geometry;nnvar _intersectPoint = new Vector3();nnvar _worldScale = new Vector3();nnvar _mvPosition = new Vector3();nnvar _alignedPosition = new Vector2();nnvar _rotatedPosition = new Vector2();nnvar _viewWorldMatrix = new Matrix4();nnvar _vA$1 = new Vector3();nnvar _vB$1 = new Vector3();nnvar _vC$1 = new Vector3();nnvar _uvA$1 = new Vector2();nnvar _uvB$1 = new Vector2();nnvar _uvC$1 = new Vector2();nnfunction Sprite(material) {n Object3D.call(this);n this.type = 'Sprite';nn if (_geometry === undefined) {n _geometry = new BufferGeometry();n var 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]);n var interleavedBuffer = new InterleavedBuffer(float32Array, 5);nn _geometry.setIndex([0, 1, 2, 0, 2, 3]);nn _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));nn _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));n }nn this.geometry = _geometry;n this.material = material !== undefined ? material : new SpriteMaterial();n this.center = new Vector2(0.5, 0.5);n}nnSprite.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Sprite,n isSprite: true,n raycast: function raycast(raycaster, intersects) {n if (raycaster.camera === null) {n console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');n }nn _worldScale.setFromMatrixScale(this.matrixWorld);nn _viewWorldMatrix.copy(raycaster.camera.matrixWorld);nn this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);nn _mvPosition.setFromMatrixPosition(this.modelViewMatrix);nn if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {n _worldScale.multiplyScalar(-_mvPosition.z);n }nn var rotation = this.material.rotation;n var sin, cos;nn if (rotation !== 0) {n cos = Math.cos(rotation);n sin = Math.sin(rotation);n }nn var center = this.center;n transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);n transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);n transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);nn _uvA$1.set(0, 0);nn _uvB$1.set(1, 0);nn _uvC$1.set(1, 1); // check first trianglennn var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);nn if (intersect === null) {n // check second trianglen transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);nn _uvB$1.set(0, 1);nn intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);nn if (intersect === null) {n return;n }n }nn var distance = raycaster.ray.origin.distanceTo(_intersectPoint);n if (distance < raycaster.near || distance > raycaster.far) return;n intersects.push({n distance: distance,n point: _intersectPoint.clone(),n uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),n face: null,n object: thisn });n },n clone: function clone() {n return new this.constructor(this.material).copy(this);n },n copy: function copy(source) {n Object3D.prototype.copy.call(this, source);n if (source.center !== undefined) this.center.copy(source.center);n return this;n }n});nnfunction transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {n // compute position in camera spacen _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zeronnn if (sin !== undefined) {n _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;n _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;n } else {n _rotatedPosition.copy(_alignedPosition);n }nn vertexPosition.copy(mvPosition);n vertexPosition.x += _rotatedPosition.x;n vertexPosition.y += _rotatedPosition.y; // transform to world spacenn vertexPosition.applyMatrix4(_viewWorldMatrix);n}n/**n * @author mikael emtinger / gomo.se/n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n */nnnvar _v1$4 = new Vector3();nnvar _v2$2 = new Vector3();nnfunction LOD() {n Object3D.call(this);n this.type = 'LOD';n Object.defineProperties(this, {n levels: {n enumerable: true,n value: []n }n });n this.autoUpdate = true;n}nnLOD.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: LOD,n isLOD: true,n copy: function copy(source) {n Object3D.prototype.copy.call(this, source, false);n var levels = source.levels;nn for (var i = 0, l = levels.length; i < l; i++) {n var level = levels;n this.addLevel(level.object.clone(), level.distance);n }nn return this;n },n addLevel: function addLevel(object, distance) {n if (distance === undefined) distance = 0;n distance = Math.abs(distance);n var levels = this.levels;nn for (var l = 0; l < levels.length; l++) {n if (distance < levels.distance) {n break;n }n }nn levels.splice(l, 0, {n distance: distance,n object: objectn });n this.add(object);n return this;n },n getObjectForDistance: function getObjectForDistance(distance) {n var levels = this.levels;nn for (var i = 1, l = levels.length; i < l; i++) {n if (distance < levels.distance) {n break;n }n }nn return levels[i - 1].object;n },n raycast: function raycast(raycaster, intersects) {n _v1$4.setFromMatrixPosition(this.matrixWorld);nn var distance = raycaster.ray.origin.distanceTo(_v1$4);n this.getObjectForDistance(distance).raycast(raycaster, intersects);n },n update: function update(camera) {n var levels = this.levels;nn if (levels.length > 1) {n _v1$4.setFromMatrixPosition(camera.matrixWorld);nn _v2$2.setFromMatrixPosition(this.matrixWorld);nn var distance = _v1$4.distanceTo(_v2$2);nn levels.object.visible = true;nn for (var i = 1, l = levels.length; i < l; i++) {n if (distance >= levels.distance) {n levels[i - 1].object.visible = false;n levels.object.visible = true;n } else {n break;n }n }nn for (; i < l; i++) {n levels.object.visible = false;n }n }n },n toJSON: function toJSON(meta) {n var data = Object3D.prototype.toJSON.call(this, meta);n data.object.levels = [];n var levels = this.levels;nn for (var i = 0, l = levels.length; i < l; i++) {n var level = levels;n data.object.levels.push({n object: level.object.uuid,n distance: level.distancen });n }nn return data;n }n});n/**n * @author mikael emtinger / gomo.se/n * @author alteredq / alteredqualia.com/n * @author ikerr / verold.comn */nnfunction SkinnedMesh(geometry, material) {n if (geometry && geometry.isGeometry) {n console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');n }nn Mesh.call(this, geometry, material);n this.type = 'SkinnedMesh';n this.bindMode = 'attached';n this.bindMatrix = new Matrix4();n this.bindMatrixInverse = new Matrix4();n}nnSkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {n constructor: SkinnedMesh,n isSkinnedMesh: true,n bind: function bind(skeleton, bindMatrix) {n this.skeleton = skeleton;nn if (bindMatrix === undefined) {n this.updateMatrixWorld(true);n this.skeleton.calculateInverses();n bindMatrix = this.matrixWorld;n }nn this.bindMatrix.copy(bindMatrix);n this.bindMatrixInverse.getInverse(bindMatrix);n },n pose: function pose() {n this.skeleton.pose();n },n normalizeSkinWeights: function normalizeSkinWeights() {n var vector = new Vector4();n var skinWeight = this.geometry.attributes.skinWeight;nn for (var i = 0, l = skinWeight.count; i < l; i++) {n vector.x = skinWeight.getX(i);n vector.y = skinWeight.getY(i);n vector.z = skinWeight.getZ(i);n vector.w = skinWeight.getW(i);n var scale = 1.0 / vector.manhattanLength();nn if (scale !== Infinity) {n vector.multiplyScalar(scale);n } else {n vector.set(1, 0, 0, 0); // do something reasonablen }nn skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);n }n },n updateMatrixWorld: function updateMatrixWorld(force) {n Mesh.prototype.updateMatrixWorld.call(this, force);nn if (this.bindMode === 'attached') {n this.bindMatrixInverse.getInverse(this.matrixWorld);n } else if (this.bindMode === 'detached') {n this.bindMatrixInverse.getInverse(this.bindMatrix);n } else {n console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);n }n },n clone: function clone() {n return new this.constructor(this.geometry, this.material).copy(this);n }n});n/**n * @author mikael emtinger / gomo.se/n * @author alteredq / alteredqualia.com/n * @author michael guerrero / realitymeltdown.comn * @author ikerr / verold.comn */nnvar _offsetMatrix = new Matrix4();nnvar _identityMatrix = new Matrix4();nnfunction Skeleton(bones, boneInverses) {n // copy the bone arrayn bones = bones || [];n this.bones = bones.slice(0);n this.boneMatrices = new Float32Array(this.bones.length * 16); // use the supplied bone inverses or calculate the inversesnn if (boneInverses === undefined) {n this.calculateInverses();n } else {n if (this.bones.length === boneInverses.length) {n this.boneInverses = boneInverses.slice(0);n } else {n console.warn('THREE.Skeleton boneInverses is the wrong length.');n this.boneInverses = [];nn for (var i = 0, il = this.bones.length; i < il; i++) {n this.boneInverses.push(new Matrix4());n }n }n }n}nnObject.assign(Skeleton.prototype, {n calculateInverses: function calculateInverses() {n this.boneInverses = [];nn for (var i = 0, il = this.bones.length; i < il; i++) {n var inverse = new Matrix4();nn if (this.bones) {n inverse.getInverse(this.bones.matrixWorld);n }nn this.boneInverses.push(inverse);n }n },n pose: function pose() {n var bone, i, il; // recover the bind-time world matricesnn for (i = 0, il = this.bones.length; i < il; i++) {n bone = this.bones;nn if (bone) {n bone.matrixWorld.getInverse(this.boneInverses);n }n } // compute the local matrices, positions, rotations and scalesnnn for (i = 0, il = this.bones.length; i < il; i++) {n bone = this.bones;nn if (bone) {n if (bone.parent && bone.parent.isBone) {n bone.matrix.getInverse(bone.parent.matrixWorld);n bone.matrix.multiply(bone.matrixWorld);n } else {n bone.matrix.copy(bone.matrixWorld);n }nn bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);n }n }n },n update: function update() {n var bones = this.bones;n var boneInverses = this.boneInverses;n var boneMatrices = this.boneMatrices;n var boneTexture = this.boneTexture; // flatten bone matrices to arraynn for (var i = 0, il = bones.length; i < il; i++) {n // compute the offset between the current and the original transformn var matrix = bones ? bones.matrixWorld : _identityMatrix;nn _offsetMatrix.multiplyMatrices(matrix, boneInverses);nn _offsetMatrix.toArray(boneMatrices, i * 16);n }nn if (boneTexture !== undefined) {n boneTexture.needsUpdate = true;n }n },n clone: function clone() {n return new Skeleton(this.bones, this.boneInverses);n },n getBoneByName: function getBoneByName(name) {n for (var i = 0, il = this.bones.length; i < il; i++) {n var bone = this.bones;nn if (bone.name === name) {n return bone;n }n }nn return undefined;n }n});n/**n * @author mikael emtinger / gomo.se/n * @author alteredq / alteredqualia.com/n * @author ikerr / verold.comn */nnfunction Bone() {n Object3D.call(this);n this.type = 'Bone';n}nnBone.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Bone,n isBone: truen});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n *n * parameters = {n * color: <hex>,n * opacity: <float>,n *n * linewidth: <float>,n * linecap: "round",n * linejoin: "round"n * }n */nnfunction LineBasicMaterial(parameters) {n Material.call(this);n this.type = 'LineBasicMaterial';n this.color = new Color(0xffffff);n this.linewidth = 1;n this.linecap = 'round';n this.linejoin = 'round';n this.lights = false;n this.setValues(parameters);n}nnLineBasicMaterial.prototype = Object.create(Material.prototype);nLineBasicMaterial.prototype.constructor = LineBasicMaterial;nLineBasicMaterial.prototype.isLineBasicMaterial = true;nnLineBasicMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.color.copy(source.color);n this.linewidth = source.linewidth;n this.linecap = source.linecap;n this.linejoin = source.linejoin;n return this;n};n/**n * @author mrdoob / mrdoob.com/n */nnnvar _start = new Vector3();nnvar _end = new Vector3();nnvar _inverseMatrix$1 = new Matrix4();nnvar _ray$1 = new Ray();nnvar _sphere$2 = new Sphere();nnfunction Line(geometry, material, mode) {n if (mode === 1) {n console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');n }nn Object3D.call(this);n this.type = 'Line';n this.geometry = geometry !== undefined ? geometry : new BufferGeometry();n this.material = material !== undefined ? material : new LineBasicMaterial({n color: Math.random() * 0xffffffn });n}nnLine.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Line,n isLine: true,n computeLineDistances: function computeLineDistances() {n var geometry = this.geometry;nn if (geometry.isBufferGeometry) {n // we assume non-indexed geometryn if (geometry.index === null) {n var positionAttribute = geometry.attributes.position;n var lineDistances = [0];nn for (var i = 1, l = positionAttribute.count; i < l; i++) {n _start.fromBufferAttribute(positionAttribute, i - 1);nn _end.fromBufferAttribute(positionAttribute, i);nn lineDistances = lineDistances[i - 1];n lineDistances += _start.distanceTo(_end);n }nn geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));n } else {n console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');n }n } else if (geometry.isGeometry) {n var vertices = geometry.vertices;n var lineDistances = geometry.lineDistances;n lineDistances = 0;nn for (var i = 1, l = vertices.length; i < l; i++) {n lineDistances = lineDistances[i - 1];n lineDistances += vertices[i - 1].distanceTo(vertices);n }n }nn return this;n },n raycast: function raycast(raycaster, intersects) {n var precision = raycaster.linePrecision;n var geometry = this.geometry;n var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to raynn if (geometry.boundingSphere === null) geometry.computeBoundingSphere();nn _sphere$2.copy(geometry.boundingSphere);nn _sphere$2.applyMatrix4(matrixWorld);nn _sphere$2.radius += precision;n if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //nn _inverseMatrix$1.getInverse(matrixWorld);nn _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);nn var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);n var localPrecisionSq = localPrecision * localPrecision;n var vStart = new Vector3();n var vEnd = new Vector3();n var interSegment = new Vector3();n var interRay = new Vector3();n var step = this && this.isLineSegments ? 2 : 1;nn if (geometry.isBufferGeometry) {n var index = geometry.index;n var attributes = geometry.attributes;n var positions = attributes.position.array;nn if (index !== null) {n var indices = index.array;nn for (var i = 0, l = indices.length - 1; i < l; i += step) {n var a = indices;n var b = indices[i + 1];n vStart.fromArray(positions, a * 3);n vEnd.fromArray(positions, b * 3);nn var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);nn if (distSq > localPrecisionSq) continue;n interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculationnn var distance = raycaster.ray.origin.distanceTo(interRay);n if (distance < raycaster.near || distance > raycaster.far) continue;n intersects.push({n distance: distance,n // What do we want? intersection point on the ray or on the segment??n // point: raycaster.ray.at( distance ),n point: interSegment.clone().applyMatrix4(this.matrixWorld),n index: i,n face: null,n faceIndex: null,n object: thisn });n }n } else {n for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {n vStart.fromArray(positions, 3 * i);n vEnd.fromArray(positions, 3 * i + 3);nn var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);nn if (distSq > localPrecisionSq) continue;n interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculationnn var distance = raycaster.ray.origin.distanceTo(interRay);n if (distance < raycaster.near || distance > raycaster.far) continue;n intersects.push({n distance: distance,n // What do we want? intersection point on the ray or on the segment??n // point: raycaster.ray.at( distance ),n point: interSegment.clone().applyMatrix4(this.matrixWorld),n index: i,n face: null,n faceIndex: null,n object: thisn });n }n }n } else if (geometry.isGeometry) {n var vertices = geometry.vertices;n var nbVertices = vertices.length;nn for (var i = 0; i < nbVertices - 1; i += step) {n var distSq = _ray$1.distanceSqToSegment(vertices, vertices[i + 1], interRay, interSegment);nn if (distSq > localPrecisionSq) continue;n interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculationnn var distance = raycaster.ray.origin.distanceTo(interRay);n if (distance < raycaster.near || distance > raycaster.far) continue;n intersects.push({n distance: distance,n // What do we want? intersection point on the ray or on the segment??n // point: raycaster.ray.at( distance ),n point: interSegment.clone().applyMatrix4(this.matrixWorld),n index: i,n face: null,n faceIndex: null,n object: thisn });n }n }n },n clone: function clone() {n return new this.constructor(this.geometry, this.material).copy(this);n }n});n/**n * @author mrdoob / mrdoob.com/n */nnvar _start$1 = new Vector3();nnvar _end$1 = new Vector3();nnfunction LineSegments(geometry, material) {n Line.call(this, geometry, material);n this.type = 'LineSegments';n}nnLineSegments.prototype = Object.assign(Object.create(Line.prototype), {n constructor: LineSegments,n isLineSegments: true,n computeLineDistances: function computeLineDistances() {n var geometry = this.geometry;nn if (geometry.isBufferGeometry) {n // we assume non-indexed geometryn if (geometry.index === null) {n var positionAttribute = geometry.attributes.position;n var lineDistances = [];nn for (var i = 0, l = positionAttribute.count; i < l; i += 2) {n _start$1.fromBufferAttribute(positionAttribute, i);nn _end$1.fromBufferAttribute(positionAttribute, i + 1);nn lineDistances = i === 0 ? 0 : lineDistances[i - 1];n lineDistances[i + 1] = lineDistances + _start$1.distanceTo(_end$1);n }nn geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));n } else {n console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');n }n } else if (geometry.isGeometry) {n var vertices = geometry.vertices;n var lineDistances = geometry.lineDistances;nn for (var i = 0, l = vertices.length; i < l; i += 2) {n _start$1.copy(vertices);nn _end$1.copy(vertices[i + 1]);nn lineDistances = i === 0 ? 0 : lineDistances[i - 1];n lineDistances[i + 1] = lineDistances + _start$1.distanceTo(_end$1);n }n }nn return this;n }n});n/**n * @author mgreter / github.com/mgretern */nnfunction LineLoop(geometry, material) {n Line.call(this, geometry, material);n this.type = 'LineLoop';n}nnLineLoop.prototype = Object.assign(Object.create(Line.prototype), {n constructor: LineLoop,n isLineLoop: truen});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n *n * parameters = {n * color: <hex>,n * opacity: <float>,n * map: new THREE.Texture( <Image> ),n *n * size: <float>,n * sizeAttenuation: <bool>n *n * morphTargets: <bool>n * }n */nnfunction PointsMaterial(parameters) {n Material.call(this);n this.type = 'PointsMaterial';n this.color = new Color(0xffffff);n this.map = null;n this.size = 1;n this.sizeAttenuation = true;n this.morphTargets = false;n this.lights = false;n this.setValues(parameters);n}nnPointsMaterial.prototype = Object.create(Material.prototype);nPointsMaterial.prototype.constructor = PointsMaterial;nPointsMaterial.prototype.isPointsMaterial = true;nnPointsMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.color.copy(source.color);n this.map = source.map;n this.size = source.size;n this.sizeAttenuation = source.sizeAttenuation;n this.morphTargets = source.morphTargets;n return this;n};n/**n * @author alteredq / alteredqualia.com/n */nnnvar _inverseMatrix$2 = new Matrix4();nnvar _ray$2 = new Ray();nnvar _sphere$3 = new Sphere();nnvar _position$1 = new Vector3();nnfunction Points(geometry, material) {n Object3D.call(this);n this.type = 'Points';n this.geometry = geometry !== undefined ? geometry : new BufferGeometry();n this.material = material !== undefined ? material : new PointsMaterial({n color: Math.random() * 0xffffffn });n this.updateMorphTargets();n}nnPoints.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Points,n isPoints: true,n raycast: function raycast(raycaster, intersects) {n var geometry = this.geometry;n var matrixWorld = this.matrixWorld;n var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to raynn if (geometry.boundingSphere === null) geometry.computeBoundingSphere();nn _sphere$3.copy(geometry.boundingSphere);nn _sphere$3.applyMatrix4(matrixWorld);nn _sphere$3.radius += threshold;n if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //nn _inverseMatrix$2.getInverse(matrixWorld);nn _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);nn var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);n var localThresholdSq = localThreshold * localThreshold;nn if (geometry.isBufferGeometry) {n var index = geometry.index;n var attributes = geometry.attributes;n var positions = attributes.position.array;nn if (index !== null) {n var indices = index.array;nn for (var i = 0, il = indices.length; i < il; i++) {n var a = indices;nn _position$1.fromArray(positions, a * 3);nn testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);n }n } else {n for (var i = 0, l = positions.length / 3; i < l; i++) {n _position$1.fromArray(positions, i * 3);nn testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);n }n }n } else {n var vertices = geometry.vertices;nn for (var i = 0, l = vertices.length; i < l; i++) {n testPoint(vertices, i, localThresholdSq, matrixWorld, raycaster, intersects, this);n }n }n },n updateMorphTargets: function updateMorphTargets() {n var geometry = this.geometry;n var m, ml, name;nn if (geometry.isBufferGeometry) {n var morphAttributes = geometry.morphAttributes;n var keys = Object.keys(morphAttributes);nn if (keys.length > 0) {n var morphAttribute = morphAttributes[keys];nn if (morphAttribute !== undefined) {n this.morphTargetInfluences = [];n this.morphTargetDictionary = {};nn for (m = 0, ml = morphAttribute.length; m < ml; m++) {n name = morphAttribute.name || String(m);n this.morphTargetInfluences.push(0);n this.morphTargetDictionary = m;n }n }n }n } else {n var morphTargets = geometry.morphTargets;nn if (morphTargets !== undefined && morphTargets.length > 0) {n console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');n }n }n },n clone: function clone() {n return new this.constructor(this.geometry, this.material).copy(this);n }n});nnfunction testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {n var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);nn if (rayPointDistanceSq < localThresholdSq) {n var intersectPoint = new Vector3();nn _ray$2.closestPointToPoint(point, intersectPoint);nn intersectPoint.applyMatrix4(matrixWorld);n var distance = raycaster.ray.origin.distanceTo(intersectPoint);n if (distance < raycaster.near || distance > raycaster.far) return;n intersects.push({n distance: distance,n distanceToRay: Math.sqrt(rayPointDistanceSq),n point: intersectPoint,n index: index,n face: null,n object: objectn });n }n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {n Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);n this.format = format !== undefined ? format : RGBFormat;n this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;n this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;n this.generateMipmaps = false;n}nnVideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {n constructor: VideoTexture,n isVideoTexture: true,n update: function update() {n var video = this.image;nn if (video.readyState >= video.HAVE_CURRENT_DATA) {n this.needsUpdate = true;n }n }n});n/**n * @author alteredq / alteredqualia.com/n */nnfunction CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {n Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);n this.image = {n width: width,n height: heightn };n this.mipmaps = mipmaps; // no flipping for cube texturesn // (also flipping doesn't work for compressed textures )nn this.flipY = false; // can't generate mipmaps for compressed texturesn // mips must be embedded in DDS filesnn this.generateMipmaps = false;n}nnCompressedTexture.prototype = Object.create(Texture.prototype);nCompressedTexture.prototype.constructor = CompressedTexture;nCompressedTexture.prototype.isCompressedTexture = true;n/**n * @author mrdoob / mrdoob.com/n */nnfunction CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {n Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);n this.needsUpdate = true;n}nnCanvasTexture.prototype = Object.create(Texture.prototype);nCanvasTexture.prototype.constructor = CanvasTexture;nCanvasTexture.prototype.isCanvasTexture = true;n/**n * @author Matt DesLauriers / @mattdesln * @author atix / arthursilber.den */nnfunction DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {n format = format !== undefined ? format : DepthFormat;nn if (format !== DepthFormat && format !== DepthStencilFormat) {n throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');n }nn if (type === undefined && format === DepthFormat) type = UnsignedShortType;n if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;n Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);n this.image = {n width: width,n height: heightn };n this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;n this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;n this.flipY = false;n this.generateMipmaps = false;n}nnDepthTexture.prototype = Object.create(Texture.prototype);nDepthTexture.prototype.constructor = DepthTexture;nDepthTexture.prototype.isDepthTexture = true;n/**n * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n */nnfunction WireframeGeometry(geometry) {n BufferGeometry.call(this);n this.type = 'WireframeGeometry'; // buffernn var vertices = []; // helper variablesnn var i, j, l, o, ol;n var edge = [0, 0],n edges = {},n e,n edge1,n edge2;n var key,n keys = ['a', 'b', 'c'];n var vertex; // different logic for Geometry and BufferGeometrynn if (geometry && geometry.isGeometry) {n // create a data structure that contains all edges without duplicatesn var faces = geometry.faces;nn for (i = 0, l = faces.length; i < l; i++) {n var face = faces;nn for (j = 0; j < 3; j++) {n edge1 = face[keys];n edge2 = face[keys[(j + 1) % 3]];n edge = Math.min(edge1, edge2); // sorting prevents duplicatesnn edge = Math.max(edge1, edge2);n key = edge + ',' + edge;nn if (edges === undefined) {n edges = {n index1: edge,n index2: edgen };n }n }n } // generate verticesnnn for (key in edges) {n e = edges;n vertex = geometry.vertices;n vertices.push(vertex.x, vertex.y, vertex.z);n vertex = geometry.vertices;n vertices.push(vertex.x, vertex.y, vertex.z);n }n } else if (geometry && geometry.isBufferGeometry) {n var position, indices, groups;n var group, start, count;n var index1, index2;n vertex = new Vector3();nn if (geometry.index !== null) {n // indexed BufferGeometryn position = geometry.attributes.position;n indices = geometry.index;n groups = geometry.groups;nn if (groups.length === 0) {n groups = [{n start: 0,n count: indices.count,n materialIndex: 0n }];n } // create a data structure that contains all eges without duplicatesnnn for (o = 0, ol = groups.length; o < ol; ++o) {n group = groups;n start = group.start;n count = group.count;nn for (i = start, l = start + count; i < l; i += 3) {n for (j = 0; j < 3; j++) {n edge1 = indices.getX(i + j);n edge2 = indices.getX(i + (j + 1) % 3);n edge = Math.min(edge1, edge2); // sorting prevents duplicatesnn edge = Math.max(edge1, edge2);n key = edge + ',' + edge;nn if (edges === undefined) {n edges = {n index1: edge,n index2: edgen };n }n }n }n } // generate verticesnnn for (key in edges) {n e = edges;n vertex.fromBufferAttribute(position, e.index1);n vertices.push(vertex.x, vertex.y, vertex.z);n vertex.fromBufferAttribute(position, e.index2);n vertices.push(vertex.x, vertex.y, vertex.z);n }n } else {n // non-indexed BufferGeometryn position = geometry.attributes.position;nn for (i = 0, l = position.count / 3; i < l; i++) {n for (j = 0; j < 3; j++) {n // three edges per triangle, an edge is represented as (index1, index2)n // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)n index1 = 3 * i + j;n vertex.fromBufferAttribute(position, index1);n vertices.push(vertex.x, vertex.y, vertex.z);n index2 = 3 * i + (j + 1) % 3;n vertex.fromBufferAttribute(position, index2);n vertices.push(vertex.x, vertex.y, vertex.z);n }n }n }n } // build geometrynnn this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n}nnWireframeGeometry.prototype = Object.create(BufferGeometry.prototype);nWireframeGeometry.prototype.constructor = WireframeGeometry;n/**n * @author zz85 / github.com/zz85n * @author Mugen87 / github.com/Mugen87n *n * Parametric Surfaces Geometryn * based on the brilliant article by @prideout prideout.net/blog/?p=44n */n// ParametricGeometrynnfunction ParametricGeometry(func, slices, stacks) {n Geometry.call(this);n this.type = 'ParametricGeometry';n this.parameters = {n func: func,n slices: slices,n stacks: stacksn };n this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));n this.mergeVertices();n}nnParametricGeometry.prototype = Object.create(Geometry.prototype);nParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometrynnfunction ParametricBufferGeometry(func, slices, stacks) {n BufferGeometry.call(this);n this.type = 'ParametricBufferGeometry';n this.parameters = {n func: func,n slices: slices,n stacks: stacksn }; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = [];n var EPS = 0.00001;n var normal = new Vector3();n var p0 = new Vector3(),n p1 = new Vector3();n var pu = new Vector3(),n pv = new Vector3();n var i, j;nn if (func.length < 3) {n console.error('THREE.ParametricGeometry: Function
must now modify a Vector3 as third parameter.');n } // generate vertices, normals and uvsnnn var sliceCount = slices + 1;nn for (i = 0; i <= stacks; i++) {n var v = i / stacks;nn for (j = 0; j <= slices; j++) {n var u = j / slices; // vertexnn func(u, v, p0);n vertices.push(p0.x, p0.y, p0.z); // normaln // approximate tangent vectors via finite differencesnn if (u - EPS >= 0) {n func(u - EPS, v, p1);n pu.subVectors(p0, p1);n } else {n func(u + EPS, v, p1);n pu.subVectors(p1, p0);n }nn if (v - EPS >= 0) {n func(u, v - EPS, p1);n pv.subVectors(p0, p1);n } else {n func(u, v + EPS, p1);n pv.subVectors(p1, p0);n } // cross product of tangent vectors returns surface normalnnn normal.crossVectors(pu, pv).normalize();n normals.push(normal.x, normal.y, normal.z); // uvnn uvs.push(u, v);n }n } // generate indicesnnn for (i = 0; i < stacks; i++) {n for (j = 0; j < slices; j++) {n var a = i * sliceCount + j;n var b = i * sliceCount + j + 1;n var c = (i + 1) * sliceCount + j + 1;n var d = (i + 1) * sliceCount + j; // faces one and twonn indices.push(a, b, d);n indices.push(b, c, d);n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));n}nnParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;n/**n * @author clockworkgeek / github.com/clockworkgeekn * @author timothypratley / github.com/timothypratleyn * @author WestLangley / github.com/WestLangleyn * @author Mugen87 / github.com/Mugen87n */n// PolyhedronGeometrynnfunction PolyhedronGeometry(vertices, indices, radius, detail) {n Geometry.call(this);n this.type = 'PolyhedronGeometry';n this.parameters = {n vertices: vertices,n indices: indices,n radius: radius,n detail: detailn };n this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));n this.mergeVertices();n}nnPolyhedronGeometry.prototype = Object.create(Geometry.prototype);nPolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometrynnfunction PolyhedronBufferGeometry(vertices, indices, radius, detail) {n BufferGeometry.call(this);n this.type = 'PolyhedronBufferGeometry';n this.parameters = {n vertices: vertices,n indices: indices,n radius: radius,n detail: detailn };n radius = radius || 1;n detail = detail || 0; // default buffer datann var vertexBuffer = [];n var uvBuffer = []; // the subdivision creates the vertex buffer datann subdivide(detail); // all vertices should lie on a conceptual sphere with a given radiusnn applyRadius(radius); // finally, create the uv datann generateUVs(); // build non-indexed geometrynn this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));n this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));n this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));nn if (detail === 0) {n this.computeVertexNormals(); // flat normalsn } else {n this.normalizeNormals(); // smooth normalsn } // helper functionsnnn function subdivide(detail) {n var a = new Vector3();n var b = new Vector3();n var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail valuenn for (var i = 0; i < indices.length; i += 3) {n // get the vertices of the facen getVertexByIndex(indices[i + 0], a);n getVertexByIndex(indices[i + 1], b);n getVertexByIndex(indices[i + 2], c); // perform subdivisionnn subdivideFace(a, b, c, detail);n }n }nn function subdivideFace(a, b, c, detail) {n var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivisionnn var v = [];n var i, j; // construct all of the vertices for this subdivisionnn for (i = 0; i <= cols; i++) {n v = [];n var aj = a.clone().lerp(c, i / cols);n var bj = b.clone().lerp(c, i / cols);n var rows = cols - i;nn for (j = 0; j <= rows; j++) {n if (j === 0 && i === cols) {n v[j] = aj;n } else {n v[j] = aj.clone().lerp(bj, j / rows);n }n }n } // construct all of the facesnnn for (i = 0; i < cols; i++) {n for (j = 0; j < 2 * (cols - i) - 1; j++) {n var k = Math.floor(j / 2);nn if (j % 2 === 0) {n pushVertex(v[k + 1]);n pushVertex(v[i + 1]);n pushVertex(v[k]);n } else {n pushVertex(v[k + 1]);n pushVertex(v[i + 1][k + 1]);n pushVertex(v[i + 1]);n }n }n }n }nn function applyRadius(radius) {n var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertexnn for (var i = 0; i < vertexBuffer.length; i += 3) {n vertex.x = vertexBuffer[i + 0];n vertex.y = vertexBuffer[i + 1];n vertex.z = vertexBuffer[i + 2];n vertex.normalize().multiplyScalar(radius);n vertexBuffer[i + 0] = vertex.x;n vertexBuffer[i + 1] = vertex.y;n vertexBuffer[i + 2] = vertex.z;n }n }nn function generateUVs() {n var vertex = new Vector3();nn for (var i = 0; i < vertexBuffer.length; i += 3) {n vertex.x = vertexBuffer[i + 0];n vertex.y = vertexBuffer[i + 1];n vertex.z = vertexBuffer[i + 2];n var u = azimuth(vertex) / 2 / Math.PI + 0.5;n var v = inclination(vertex) / Math.PI + 0.5;n uvBuffer.push(u, 1 - v);n }nn correctUVs();n correctSeam();n }nn function correctSeam() {n // handle case when face straddles the seam, see #3269n for (var i = 0; i < uvBuffer.length; i += 6) {n // uv data of a single facen var x0 = uvBuffer[i + 0];n var x1 = uvBuffer[i + 2];n var x2 = uvBuffer[i + 4];n var max = Math.max(x0, x1, x2);n var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrarynn if (max > 0.9 && min < 0.1) {n if (x0 < 0.2) uvBuffer[i + 0] += 1;n if (x1 < 0.2) uvBuffer[i + 2] += 1;n if (x2 < 0.2) uvBuffer[i + 4] += 1;n }n }n }nn function pushVertex(vertex) {n vertexBuffer.push(vertex.x, vertex.y, vertex.z);n }nn function getVertexByIndex(index, vertex) {n var stride = index * 3;n vertex.x = vertices[stride + 0];n vertex.y = vertices[stride + 1];n vertex.z = vertices[stride + 2];n }nn function correctUVs() {n var a = new Vector3();n var b = new Vector3();n var c = new Vector3();n var centroid = new Vector3();n var uvA = new Vector2();n var uvB = new Vector2();n var uvC = new Vector2();nn for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {n a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);n b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);n c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);n uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);n uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);n uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);n centroid.copy(a).add(b).add©.divideScalar(3);n var azi = azimuth(centroid);n correctUV(uvA, j + 0, a, azi);n correctUV(uvB, j + 2, b, azi);n correctUV(uvC, j + 4, c, azi);n }n }nn function correctUV(uv, stride, vector, azimuth) {n if (azimuth < 0 && uv.x === 1) {n uvBuffer = uv.x - 1;n }nn if (vector.x === 0 && vector.z === 0) {n uvBuffer = azimuth / 2 / Math.PI + 0.5;n }n } // Angle around the Y axis, counter-clockwise when looking from above.nnn function azimuth(vector) {n return Math.atan2(vector.z, -vector.x);n } // Angle above the XZ plane.nnn function inclination(vector) {n return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));n }n}nnPolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nPolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;n/**n * @author timothypratley / github.com/timothypratleyn * @author Mugen87 / github.com/Mugen87n */n// TetrahedronGeometrynnfunction TetrahedronGeometry(radius, detail) {n Geometry.call(this);n this.type = 'TetrahedronGeometry';n this.parameters = {n radius: radius,n detail: detailn };n this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));n this.mergeVertices();n}nnTetrahedronGeometry.prototype = Object.create(Geometry.prototype);nTetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometrynnfunction TetrahedronBufferGeometry(radius, detail) {n var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];n var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];n PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);n this.type = 'TetrahedronBufferGeometry';n this.parameters = {n radius: radius,n detail: detailn };n}nnTetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);nTetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;n/**n * @author timothypratley / github.com/timothypratleyn * @author Mugen87 / github.com/Mugen87n */n// OctahedronGeometrynnfunction OctahedronGeometry(radius, detail) {n Geometry.call(this);n this.type = 'OctahedronGeometry';n this.parameters = {n radius: radius,n detail: detailn };n this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));n this.mergeVertices();n}nnOctahedronGeometry.prototype = Object.create(Geometry.prototype);nOctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometrynnfunction OctahedronBufferGeometry(radius, detail) {n var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];n var indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];n PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);n this.type = 'OctahedronBufferGeometry';n this.parameters = {n radius: radius,n detail: detailn };n}nnOctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);nOctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;n/**n * @author timothypratley / github.com/timothypratleyn * @author Mugen87 / github.com/Mugen87n */n// IcosahedronGeometrynnfunction IcosahedronGeometry(radius, detail) {n Geometry.call(this);n this.type = 'IcosahedronGeometry';n this.parameters = {n radius: radius,n detail: detailn };n this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));n this.mergeVertices();n}nnIcosahedronGeometry.prototype = Object.create(Geometry.prototype);nIcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometrynnfunction IcosahedronBufferGeometry(radius, detail) {n var t = (1 + Math.sqrt(5)) / 2;n var vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];n var indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];n PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);n this.type = 'IcosahedronBufferGeometry';n this.parameters = {n radius: radius,n detail: detailn };n}nnIcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);nIcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;n/**n * @author Abe Pazos / hamoid.comn * @author Mugen87 / github.com/Mugen87n */n// DodecahedronGeometrynnfunction DodecahedronGeometry(radius, detail) {n Geometry.call(this);n this.type = 'DodecahedronGeometry';n this.parameters = {n radius: radius,n detail: detailn };n this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));n this.mergeVertices();n}nnDodecahedronGeometry.prototype = Object.create(Geometry.prototype);nDodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometrynnfunction DodecahedronBufferGeometry(radius, detail) {n var t = (1 + Math.sqrt(5)) / 2;n var r = 1 / t;n var vertices = [// (±1, ±1, ±1)n -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/φ, ±φ)n 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)n -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)n -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];n var indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];n PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);n this.type = 'DodecahedronBufferGeometry';n this.parameters = {n radius: radius,n detail: detailn };n}nnDodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);nDodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;n/**n * @author oosmoxiecode / github.com/oosmoxiecoden * @author WestLangley / github.com/WestLangleyn * @author zz85 / github.com/zz85n * @author miningold / github.com/miningoldn * @author jonobr1 / github.com/jonobr1n * @author Mugen87 / github.com/Mugen87n *n */n// TubeGeometrynnfunction TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {n Geometry.call(this);n this.type = 'TubeGeometry';n this.parameters = {n path: path,n tubularSegments: tubularSegments,n radius: radius,n radialSegments: radialSegments,n closed: closedn };n if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');n var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internalsnn this.tangents = bufferGeometry.tangents;n this.normals = bufferGeometry.normals;n this.binormals = bufferGeometry.binormals; // create geometrynn this.fromBufferGeometry(bufferGeometry);n this.mergeVertices();n}nnTubeGeometry.prototype = Object.create(Geometry.prototype);nTubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometrynnfunction TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {n BufferGeometry.call(this);n this.type = 'TubeBufferGeometry';n this.parameters = {n path: path,n tubularSegments: tubularSegments,n radius: radius,n radialSegments: radialSegments,n closed: closedn };n tubularSegments = tubularSegments || 64;n radius = radius || 1;n radialSegments = radialSegments || 8;n closed = closed || false;n var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internalsnn this.tangents = frames.tangents;n this.normals = frames.normals;n this.binormals = frames.binormals; // helper variablesnn var vertex = new Vector3();n var normal = new Vector3();n var uv = new Vector2();n var P = new Vector3();n var i, j; // buffernn var vertices = [];n var normals = [];n var uvs = [];n var indices = []; // create buffer datann generateBufferData(); // build geometrynn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functionsnn function generateBufferData() {n for (i = 0; i < tubularSegments; i++) {n generateSegment(i);n } // if the geometry is not closed, generate the last row of vertices and normalsn // at the regular position on the given pathn //n // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)nnn generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.n // this makes it easy compute correct values for closed geometriesnn generateUVs(); // finally create facesnn generateIndices();n }nn function generateSegment(i) {n // we use getPointAt to sample evenly distributed points from the given pathn P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormalnn var N = frames.normals;n var B = frames.binormals; // generate normals and vertices for the current segmentnn for (j = 0; j <= radialSegments; j++) {n var v = j / radialSegments * Math.PI * 2;n var sin = Math.sin(v);n var cos = -Math.cos(v); // normalnn normal.x = cos * N.x + sin * B.x;n normal.y = cos * N.y + sin * B.y;n normal.z = cos * N.z + sin * B.z;n normal.normalize();n normals.push(normal.x, normal.y, normal.z); // vertexnn vertex.x = P.x + radius * normal.x;n vertex.y = P.y + radius * normal.y;n vertex.z = P.z + radius * normal.z;n vertices.push(vertex.x, vertex.y, vertex.z);n }n }nn function generateIndices() {n for (j = 1; j <= tubularSegments; j++) {n for (i = 1; i <= radialSegments; i++) {n var a = (radialSegments + 1) * (j - 1) + (i - 1);n var b = (radialSegments + 1) * j + (i - 1);n var c = (radialSegments + 1) * j + i;n var d = (radialSegments + 1) * (j - 1) + i; // facesnn indices.push(a, b, d);n indices.push(b, c, d);n }n }n }nn function generateUVs() {n for (i = 0; i <= tubularSegments; i++) {n for (j = 0; j <= radialSegments; j++) {n uv.x = i / tubularSegments;n uv.y = j / radialSegments;n uvs.push(uv.x, uv.y);n }n }n }n}nnTubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nTubeBufferGeometry.prototype.constructor = TubeBufferGeometry;nnTubeBufferGeometry.prototype.toJSON = function () {n var data = BufferGeometry.prototype.toJSON.call(this);n data.path = this.parameters.path.toJSON();n return data;n};n/**n * @author oosmoxiecoden * @author Mugen87 / github.com/Mugen87n *n * based on www.blackpawn.com/texts/pqtorus/n */n// TorusKnotGeometrynnnfunction TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {n Geometry.call(this);n this.type = 'TorusKnotGeometry';n this.parameters = {n radius: radius,n tube: tube,n tubularSegments: tubularSegments,n radialSegments: radialSegments,n p: p,n q: qn };n if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');n this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));n this.mergeVertices();n}nnTorusKnotGeometry.prototype = Object.create(Geometry.prototype);nTorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometrynnfunction TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {n BufferGeometry.call(this);n this.type = 'TorusKnotBufferGeometry';n this.parameters = {n radius: radius,n tube: tube,n tubularSegments: tubularSegments,n radialSegments: radialSegments,n p: p,n q: qn };n radius = radius || 1;n tube = tube || 0.4;n tubularSegments = Math.floor(tubularSegments) || 64;n radialSegments = Math.floor(radialSegments) || 8;n p = p || 2;n q = q || 3; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // helper variablesnn var i, j;n var vertex = new Vector3();n var normal = new Vector3();n var P1 = new Vector3();n var P2 = new Vector3();n var B = new Vector3();n var T = new Vector3();n var N = new Vector3(); // generate vertices, normals and uvsnn for (i = 0; i <= tubularSegments; ++i) {n // the radian "u" is used to calculate the position on the torus curve of the current tubular segementn var u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.n // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positionsnn calculatePositionOnCurve(u, p, q, radius, P1);n calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basisnn T.subVectors(P2, P1);n N.addVectors(P2, P1);n B.crossVectors(T, N);n N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use itnn B.normalize();n N.normalize();nn for (j = 0; j <= radialSegments; ++j) {n // now calculate the vertices. they are nothing more than an extrusion of the torus curve.n // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.n var v = j / radialSegments * Math.PI * 2;n var cx = -tube * Math.cos(v);n var cy = tube * Math.sin(v); // now calculate the final vertex position.n // first we orient the extrusion with our basis vectos, then we add it to the current position on the curvenn vertex.x = P1.x + (cx * N.x + cy * B.x);n vertex.y = P1.y + (cx * N.y + cy * B.y);n vertex.z = P1.z + (cx * N.z + cy * B.z);n vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)nn normal.subVectors(vertex, P1).normalize();n normals.push(normal.x, normal.y, normal.z); // uvnn uvs.push(i / tubularSegments);n uvs.push(j / radialSegments);n }n } // generate indicesnnn for (j = 1; j <= tubularSegments; j++) {n for (i = 1; i <= radialSegments; i++) {n // indicesn var a = (radialSegments + 1) * (j - 1) + (i - 1);n var b = (radialSegments + 1) * j + (i - 1);n var c = (radialSegments + 1) * j + i;n var d = (radialSegments + 1) * (j - 1) + i; // facesnn indices.push(a, b, d);n indices.push(b, c, d);n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curvenn function calculatePositionOnCurve(u, p, q, radius, position) {n var cu = Math.cos(u);n var su = Math.sin(u);n var quOverP = q / p * u;n var cs = Math.cos(quOverP);n position.x = radius * (2 + cs) * 0.5 * cu;n position.y = radius * (2 + cs) * su * 0.5;n position.z = radius * Math.sin(quOverP) * 0.5;n }n}nnTorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nTorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;n/**n * @author oosmoxiecoden * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n */n// TorusGeometrynnfunction TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {n Geometry.call(this);n this.type = 'TorusGeometry';n this.parameters = {n radius: radius,n tube: tube,n radialSegments: radialSegments,n tubularSegments: tubularSegments,n arc: arcn };n this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));n this.mergeVertices();n}nnTorusGeometry.prototype = Object.create(Geometry.prototype);nTorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometrynnfunction TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {n BufferGeometry.call(this);n this.type = 'TorusBufferGeometry';n this.parameters = {n radius: radius,n tube: tube,n radialSegments: radialSegments,n tubularSegments: tubularSegments,n arc: arcn };n radius = radius || 1;n tube = tube || 0.4;n radialSegments = Math.floor(radialSegments) || 8;n tubularSegments = Math.floor(tubularSegments) || 6;n arc = arc || Math.PI * 2; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // helper variablesnn var center = new Vector3();n var vertex = new Vector3();n var normal = new Vector3();n var j, i; // generate vertices, normals and uvsnn for (j = 0; j <= radialSegments; j++) {n for (i = 0; i <= tubularSegments; i++) {n var u = i / tubularSegments * arc;n var v = j / radialSegments * Math.PI * 2; // vertexnn vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);n vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);n vertex.z = tube * Math.sin(v);n vertices.push(vertex.x, vertex.y, vertex.z); // normalnn center.x = radius * Math.cos(u);n center.y = radius * Math.sin(u);n normal.subVectors(vertex, center).normalize();n normals.push(normal.x, normal.y, normal.z); // uvnn uvs.push(i / tubularSegments);n uvs.push(j / radialSegments);n }n } // generate indicesnnn for (j = 1; j <= radialSegments; j++) {n for (i = 1; i <= tubularSegments; i++) {n // indicesn var a = (tubularSegments + 1) * j + i - 1;n var b = (tubularSegments + 1) * (j - 1) + i - 1;n var c = (tubularSegments + 1) * (j - 1) + i;n var d = (tubularSegments + 1) * j + i; // facesnn indices.push(a, b, d);n indices.push(b, c, d);n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));n}nnTorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nTorusBufferGeometry.prototype.constructor = TorusBufferGeometry;n/**n * @author Mugen87 / github.com/Mugen87n * Port from github.com/mapbox/earcut (v2.1.5)n */nnvar Earcut = {n triangulate: function triangulate(data, holeIndices, dim) {n dim = dim || 2;n var hasHoles = holeIndices && holeIndices.length,n outerLen = hasHoles ? holeIndices * dim : data.length,n outerNode = linkedList(data, 0, outerLen, dim, true),n triangles = [];n if (!outerNode || outerNode.next === outerNode.prev) return triangles;n var minX, minY, maxX, maxY, x, y, invSize;n 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 bboxnn if (data.length > 80 * dim) {n minX = maxX = data;n minY = maxY = data;nn for (var i = dim; i < outerLen; i += dim) {n x = data;n y = data[i + 1];n if (x < minX) minX = x;n if (y < minY) minY = y;n if (x > maxX) maxX = x;n if (y > maxY) maxY = y;n } // minX, minY and invSize are later used to transform coords into integers for z-order calculationnnn invSize = Math.max(maxX - minX, maxY - minY);n invSize = invSize !== 0 ? 1 / invSize : 0;n }nn earcutLinked(outerNode, triangles, dim, minX, minY, invSize);n return triangles;n }n}; // create a circular doubly linked list from polygon points in the specified winding ordernnfunction linkedList(data, start, end, dim, clockwise) {n var i, last;nn if (clockwise === signedArea(data, start, end, dim) > 0) {n for (i = start; i < end; i += dim) {n last = insertNode(i, data, data[i + 1], last);n }n } else {n for (i = end - dim; i >= start; i -= dim) {n last = insertNode(i, data, data[i + 1], last);n }n }nn if (last && equals(last, last.next)) {n removeNode(last);n last = last.next;n }nn return last;n} // eliminate colinear or duplicate pointsnnnfunction filterPoints(start, end) {n if (!start) return start;n if (!end) end = start;n var p = start,n again;nn do {n again = false;nn if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {n removeNode(p);n p = end = p.prev;n if (p === p.next) break;n again = true;n } else {n p = p.next;n }n } while (again || p !== end);nn return end;n} // main ear slicing loop which triangulates a polygon (given as a linked list)nnnfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {n if (!ear) return; // interlink polygon nodes in z-ordernn if (!pass && invSize) indexCurve(ear, minX, minY, invSize);n var stop = ear,n prev,n next; // iterate through ears, slicing them one by onenn while (ear.prev !== ear.next) {n prev = ear.prev;n next = ear.next;nn if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {n // cut off the trianglen triangles.push(prev.i / dim);n triangles.push(ear.i / dim);n triangles.push(next.i / dim);n removeNode(ear); // skipping the next vertex leads to less sliver trianglesnn ear = next.next;n stop = next.next;n continue;n }nn ear = next; // if we looped through the whole remaining polygon and can't find any more earsnn if (ear === stop) {n // try filtering points and slicing againn if (!pass) {n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locallyn } else if (pass === 1) {n ear = cureLocalIntersections(ear, triangles, dim);n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into twon } else if (pass === 2) {n splitEarcut(ear, triangles, dim, minX, minY, invSize);n }nn break;n }n }n} // check whether a polygon node forms a valid ear with adjacent nodesnnnfunction isEar(ear) {n var a = ear.prev,n b = ear,n c = ear.next;n if (area(a, b, c) >= 0) return false; // reflex, can't be an earn // now make sure we don't have other points inside the potential earnn var p = ear.next.next;nn while (p !== ear.prev) {n 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;n p = p.next;n }nn return true;n}nnfunction isEarHashed(ear, minX, minY, invSize) {n var a = ear.prev,n b = ear,n c = ear.next;n if (area(a, b, c) >= 0) return false; // reflex, can't be an earn // triangle bbox; min & max are calculated like this for speednn var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,n minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,n maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,n maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;nn var minZ = zOrder(minTX, minTY, minX, minY, invSize),n maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);n var p = ear.prevZ,n n = ear.nextZ; // look for points inside the triangle in both directionsnn while (p && p.z >= minZ && n && n.z <= maxZ) {n 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;n p = p.prevZ;n 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 = n.nextZ;n } // look for remaining points in decreasing z-ordernnn while (p && p.z >= minZ) {n 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;n p = p.prevZ;n } // look for remaining points in increasing z-ordernnn while (n && n.z <= maxZ) {n 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 = n.nextZ;n }nn return true;n} // go through all polygon nodes and cure small local self-intersectionsnnnfunction cureLocalIntersections(start, triangles, dim) {n var p = start;nn do {n var a = p.prev,n b = p.next.next;nn if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {n triangles.push(a.i / dim);n triangles.push(p.i / dim);n triangles.push(b.i / dim); // remove two nodes involvednn removeNode(p);n removeNode(p.next);n p = start = b;n }nn p = p.next;n } while (p !== start);nn return p;n} // try splitting polygon into two and triangulate them independentlynnnfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {n // look for a valid diagonal that divides the polygon into twon var a = start;nn do {n var b = a.next.next;nn while (b !== a.prev) {n if (a.i !== b.i && isValidDiagonal(a, b)) {n // split the polygon in two by the diagonaln var c = splitPolygon(a, b); // filter colinear points around the cutsnn a = filterPoints(a, a.next);n c = filterPoints(c, c.next); // run earcut on each halfnn earcutLinked(a, triangles, dim, minX, minY, invSize);n earcutLinked(c, triangles, dim, minX, minY, invSize);n return;n }nn b = b.next;n }nn a = a.next;n } while (a !== start);n} // link every hole into the outer loop, producing a single-ring polygon without holesnnnfunction eliminateHoles(data, holeIndices, outerNode, dim) {n var queue = [],n i,n len,n start,n end,n list;nn for (i = 0, len = holeIndices.length; i < len; i++) {n start = holeIndices * dim;n end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;n list = linkedList(data, start, end, dim, false);n if (list === list.next) list.steiner = true;n queue.push(getLeftmost(list));n }nn queue.sort(compareX); // process holes from left to rightnn for (i = 0; i < queue.length; i++) {n eliminateHole(queue, outerNode);n outerNode = filterPoints(outerNode, outerNode.next);n }nn return outerNode;n}nnfunction compareX(a, b) {n return a.x - b.x;n} // find a bridge between vertices that connects hole with an outer ring and and link itnnnfunction eliminateHole(hole, outerNode) {n outerNode = findHoleBridge(hole, outerNode);nn if (outerNode) {n var b = splitPolygon(outerNode, hole);n filterPoints(b, b.next);n }n} // David Eberly's algorithm for finding a bridge between hole and outer polygonnnnfunction findHoleBridge(hole, outerNode) {n var p = outerNode,n hx = hole.x,n hy = hole.y,n qx = -Infinity,n m; // find a segment intersected by a ray from the hole's leftmost point to the left;n // segment's endpoint with lesser x will be potential connection pointnn do {n if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {n var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);nn if (x <= hx && x > qx) {n qx = x;nn if (x === hx) {n if (hy === p.y) return p;n if (hy === p.next.y) return p.next;n }nn m = p.x < p.next.x ? p : p.next;n }n }nn p = p.next;n } while (p !== outerNode);nn if (!m) return null;n if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpointn // look for points inside the triangle of hole point, segment intersection and endpoint;n // if there are no points found, we have a valid connection;n // otherwise choose the point of the minimum angle with the ray as connection pointnn var stop = m,n mx = m.x,n my = m.y,n tanMin = Infinity,n tan;n p = m.next;nn while (p !== stop) {n 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)) {n tan = Math.abs(hy - p.y) / (hx - p.x); // tangentialnn if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {n m = p;n tanMin = tan;n }n }nn p = p.next;n }nn return m;n} // interlink polygon nodes in z-ordernnnfunction indexCurve(start, minX, minY, invSize) {n var p = start;nn do {n if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);n p.prevZ = p.prev;n p.nextZ = p.next;n p = p.next;n } while (p !== start);nn p.prevZ.nextZ = null;n p.prevZ = null;n sortLinked(p);n} // Simon Tatham's linked list merge sort algorithmn// www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.htmlnnnfunction sortLinked(list) {n var i,n p,n q,n e,n tail,n numMerges,n pSize,n qSize,n inSize = 1;nn do {n p = list;n list = null;n tail = null;n numMerges = 0;nn while (p) {n numMerges++;n q = p;n pSize = 0;nn for (i = 0; i < inSize; i++) {n pSize++;n q = q.nextZ;n if (!q) break;n }nn qSize = inSize;nn while (pSize > 0 || qSize > 0 && q) {n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {n e = p;n p = p.nextZ;n pSize–;n } else {n e = q;n q = q.nextZ;n qSize–;n }nn if (tail) tail.nextZ = e;else list = e;n e.prevZ = tail;n tail = e;n }nn p = q;n }nn tail.nextZ = null;n inSize *= 2;n } while (numMerges > 1);nn return list;n} // z-order of a point given coords and inverse of the longer side of data bboxnnnfunction zOrder(x, y, minX, minY, invSize) {n // coords are transformed into non-negative 15-bit integer rangen x = 32767 * (x - minX) * invSize;n y = 32767 * (y - minY) * invSize;n x = (x | x << 8) & 0x00FF00FF;n x = (x | x << 4) & 0x0F0F0F0F;n x = (x | x << 2) & 0x33333333;n x = (x | x << 1) & 0x55555555;n y = (y | y << 8) & 0x00FF00FF;n y = (y | y << 4) & 0x0F0F0F0F;n y = (y | y << 2) & 0x33333333;n y = (y | y << 1) & 0x55555555;n return x | y << 1;n} // find the leftmost node of a polygon ringnnnfunction getLeftmost(start) {n var p = start,n leftmost = start;nn do {n if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;n p = p.next;n } while (p !== start);nn return leftmost;n} // check if a point lies within a convex trianglennnfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {n 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;n} // check if a diagonal between two polygon nodes is valid (lies in polygon interior)nnnfunction isValidDiagonal(a, b) {n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);n} // signed area of a trianglennnfunction area(p, q, r) {n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);n} // check if two points are equalnnnfunction equals(p1, p2) {n return p1.x === p2.x && p1.y === p2.y;n} // check if two segments intersectnnnfunction intersects(p1, q1, p2, q2) {n if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;n return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;n} // check if a polygon diagonal intersects any polygon segmentsnnnfunction intersectsPolygon(a, b) {n var p = a;nn do {n 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;n p = p.next;n } while (p !== a);nn return false;n} // check if a polygon diagonal is locally inside the polygonnnnfunction locallyInside(a, b) {n 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;n} // check if the middle point of a polygon diagonal is inside the polygonnnnfunction middleInside(a, b) {n var p = a,n inside = false,n px = (a.x + b.x) / 2,n py = (a.y + b.y) / 2;nn do {n 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;n p = p.next;n } while (p !== a);nn return inside;n} // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;n// if one belongs to the outer ring and another to a hole, it merges it into a single ringnnnfunction splitPolygon(a, b) {n var a2 = new Node(a.i, a.x, a.y),n b2 = new Node(b.i, b.x, b.y),n an = a.next,n bp = b.prev;n a.next = b;n b.prev = a;n a2.next = an;n an.prev = a2;n b2.next = a2;n a2.prev = b2;n bp.next = b2;n b2.prev = bp;n return b2;n} // create a node and optionally link it with previous one (in a circular doubly linked list)nnnfunction insertNode(i, x, y, last) {n var p = new Node(i, x, y);nn if (!last) {n p.prev = p;n p.next = p;n } else {n p.next = last.next;n p.prev = last;n last.next.prev = p;n last.next = p;n }nn return p;n}nnfunction removeNode(p) {n p.next.prev = p.prev;n p.prev.next = p.next;n if (p.prevZ) p.prevZ.nextZ = p.nextZ;n if (p.nextZ) p.nextZ.prevZ = p.prevZ;n}nnfunction Node(i, x, y) {n // vertex index in coordinates arrayn this.i = i; // vertex coordinatesnn this.x = x;n this.y = y; // previous and next vertex nodes in a polygon ringnn this.prev = null;n this.next = null; // z-order curve valuenn this.z = null; // previous and next nodes in z-ordernn this.prevZ = null;n this.nextZ = null; // indicates whether this is a steiner pointnn this.steiner = false;n}nnfunction signedArea(data, start, end, dim) {n var sum = 0;nn for (var i = start, j = end - dim; i < end; i += dim) {n sum += (data - data) * (data[i + 1] + data[j + 1]);n j = i;n }nn return sum;n}n/**n * @author zz85 / www.lab4games.net/zz85/blogn */nnnvar ShapeUtils = {n // calculate area of the contour polygonn area: function area(contour) {n var n = contour.length;n var a = 0.0;nn for (var p = n - 1, q = 0; q < n; p = q++) {n a += contour.x * contour.y - contour.x * contour.y;n }nn return a * 0.5;n },n isClockWise: function isClockWise(pts) {n return ShapeUtils.area(pts) < 0;n },n triangulateShape: function triangulateShape(contour, holes) {n var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, … ]nn var holeIndices = []; // array of hole indicesnn var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]nn removeDupEndPts(contour);n addContour(vertices, contour); //nn var holeIndex = contour.length;n holes.forEach(removeDupEndPts);nn for (var i = 0; i < holes.length; i++) {n holeIndices.push(holeIndex);n holeIndex += holes.length;n addContour(vertices, holes);n } //nnn var triangles = Earcut.triangulate(vertices, holeIndices); //nn for (var i = 0; i < triangles.length; i += 3) {n faces.push(triangles.slice(i, i + 3));n }nn return faces;n }n};nnfunction removeDupEndPts(points) {n var l = points.length;nn if (l > 2 && points[l - 1].equals(points)) {n points.pop();n }n}nnfunction addContour(vertices, contour) {n for (var i = 0; i < contour.length; i++) {n vertices.push(contour.x);n vertices.push(contour.y);n }n}n/**n * @author zz85 / www.lab4games.net/zz85/blogn *n * Creates extruded geometry from a path shape.n *n * parameters = {n *n * curveSegments: <int>, // number of points on the curvesn * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline toon * depth: <float>, // Depth to extrude the shapen *n * bevelEnabled: <bool>, // turn on beveln * bevelThickness: <float>, // how deep into the original shape bevel goesn * bevelSize: <float>, // how far from shape outline (including bevelOffset) is beveln * bevelOffset: <float>, // how far from shape outline does bevel startn * bevelSegments: <int>, // number of bevel layersn *n * extrudePath: <THREE.Curve> // curve to extrude shape alongn *n * UVGenerator: <Object> // object that provides UV generator functionsn *n * }n */n// ExtrudeGeometrynnnfunction ExtrudeGeometry(shapes, options) {n Geometry.call(this);n this.type = 'ExtrudeGeometry';n this.parameters = {n shapes: shapes,n options: optionsn };n this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));n this.mergeVertices();n}nnExtrudeGeometry.prototype = Object.create(Geometry.prototype);nExtrudeGeometry.prototype.constructor = ExtrudeGeometry;nnExtrudeGeometry.prototype.toJSON = function () {n var data = Geometry.prototype.toJSON.call(this);n var shapes = this.parameters.shapes;n var options = this.parameters.options;n return toJSON(shapes, options, data);n}; // ExtrudeBufferGeometrynnnfunction ExtrudeBufferGeometry(shapes, options) {n BufferGeometry.call(this);n this.type = 'ExtrudeBufferGeometry';n this.parameters = {n shapes: shapes,n options: optionsn };n shapes = Array.isArray(shapes) ? shapes : [shapes];n var scope = this;n var verticesArray = [];n var uvArray = [];nn for (var i = 0, l = shapes.length; i < l; i++) {n var shape = shapes;n addShape(shape);n } // build geometrynnn this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));n this.computeVertexNormals(); // functionsnn function addShape(shape) {n var placeholder = []; // optionsnn var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;n var steps = options.steps !== undefined ? options.steps : 1;n var depth = options.depth !== undefined ? options.depth : 100;n var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;n var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;n var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;n var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;n var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;n var extrudePath = options.extrudePath;n var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated optionsnn if (options.amount !== undefined) {n console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');n depth = options.amount;n } //nnn var extrudePts,n extrudeByPath = false;n var splineTube, binormal, normal, position2;nn if (extrudePath) {n extrudePts = extrudePath.getSpacedPoints(steps);n extrudeByPath = true;n bevelEnabled = false; // bevels not supported for path extrusionn // SETUP TNB variablesn // TODO1 - have a .isClosed in spline?nn splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);nn binormal = new Vector3();n normal = new Vector3();n position2 = new Vector3();n } // Safeguards if bevels are not enablednnn if (!bevelEnabled) {n bevelSegments = 0;n bevelThickness = 0;n bevelSize = 0;n bevelOffset = 0;n } // Variables initializationnnn var ahole, h, hl; // looping of holesnn var shapePoints = shape.extractPoints(curveSegments);n var vertices = shapePoints.shape;n var holes = shapePoints.holes;n var reverse = !ShapeUtils.isClockWise(vertices);nn if (reverse) {n vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe …nn for (h = 0, hl = holes.length; h < hl; h++) {n ahole = holes;nn if (ShapeUtils.isClockWise(ahole)) {n holes = ahole.reverse();n }n }n }nn var faces = ShapeUtils.triangulateShape(vertices, holes);n /* Vertices */nn var contour = vertices; // vertices has all points but contour has only points of circumferencenn for (h = 0, hl = holes.length; h < hl; h++) {n ahole = holes;n vertices = vertices.concat(ahole);n }nn function scalePt2(pt, vec, size) {n if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");n return vec.clone().multiplyScalar(size).add(pt);n }nn var b,n bs,n t,n z,n vert,n vlen = vertices.length,n face,n flen = faces.length; // Find directions for point movementnn function getBevelVec(inPt, inPrev, inNext) {n // computes for inPt the corresponding point inPt' on a new contourn // shifted by 1 unit (length of normalized vector) to the leftn // if we walk along contour clockwise, this new contour is outside the old onen //n // inPt' is the intersection of the two lines parallel to the twon // adjacent edges of inPt at a distance of 1 unit on the left side.n var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPtn // good reading for geometry algorithms (here: line-line intersection)n // geomalgorithms.com/a05-_intersect-1.htmlnn var v_prev_x = inPt.x - inPrev.x,n v_prev_y = inPt.y - inPrev.y;n var v_next_x = inNext.x - inPt.x,n v_next_y = inNext.y - inPt.y;n var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edgesnn var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;nn if (Math.abs(collinear0) > Number
.EPSILON) {n // not collinearn // length of vectors for normalizingn var v_prev_len = Math.sqrt(v_prev_lensq);n var v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the leftnn var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;n var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;n var ptNextShift_x = inNext.x - v_next_y / v_next_len;n var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection pointnn var sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection pointnn v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;n v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become uglyn // but prevent crazy spikesnn var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;nn if (v_trans_lensq <= 2) {n return new Vector2(v_trans_x, v_trans_y);n } else {n shrink_by = Math.sqrt(v_trans_lensq / 2);n }n } else {n // handle special case of collinear edgesn var direction_eq = false; // assumes: oppositenn if (v_prev_x > Number
.EPSILON) {n if (v_next_x > Number
.EPSILON) {n direction_eq = true;n }n } else {n if (v_prev_x < -Number.EPSILON) {n if (v_next_x < -Number.EPSILON) {n direction_eq = true;n }n } else {n if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {n direction_eq = true;n }n }n }nn if (direction_eq) {n // console.log("Warning: lines are a straight sequence");n v_trans_x = -v_prev_y;n v_trans_y = v_prev_x;n shrink_by = Math.sqrt(v_prev_lensq);n } else {n // console.log("Warning: lines are a straight spike");n v_trans_x = v_prev_x;n v_trans_y = v_prev_y;n shrink_by = Math.sqrt(v_prev_lensq / 2);n }n }nn return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);n }nn var contourMovements = [];nn for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {n if (j === il) j = 0;n if (k === il) k = 0; // (j)—(i)—(k)n // console.log('i,j,k', i, j , k)nn contourMovements = getBevelVec(contour, contour, contour);n }nn var holesMovements = [],n oneHoleMovements,n verticesMovements = contourMovements.concat();nn for (h = 0, hl = holes.length; h < hl; h++) {n ahole = holes;n oneHoleMovements = [];nn for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {n if (j === il) j = 0;n if (k === il) k = 0; // (j)—(i)—(k)nn oneHoleMovements = getBevelVec(ahole, ahole, ahole);n }nn holesMovements.push(oneHoleMovements);n verticesMovements = verticesMovements.concat(oneHoleMovements);n } // Loop bevelSegments, 1 for the front, 1 for the backnnn for (b = 0; b < bevelSegments; b++) {n //for ( b = bevelSegments; b > 0; b – ) {n t = b / bevelSegments;n z = bevelThickness * Math.cos(t * Math.PI / 2);n bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shapenn for (i = 0, il = contour.length; i < il; i++) {n vert = scalePt2(contour, contourMovements, bs);n v(vert.x, vert.y, -z);n } // expand holesnnn for (h = 0, hl = holes.length; h < hl; h++) {n ahole = holes;n oneHoleMovements = holesMovements;nn for (i = 0, il = ahole.length; i < il; i++) {n vert = scalePt2(ahole, oneHoleMovements, bs);n v(vert.x, vert.y, -z);n }n }n }nn bs = bevelSize + bevelOffset; // Back facing verticesnn for (i = 0; i < vlen; i++) {n vert = bevelEnabled ? scalePt2(vertices, verticesMovements, bs) : vertices;nn if (!extrudeByPath) {n v(vert.x, vert.y, 0);n } else {n // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );n normal.copy(splineTube.normals).multiplyScalar(vert.x);n binormal.copy(splineTube.binormals).multiplyScalar(vert.y);n position2.copy(extrudePts).add(normal).add(binormal);n v(position2.x, position2.y, position2.z);n }n } // Add stepped vertices…n // Including front facing verticesnnn var s;nn for (s = 1; s <= steps; s++) {n for (i = 0; i < vlen; i++) {n vert = bevelEnabled ? scalePt2(vertices, verticesMovements, bs) : vertices;nn if (!extrudeByPath) {n v(vert.x, vert.y, depth / steps * s);n } else {n // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );n normal.copy(splineTube.normals).multiplyScalar(vert.x);n binormal.copy(splineTube.binormals).multiplyScalar(vert.y);n position2.copy(extrudePts).add(normal).add(binormal);n v(position2.x, position2.y, position2.z);n }n }n } // Add bevel segments planesn //for ( b = 1; b <= bevelSegments; b ++ ) {nnn for (b = bevelSegments - 1; b >= 0; b–) {n t = b / bevelSegments;n z = bevelThickness * Math.cos(t * Math.PI / 2);n bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shapenn for (i = 0, il = contour.length; i < il; i++) {n vert = scalePt2(contour, contourMovements, bs);n v(vert.x, vert.y, depth + z);n } // expand holesnnn for (h = 0, hl = holes.length; h < hl; h++) {n ahole = holes;n oneHoleMovements = holesMovements;nn for (i = 0, il = ahole.length; i < il; i++) {n vert = scalePt2(ahole, oneHoleMovements, bs);nn if (!extrudeByPath) {n v(vert.x, vert.y, depth + z);n } else {n v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);n }n }n }n }n /* Faces */n // Top and bottom facesnnn buildLidFaces(); // Sides facesnn buildSideFaces(); ///// Internal functionsnn function buildLidFaces() {n var start = verticesArray.length / 3;nn if (bevelEnabled) {n var layer = 0; // steps + 1nn var offset = vlen * layer; // Bottom facesnn for (i = 0; i < flen; i++) {n face = faces;n f3(face + offset, face + offset, face + offset);n }nn layer = steps + bevelSegments * 2;n offset = vlen * layer; // Top facesnn for (i = 0; i < flen; i++) {n face = faces;n f3(face + offset, face + offset, face + offset);n }n } else {n // Bottom facesn for (i = 0; i < flen; i++) {n face = faces;n f3(face, face, face);n } // Top facesnnn for (i = 0; i < flen; i++) {n face = faces;n f3(face + vlen * steps, face + vlen * steps, face + vlen * steps);n }n }nn scope.addGroup(start, verticesArray.length / 3 - start, 0);n } // Create faces for the z-sides of the shapennn function buildSideFaces() {n var start = verticesArray.length / 3;n var layeroffset = 0;n sidewalls(contour, layeroffset);n layeroffset += contour.length;nn for (h = 0, hl = holes.length; h < hl; h++) {n ahole = holes;n sidewalls(ahole, layeroffset); //, truenn layeroffset += ahole.length;n }nn scope.addGroup(start, verticesArray.length / 3 - start, 1);n }nn function sidewalls(contour, layeroffset) {n var j, k;n i = contour.length;nn while (–i >= 0) {n j = i;n k = i - 1;n if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);nn var s = 0,n sl = steps + bevelSegments * 2;nn for (s = 0; s < sl; s++) {n var slen1 = vlen * s;n var slen2 = vlen * (s + 1);n var a = layeroffset + j + slen1,n b = layeroffset + k + slen1,n c = layeroffset + k + slen2,n d = layeroffset + j + slen2;n f4(a, b, c, d);n }n }n }nn function v(x, y, z) {n placeholder.push(x);n placeholder.push(y);n placeholder.push(z);n }nn function f3(a, b, c) {n addVertex(a);n addVertex(b);n addVertex©;n var nextIndex = verticesArray.length / 3;n var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);n addUV(uvs);n addUV(uvs);n addUV(uvs);n }nn function f4(a, b, c, d) {n addVertex(a);n addVertex(b);n addVertex(d);n addVertex(b);n addVertex©;n addVertex(d);n var nextIndex = verticesArray.length / 3;n var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);n addUV(uvs);n addUV(uvs);n addUV(uvs);n addUV(uvs);n addUV(uvs);n addUV(uvs);n }nn function addVertex(index) {n verticesArray.push(placeholder[index * 3 + 0]);n verticesArray.push(placeholder[index * 3 + 1]);n verticesArray.push(placeholder[index * 3 + 2]);n }nn function addUV(vector2) {n uvArray.push(vector2.x);n uvArray.push(vector2.y);n }n }n}nnExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;nnExtrudeBufferGeometry.prototype.toJSON = function () {n var data = BufferGeometry.prototype.toJSON.call(this);n var shapes = this.parameters.shapes;n var options = this.parameters.options;n return toJSON(shapes, options, data);n}; //nnnvar WorldUVGenerator = {n generateTopUV: function generateTopUV(geometry, vertices, indexA, indexB, indexC) {n var a_x = vertices[indexA * 3];n var a_y = vertices[indexA * 3 + 1];n var b_x = vertices[indexB * 3];n var b_y = vertices[indexB * 3 + 1];n var c_x = vertices[indexC * 3];n var c_y = vertices[indexC * 3 + 1];n return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];n },n generateSideWallUV: function generateSideWallUV(geometry, vertices, indexA, indexB, indexC, indexD) {n var a_x = vertices[indexA * 3];n var a_y = vertices[indexA * 3 + 1];n var a_z = vertices[indexA * 3 + 2];n var b_x = vertices[indexB * 3];n var b_y = vertices[indexB * 3 + 1];n var b_z = vertices[indexB * 3 + 2];n var c_x = vertices[indexC * 3];n var c_y = vertices[indexC * 3 + 1];n var c_z = vertices[indexC * 3 + 2];n var d_x = vertices[indexD * 3];n var d_y = vertices[indexD * 3 + 1];n var d_z = vertices[indexD * 3 + 2];nn if (Math.abs(a_y - b_y) < 0.01) {n 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)];n } else {n 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)];n }n }n};nnfunction toJSON(shapes, options, data) {n //n data.shapes = [];nn if (Array.isArray(shapes)) {n for (var i = 0, l = shapes.length; i < l; i++) {n var shape = shapes;n data.shapes.push(shape.uuid);n }n } else {n data.shapes.push(shapes.uuid);n } //nnn if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();n return data;n}n/**n * @author zz85 / www.lab4games.net/zz85/blogn * @author alteredq / alteredqualia.com/n *n * Text = 3D Textn *n * parameters = {n * font: <THREE.Font>, // fontn *n * size: <float>, // size of the textn * height: <float>, // thickness to extrude textn * curveSegments: <int>, // number of points on the curvesn *n * bevelEnabled: <bool>, // turn on beveln * bevelThickness: <float>, // how deep into text bevel goesn * bevelSize: <float>, // how far from text outline (including bevelOffset) is beveln * bevelOffset: <float> // how far from text outline does bevel startn * }n */n// TextGeometrynnnfunction TextGeometry(text, parameters) {n Geometry.call(this);n this.type = 'TextGeometry';n this.parameters = {n text: text,n parameters: parametersn };n this.fromBufferGeometry(new TextBufferGeometry(text, parameters));n this.mergeVertices();n}nnTextGeometry.prototype = Object.create(Geometry.prototype);nTextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometrynnfunction TextBufferGeometry(text, parameters) {n parameters = parameters || {};n var font = parameters.font;nn if (!(font && font.isFont)) {n console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');n return new Geometry();n }nn var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry APInn parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaultsnn if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;n if (parameters.bevelSize === undefined) parameters.bevelSize = 8;n if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;n ExtrudeBufferGeometry.call(this, shapes, parameters);n this.type = 'TextBufferGeometry';n}nnTextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);nTextBufferGeometry.prototype.constructor = TextBufferGeometry;n/**n * @author mrdoob / mrdoob.com/n * @author benaadams / twitter.com/ben_a_adamsn * @author Mugen87 / github.com/Mugen87n */n// SphereGeometrynnfunction SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {n Geometry.call(this);n this.type = 'SphereGeometry';n this.parameters = {n radius: radius,n widthSegments: widthSegments,n heightSegments: heightSegments,n phiStart: phiStart,n phiLength: phiLength,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));n this.mergeVertices();n}nnSphereGeometry.prototype = Object.create(Geometry.prototype);nSphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometrynnfunction SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {n BufferGeometry.call(this);n this.type = 'SphereBufferGeometry';n this.parameters = {n radius: radius,n widthSegments: widthSegments,n heightSegments: heightSegments,n phiStart: phiStart,n phiLength: phiLength,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n radius = radius || 1;n widthSegments = Math.max(3, Math.floor(widthSegments) || 8);n heightSegments = Math.max(2, Math.floor(heightSegments) || 6);n phiStart = phiStart !== undefined ? phiStart : 0;n phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;n thetaStart = thetaStart !== undefined ? thetaStart : 0;n thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;n var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);n var ix, iy;n var index = 0;n var grid = [];n var vertex = new Vector3();n var normal = new Vector3(); // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // generate vertices, normals and uvsnn for (iy = 0; iy <= heightSegments; iy++) {n var verticesRow = [];n var v = iy / heightSegments; // special case for the polesnn var uOffset = 0;nn if (iy == 0 && thetaStart == 0) {n uOffset = 0.5 / widthSegments;n } else if (iy == heightSegments && thetaEnd == Math.PI) {n uOffset = -0.5 / widthSegments;n }nn for (ix = 0; ix <= widthSegments; ix++) {n var u = ix / widthSegments; // vertexnn vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);n vertex.y = radius * Math.cos(thetaStart + v * thetaLength);n vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);n vertices.push(vertex.x, vertex.y, vertex.z); // normalnn normal.copy(vertex).normalize();n normals.push(normal.x, normal.y, normal.z); // uvnn uvs.push(u + uOffset, 1 - v);n verticesRow.push(index++);n }nn grid.push(verticesRow);n } // indicesnnn for (iy = 0; iy < heightSegments; iy++) {n for (ix = 0; ix < widthSegments; ix++) {n var a = grid[ix + 1];n var b = grid[ix];n var c = grid[iy + 1];n var d = grid[iy + 1][ix + 1];n if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);n if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));n}nnSphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nSphereBufferGeometry.prototype.constructor = SphereBufferGeometry;n/**n * @author Kaleb Murphyn * @author Mugen87 / github.com/Mugen87n */n// RingGeometrynnfunction RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {n Geometry.call(this);n this.type = 'RingGeometry';n this.parameters = {n innerRadius: innerRadius,n outerRadius: outerRadius,n thetaSegments: thetaSegments,n phiSegments: phiSegments,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));n this.mergeVertices();n}nnRingGeometry.prototype = Object.create(Geometry.prototype);nRingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometrynnfunction RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {n BufferGeometry.call(this);n this.type = 'RingBufferGeometry';n this.parameters = {n innerRadius: innerRadius,n outerRadius: outerRadius,n thetaSegments: thetaSegments,n phiSegments: phiSegments,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n innerRadius = innerRadius || 0.5;n outerRadius = outerRadius || 1;n thetaStart = thetaStart !== undefined ? thetaStart : 0;n thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;n thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;n phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // some helper variablesnn var segment;n var radius = innerRadius;n var radiusStep = (outerRadius - innerRadius) / phiSegments;n var vertex = new Vector3();n var uv = new Vector2();n var j, i; // generate vertices, normals and uvsnn for (j = 0; j <= phiSegments; j++) {n for (i = 0; i <= thetaSegments; i++) {n // values are generate from the inside of the ring to the outsiden segment = thetaStart + i / thetaSegments * thetaLength; // vertexnn vertex.x = radius * Math.cos(segment);n vertex.y = radius * Math.sin(segment);n vertices.push(vertex.x, vertex.y, vertex.z); // normalnn normals.push(0, 0, 1); // uvnn uv.x = (vertex.x / outerRadius + 1) / 2;n uv.y = (vertex.y / outerRadius + 1) / 2;n uvs.push(uv.x, uv.y);n } // increase the radius for next row of verticesnnn radius += radiusStep;n } // indicesnnn for (j = 0; j < phiSegments; j++) {n var thetaSegmentLevel = j * (thetaSegments + 1);nn for (i = 0; i < thetaSegments; i++) {n segment = i + thetaSegmentLevel;n var a = segment;n var b = segment + thetaSegments + 1;n var c = segment + thetaSegments + 2;n var d = segment + 1; // facesnn indices.push(a, b, d);n indices.push(b, c, d);n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));n}nnRingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nRingBufferGeometry.prototype.constructor = RingBufferGeometry;n/**n * @author zz85 / github.com/zz85n * @author bhouston / clara.ion * @author Mugen87 / github.com/Mugen87n */n// LatheGeometrynnfunction LatheGeometry(points, segments, phiStart, phiLength) {n Geometry.call(this);n this.type = 'LatheGeometry';n this.parameters = {n points: points,n segments: segments,n phiStart: phiStart,n phiLength: phiLengthn };n this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));n this.mergeVertices();n}nnLatheGeometry.prototype = Object.create(Geometry.prototype);nLatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometrynnfunction LatheBufferGeometry(points, segments, phiStart, phiLength) {n BufferGeometry.call(this);n this.type = 'LatheBufferGeometry';n this.parameters = {n points: points,n segments: segments,n phiStart: phiStart,n phiLength: phiLengthn };n segments = Math.floor(segments) || 12;n phiStart = phiStart || 0;n phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]nn phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffersnn var indices = [];n var vertices = [];n var uvs = []; // helper variablesnn var base;n var inverseSegments = 1.0 / segments;n var vertex = new Vector3();n var uv = new Vector2();n var i, j; // generate vertices and uvsnn for (i = 0; i <= segments; i++) {n var phi = phiStart + i * inverseSegments * phiLength;n var sin = Math.sin(phi);n var cos = Math.cos(phi);nn for (j = 0; j <= points.length - 1; j++) {n // vertexn vertex.x = points.x * sin;n vertex.y = points.y;n vertex.z = points.x * cos;n vertices.push(vertex.x, vertex.y, vertex.z); // uvnn uv.x = i / segments;n uv.y = j / (points.length - 1);n uvs.push(uv.x, uv.y);n }n } // indicesnnn for (i = 0; i < segments; i++) {n for (j = 0; j < points.length - 1; j++) {n base = j + i * points.length;n var a = base;n var b = base + points.length;n var c = base + points.length + 1;n var d = base + 1; // facesnn indices.push(a, b, d);n indices.push(b, c, d);n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normalsnn this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.n // because the corresponding vertices are identical (but still have different UVs).nn if (phiLength === Math.PI * 2) {n var normals = this.attributes.normal.array;n var n1 = new Vector3();n var n2 = new Vector3();n var n = new Vector3(); // this is the buffer offset for the last line of verticesnn base = segments * points.length * 3;nn for (i = 0, j = 0; i < points.length; i++, j += 3) {n // select the normal of the vertex in the first linen n1.x = normals[j + 0];n n1.y = normals[j + 1];n n1.z = normals[j + 2]; // select the normal of the vertex in the last linenn n2.x = normals[base + j + 0];n n2.y = normals[base + j + 1];n n2.z = normals[base + j + 2]; // average normalsnn n.addVectors(n1, n2).normalize(); // assign the new values to both normalsnn normals[j + 0] = normals[base + j + 0] = n.x;n normals[j + 1] = normals[base + j + 1] = n.y;n normals[j + 2] = normals[base + j + 2] = n.z;n }n }n}nnLatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nLatheBufferGeometry.prototype.constructor = LatheBufferGeometry;n/**n * @author jonobr1 / jonobr1.comn * @author Mugen87 / github.com/Mugen87n */n// ShapeGeometrynnfunction ShapeGeometry(shapes, curveSegments) {n Geometry.call(this);n this.type = 'ShapeGeometry';nn if (_typeof(curveSegments) === 'object') {n console.warn('THREE.ShapeGeometry: Options parameter has been removed.');n curveSegments = curveSegments.curveSegments;n }nn this.parameters = {n shapes: shapes,n curveSegments: curveSegmentsn };n this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));n this.mergeVertices();n}nnShapeGeometry.prototype = Object.create(Geometry.prototype);nShapeGeometry.prototype.constructor = ShapeGeometry;nnShapeGeometry.prototype.toJSON = function () {n var data = Geometry.prototype.toJSON.call(this);n var shapes = this.parameters.shapes;n return toJSON$1(shapes, data);n}; // ShapeBufferGeometrynnnfunction ShapeBufferGeometry(shapes, curveSegments) {n BufferGeometry.call(this);n this.type = 'ShapeBufferGeometry';n this.parameters = {n shapes: shapes,n curveSegments: curveSegmentsn };n curveSegments = curveSegments || 12; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // helper variablesnn var groupStart = 0;n var groupCount = 0; // allow single and array values for "shapes" parameternn if (Array.isArray(shapes) === false) {n addShape(shapes);n } else {n for (var i = 0; i < shapes.length; i++) {n addShape(shapes);n this.addGroup(groupStart, groupCount, i); // enables MultiMaterial supportnn groupStart += groupCount;n groupCount = 0;n }n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functionsnn function addShape(shape) {n var i, l, shapeHole;n var indexOffset = vertices.length / 3;n var points = shape.extractPoints(curveSegments);n var shapeVertices = points.shape;n var shapeHoles = points.holes; // check direction of verticesnn if (ShapeUtils.isClockWise(shapeVertices) === false) {n shapeVertices = shapeVertices.reverse();n }nn for (i = 0, l = shapeHoles.length; i < l; i++) {n shapeHole = shapeHoles;nn if (ShapeUtils.isClockWise(shapeHole) === true) {n shapeHoles = shapeHole.reverse();n }n }nn var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single arraynn for (i = 0, l = shapeHoles.length; i < l; i++) {n shapeHole = shapeHoles;n shapeVertices = shapeVertices.concat(shapeHole);n } // vertices, normals, uvsnnn for (i = 0, l = shapeVertices.length; i < l; i++) {n var vertex = shapeVertices;n vertices.push(vertex.x, vertex.y, 0);n normals.push(0, 0, 1);n uvs.push(vertex.x, vertex.y); // world uvsn } // incidesnnn for (i = 0, l = faces.length; i < l; i++) {n var face = faces;n var a = face + indexOffset;n var b = face + indexOffset;n var c = face + indexOffset;n indices.push(a, b, c);n groupCount += 3;n }n }n}nnShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;nnShapeBufferGeometry.prototype.toJSON = function () {n var data = BufferGeometry.prototype.toJSON.call(this);n var shapes = this.parameters.shapes;n return toJSON$1(shapes, data);n}; //nnnfunction toJSON$1(shapes, data) {n data.shapes = [];nn if (Array.isArray(shapes)) {n for (var i = 0, l = shapes.length; i < l; i++) {n var shape = shapes;n data.shapes.push(shape.uuid);n }n } else {n data.shapes.push(shapes.uuid);n }nn return data;n}n/**n * @author WestLangley / github.com/WestLangleyn * @author Mugen87 / github.com/Mugen87n */nnnfunction EdgesGeometry(geometry, thresholdAngle) {n BufferGeometry.call(this);n this.type = 'EdgesGeometry';n this.parameters = {n thresholdAngle: thresholdAnglen };n thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffernn var vertices = []; // helper variablesnn var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);n var edge = [0, 0],n edges = {},n edge1,n edge2;n var key,n keys = ['a', 'b', 'c']; // prepare source geometrynn var geometry2;nn if (geometry.isBufferGeometry) {n geometry2 = new Geometry();n geometry2.fromBufferGeometry(geometry);n } else {n geometry2 = geometry.clone();n }nn geometry2.mergeVertices();n geometry2.computeFaceNormals();n var sourceVertices = geometry2.vertices;n var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining facesnn for (var i = 0, l = faces.length; i < l; i++) {n var face = faces;nn for (var j = 0; j < 3; j++) {n edge1 = face[keys];n edge2 = face[keys[(j + 1) % 3]];n edge = Math.min(edge1, edge2);n edge = Math.max(edge1, edge2);n key = edge + ',' + edge;nn if (edges === undefined) {n edges = {n index1: edge,n index2: edge,n face1: i,n face2: undefinedn };n } else {n edges.face2 = i;n }n }n } // generate verticesnnn for (key in edges) {n var e = edges; // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.nn if (e.face2 === undefined || faces.normal.dot(faces.normal) <= thresholdDot) {n var vertex = sourceVertices;n vertices.push(vertex.x, vertex.y, vertex.z);n vertex = sourceVertices;n vertices.push(vertex.x, vertex.y, vertex.z);n }n } // build geometrynnn this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n}nnEdgesGeometry.prototype = Object.create(BufferGeometry.prototype);nEdgesGeometry.prototype.constructor = EdgesGeometry;n/**n * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n */n// CylinderGeometrynnfunction CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {n Geometry.call(this);n this.type = 'CylinderGeometry';n this.parameters = {n radiusTop: radiusTop,n radiusBottom: radiusBottom,n height: height,n radialSegments: radialSegments,n heightSegments: heightSegments,n openEnded: openEnded,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));n this.mergeVertices();n}nnCylinderGeometry.prototype = Object.create(Geometry.prototype);nCylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometrynnfunction CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {n BufferGeometry.call(this);n this.type = 'CylinderBufferGeometry';n this.parameters = {n radiusTop: radiusTop,n radiusBottom: radiusBottom,n height: height,n radialSegments: radialSegments,n heightSegments: heightSegments,n openEnded: openEnded,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n var scope = this;n radiusTop = radiusTop !== undefined ? radiusTop : 1;n radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;n height = height || 1;n radialSegments = Math.floor(radialSegments) || 8;n heightSegments = Math.floor(heightSegments) || 1;n openEnded = openEnded !== undefined ? openEnded : false;n thetaStart = thetaStart !== undefined ? thetaStart : 0.0;n thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // helper variablesnn var index = 0;n var indexArray = [];n var halfHeight = height / 2;n var groupStart = 0; // generate geometrynn generateTorso();nn if (openEnded === false) {n if (radiusTop > 0) generateCap(true);n if (radiusBottom > 0) generateCap(false);n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));nn function generateTorso() {n var x, y;n var normal = new Vector3();n var vertex = new Vector3();n var groupCount = 0; // this will be used to calculate the normalnn var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvsnn for (y = 0; y <= heightSegments; y++) {n var indexRow = [];n var v = y / heightSegments; // calculate the radius of the current rownn var radius = v * (radiusBottom - radiusTop) + radiusTop;nn for (x = 0; x <= radialSegments; x++) {n var u = x / radialSegments;n var theta = u * thetaLength + thetaStart;n var sinTheta = Math.sin(theta);n var cosTheta = Math.cos(theta); // vertexnn vertex.x = radius * sinTheta;n vertex.y = -v * height + halfHeight;n vertex.z = radius * cosTheta;n vertices.push(vertex.x, vertex.y, vertex.z); // normalnn normal.set(sinTheta, slope, cosTheta).normalize();n normals.push(normal.x, normal.y, normal.z); // uvnn uvs.push(u, 1 - v); // save index of vertex in respective rownn indexRow.push(index++);n } // now save vertices of the row in our index arraynnn indexArray.push(indexRow);n } // generate indicesnnn for (x = 0; x < radialSegments; x++) {n for (y = 0; y < heightSegments; y++) {n // we use the index array to access the correct indicesn var a = indexArray[x];n var b = indexArray[y + 1];n var c = indexArray[y + 1][x + 1];n var d = indexArray[x + 1]; // facesnn indices.push(a, b, d);n indices.push(b, c, d); // update group counternn groupCount += 6;n }n } // add a group to the geometry. this will ensure multi material supportnnn scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groupsnn groupStart += groupCount;n }nn function generateCap(top) {n var x, centerIndexStart, centerIndexEnd;n var uv = new Vector2();n var vertex = new Vector3();n var groupCount = 0;n var radius = top === true ? radiusTop : radiusBottom;n var sign = top === true ? 1 : -1; // save the index of the first center vertexnn centerIndexStart = index; // first we generate the center vertex data of the cap.n // because the geometry needs one set of uvs per face,n // we must generate a center vertex per face/segmentnn for (x = 1; x <= radialSegments; x++) {n // vertexn vertices.push(0, halfHeight * sign, 0); // normalnn normals.push(0, sign, 0); // uvnn uvs.push(0.5, 0.5); // increase indexnn index++;n } // save the index of the last center vertexnnn centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvsnn for (x = 0; x <= radialSegments; x++) {n var u = x / radialSegments;n var theta = u * thetaLength + thetaStart;n var cosTheta = Math.cos(theta);n var sinTheta = Math.sin(theta); // vertexnn vertex.x = radius * sinTheta;n vertex.y = halfHeight * sign;n vertex.z = radius * cosTheta;n vertices.push(vertex.x, vertex.y, vertex.z); // normalnn normals.push(0, sign, 0); // uvnn uv.x = cosTheta * 0.5 + 0.5;n uv.y = sinTheta * 0.5 * sign + 0.5;n uvs.push(uv.x, uv.y); // increase indexnn index++;n } // generate indicesnnn for (x = 0; x < radialSegments; x++) {n var c = centerIndexStart + x;n var i = centerIndexEnd + x;nn if (top === true) {n // face topn indices.push(i, i + 1, c);n } else {n // face bottomn indices.push(i + 1, i, c);n }nn groupCount += 3;n } // add a group to the geometry. this will ensure multi material supportnnn scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groupsnn groupStart += groupCount;n }n}nnCylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nCylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;n/**n * @author abelnation / github.com/abelnationn */n// ConeGeometrynnfunction ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {n CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);n this.type = 'ConeGeometry';n this.parameters = {n radius: radius,n height: height,n radialSegments: radialSegments,n heightSegments: heightSegments,n openEnded: openEnded,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n}nnConeGeometry.prototype = Object.create(CylinderGeometry.prototype);nConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometrynnfunction ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {n CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);n this.type = 'ConeBufferGeometry';n this.parameters = {n radius: radius,n height: height,n radialSegments: radialSegments,n heightSegments: heightSegments,n openEnded: openEnded,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n}nnConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);nConeBufferGeometry.prototype.constructor = ConeBufferGeometry;n/**n * @author benaadams / twitter.com/ben_a_adamsn * @author Mugen87 / github.com/Mugen87n * @author hughesn */n// CircleGeometrynnfunction CircleGeometry(radius, segments, thetaStart, thetaLength) {n Geometry.call(this);n this.type = 'CircleGeometry';n this.parameters = {n radius: radius,n segments: segments,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));n this.mergeVertices();n}nnCircleGeometry.prototype = Object.create(Geometry.prototype);nCircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometrynnfunction CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {n BufferGeometry.call(this);n this.type = 'CircleBufferGeometry';n this.parameters = {n radius: radius,n segments: segments,n thetaStart: thetaStart,n thetaLength: thetaLengthn };n radius = radius || 1;n segments = segments !== undefined ? Math.max(3, segments) : 8;n thetaStart = thetaStart !== undefined ? thetaStart : 0;n thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffersnn var indices = [];n var vertices = [];n var normals = [];n var uvs = []; // helper variablesnn var i, s;n var vertex = new Vector3();n var uv = new Vector2(); // center pointnn vertices.push(0, 0, 0);n normals.push(0, 0, 1);n uvs.push(0.5, 0.5);nn for (s = 0, i = 3; s <= segments; s++, i += 3) {n var segment = thetaStart + s / segments * thetaLength; // vertexnn vertex.x = radius * Math.cos(segment);n vertex.y = radius * Math.sin(segment);n vertices.push(vertex.x, vertex.y, vertex.z); // normalnn normals.push(0, 0, 1); // uvsnn uv.x = (vertices / radius + 1) / 2;n uv.y = (vertices[i + 1] / radius + 1) / 2;n uvs.push(uv.x, uv.y);n } // indicesnnn for (i = 1; i <= segments; i++) {n indices.push(i, i + 1, 0);n } // build geometrynnn this.setIndex(indices);n this.addAttribute('position', new Float32BufferAttribute(vertices, 3));n this.addAttribute('normal', new Float32BufferAttribute(normals, 3));n this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));n}nnCircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);nCircleBufferGeometry.prototype.constructor = CircleBufferGeometry;nvar Geometries =n/*#__PURE__*/nObject.freeze({n WireframeGeometry: WireframeGeometry,n ParametricGeometry: ParametricGeometry,n ParametricBufferGeometry: ParametricBufferGeometry,n TetrahedronGeometry: TetrahedronGeometry,n TetrahedronBufferGeometry: TetrahedronBufferGeometry,n OctahedronGeometry: OctahedronGeometry,n OctahedronBufferGeometry: OctahedronBufferGeometry,n IcosahedronGeometry: IcosahedronGeometry,n IcosahedronBufferGeometry: IcosahedronBufferGeometry,n DodecahedronGeometry: DodecahedronGeometry,n DodecahedronBufferGeometry: DodecahedronBufferGeometry,n PolyhedronGeometry: PolyhedronGeometry,n PolyhedronBufferGeometry: PolyhedronBufferGeometry,n TubeGeometry: TubeGeometry,n TubeBufferGeometry: TubeBufferGeometry,n TorusKnotGeometry: TorusKnotGeometry,n TorusKnotBufferGeometry: TorusKnotBufferGeometry,n TorusGeometry: TorusGeometry,n TorusBufferGeometry: TorusBufferGeometry,n TextGeometry: TextGeometry,n TextBufferGeometry: TextBufferGeometry,n SphereGeometry: SphereGeometry,n SphereBufferGeometry: SphereBufferGeometry,n RingGeometry: RingGeometry,n RingBufferGeometry: RingBufferGeometry,n PlaneGeometry: PlaneGeometry,n PlaneBufferGeometry: PlaneBufferGeometry,n LatheGeometry: LatheGeometry,n LatheBufferGeometry: LatheBufferGeometry,n ShapeGeometry: ShapeGeometry,n ShapeBufferGeometry: ShapeBufferGeometry,n ExtrudeGeometry: ExtrudeGeometry,n ExtrudeBufferGeometry: ExtrudeBufferGeometry,n EdgesGeometry: EdgesGeometry,n ConeGeometry: ConeGeometry,n ConeBufferGeometry: ConeBufferGeometry,n CylinderGeometry: CylinderGeometry,n CylinderBufferGeometry: CylinderBufferGeometry,n CircleGeometry: CircleGeometry,n CircleBufferGeometry: CircleBufferGeometry,n BoxGeometry: BoxGeometry,n BoxBufferGeometry: BoxBufferGeometryn});n/**n * @author mrdoob / mrdoob.com/n *n * parameters = {n * color: <THREE.Color>n * }n */nnfunction ShadowMaterial(parameters) {n Material.call(this);n this.type = 'ShadowMaterial';n this.color = new Color(0x000000);n this.transparent = true;n this.setValues(parameters);n}nnShadowMaterial.prototype = Object.create(Material.prototype);nShadowMaterial.prototype.constructor = ShadowMaterial;nShadowMaterial.prototype.isShadowMaterial = true;nnShadowMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.color.copy(source.color);n return this;n};n/**n * @author mrdoob / mrdoob.com/n */nnnfunction RawShaderMaterial(parameters) {n ShaderMaterial.call(this, parameters);n this.type = 'RawShaderMaterial';n}nnRawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);nRawShaderMaterial.prototype.constructor = RawShaderMaterial;nRawShaderMaterial.prototype.isRawShaderMaterial = true;n/**n * @author WestLangley / github.com/WestLangleyn *n * parameters = {n * color: <hex>,n * roughness: <float>,n * metalness: <float>,n * opacity: <float>,n *n * map: new THREE.Texture( <Image> ),n *n * lightMap: new THREE.Texture( <Image> ),n * lightMapIntensity: <float>n *n * aoMap: new THREE.Texture( <Image> ),n * aoMapIntensity: <float>n *n * emissive: <hex>,n * emissiveIntensity: <float>n * emissiveMap: new THREE.Texture( <Image> ),n *n * bumpMap: new THREE.Texture( <Image> ),n * bumpScale: <float>,n *n * normalMap: new THREE.Texture( <Image> ),n * normalMapType: THREE.TangentSpaceNormalMap,n * normalScale: <Vector2>,n *n * displacementMap: new THREE.Texture( <Image> ),n * displacementScale: <float>,n * displacementBias: <float>,n *n * roughnessMap: new THREE.Texture( <Image> ),n *n * metalnessMap: new THREE.Texture( <Image> ),n *n * alphaMap: new THREE.Texture( <Image> ),n *n * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),n * envMapIntensity: <float>n *n * refractionRatio: <float>,n *n * wireframe: <boolean>,n * wireframeLinewidth: <float>,n *n * skinning: <bool>,n * morphTargets: <bool>,n * morphNormals: <bool>n * }n */nnfunction MeshStandardMaterial(parameters) {n Material.call(this);n this.defines = {n 'STANDARD': ''n };n this.type = 'MeshStandardMaterial';n this.color = new Color(0xffffff); // diffusenn this.roughness = 0.5;n this.metalness = 0.5;n this.map = null;n this.lightMap = null;n this.lightMapIntensity = 1.0;n this.aoMap = null;n this.aoMapIntensity = 1.0;n this.emissive = new Color(0x000000);n this.emissiveIntensity = 1.0;n this.emissiveMap = null;n this.bumpMap = null;n this.bumpScale = 1;n this.normalMap = null;n this.normalMapType = TangentSpaceNormalMap;n this.normalScale = new Vector2(1, 1);n this.displacementMap = null;n this.displacementScale = 1;n this.displacementBias = 0;n this.roughnessMap = null;n this.metalnessMap = null;n this.alphaMap = null;n this.envMap = null;n this.envMapIntensity = 1.0;n this.refractionRatio = 0.98;n this.wireframe = false;n this.wireframeLinewidth = 1;n this.wireframeLinecap = 'round';n this.wireframeLinejoin = 'round';n this.skinning = false;n this.morphTargets = false;n this.morphNormals = false;n this.setValues(parameters);n}nnMeshStandardMaterial.prototype = Object.create(Material.prototype);nMeshStandardMaterial.prototype.constructor = MeshStandardMaterial;nMeshStandardMaterial.prototype.isMeshStandardMaterial = true;nnMeshStandardMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.defines = {n 'STANDARD': ''n };n this.color.copy(source.color);n this.roughness = source.roughness;n this.metalness = source.metalness;n this.map = source.map;n this.lightMap = source.lightMap;n this.lightMapIntensity = source.lightMapIntensity;n this.aoMap = source.aoMap;n this.aoMapIntensity = source.aoMapIntensity;n this.emissive.copy(source.emissive);n this.emissiveMap = source.emissiveMap;n this.emissiveIntensity = source.emissiveIntensity;n this.bumpMap = source.bumpMap;n this.bumpScale = source.bumpScale;n this.normalMap = source.normalMap;n this.normalMapType = source.normalMapType;n this.normalScale.copy(source.normalScale);n this.displacementMap = source.displacementMap;n this.displacementScale = source.displacementScale;n this.displacementBias = source.displacementBias;n this.roughnessMap = source.roughnessMap;n this.metalnessMap = source.metalnessMap;n this.alphaMap = source.alphaMap;n this.envMap = source.envMap;n this.envMapIntensity = source.envMapIntensity;n this.refractionRatio = source.refractionRatio;n this.wireframe = source.wireframe;n this.wireframeLinewidth = source.wireframeLinewidth;n this.wireframeLinecap = source.wireframeLinecap;n this.wireframeLinejoin = source.wireframeLinejoin;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.morphNormals = source.morphNormals;n return this;n};n/**n * @author WestLangley / github.com/WestLangleyn *n * parameters = {n * reflectivity: <float>n * clearcoat: <float>n * clearcoatRoughness: <float>n *n * sheen: <Color>n *n * clearcoatNormalScale: <Vector2>,n * clearcoatNormalMap: new THREE.Texture( <Image> ),n * }n */nnnfunction MeshPhysicalMaterial(parameters) {n MeshStandardMaterial.call(this);n this.defines = {n 'STANDARD': '',n 'PHYSICAL': ''n };n this.type = 'MeshPhysicalMaterial';n this.reflectivity = 0.5; // maps to F0 = 0.04nn this.clearcoat = 0.0;n this.clearcoatRoughness = 0.0;n this.sheen = null; // null will disable sheen bsdfnn this.clearcoatNormalScale = new Vector2(1, 1);n this.clearcoatNormalMap = null;n this.transparency = 0.0;n this.setValues(parameters);n}nnMeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);nMeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;nMeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;nnMeshPhysicalMaterial.prototype.copy = function (source) {n MeshStandardMaterial.prototype.copy.call(this, source);n this.defines = {n 'STANDARD': '',n 'PHYSICAL': ''n };n this.reflectivity = source.reflectivity;n this.clearcoat = source.clearcoat;n this.clearcoatRoughness = source.clearcoatRoughness;n if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;n this.clearcoatNormalMap = source.clearcoatNormalMap;n this.clearcoatNormalScale.copy(source.clearcoatNormalScale);n this.transparency = source.transparency;n return this;n};n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n *n * parameters = {n * color: <hex>,n * specular: <hex>,n * shininess: <float>,n * opacity: <float>,n *n * map: new THREE.Texture( <Image> ),n *n * lightMap: new THREE.Texture( <Image> ),n * lightMapIntensity: <float>n *n * aoMap: new THREE.Texture( <Image> ),n * aoMapIntensity: <float>n *n * emissive: <hex>,n * emissiveIntensity: <float>n * emissiveMap: new THREE.Texture( <Image> ),n *n * bumpMap: new THREE.Texture( <Image> ),n * bumpScale: <float>,n *n * normalMap: new THREE.Texture( <Image> ),n * normalMapType: THREE.TangentSpaceNormalMap,n * normalScale: <Vector2>,n *n * displacementMap: new THREE.Texture( <Image> ),n * displacementScale: <float>,n * displacementBias: <float>,n *n * specularMap: new THREE.Texture( <Image> ),n *n * alphaMap: new THREE.Texture( <Image> ),n *n * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),n * combine: THREE.Multiply,n * reflectivity: <float>,n * refractionRatio: <float>,n *n * wireframe: <boolean>,n * wireframeLinewidth: <float>,n *n * skinning: <bool>,n * morphTargets: <bool>,n * morphNormals: <bool>n * }n */nnnfunction MeshPhongMaterial(parameters) {n Material.call(this);n this.type = 'MeshPhongMaterial';n this.color = new Color(0xffffff); // diffusenn this.specular = new Color(0x111111);n this.shininess = 30;n this.map = null;n this.lightMap = null;n this.lightMapIntensity = 1.0;n this.aoMap = null;n this.aoMapIntensity = 1.0;n this.emissive = new Color(0x000000);n this.emissiveIntensity = 1.0;n this.emissiveMap = null;n this.bumpMap = null;n this.bumpScale = 1;n this.normalMap = null;n this.normalMapType = TangentSpaceNormalMap;n this.normalScale = new Vector2(1, 1);n this.displacementMap = null;n this.displacementScale = 1;n this.displacementBias = 0;n this.specularMap = null;n this.alphaMap = null;n this.envMap = null;n this.combine = MultiplyOperation;n this.reflectivity = 1;n this.refractionRatio = 0.98;n this.wireframe = false;n this.wireframeLinewidth = 1;n this.wireframeLinecap = 'round';n this.wireframeLinejoin = 'round';n this.skinning = false;n this.morphTargets = false;n this.morphNormals = false;n this.setValues(parameters);n}nnMeshPhongMaterial.prototype = Object.create(Material.prototype);nMeshPhongMaterial.prototype.constructor = MeshPhongMaterial;nMeshPhongMaterial.prototype.isMeshPhongMaterial = true;nnMeshPhongMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.color.copy(source.color);n this.specular.copy(source.specular);n this.shininess = source.shininess;n this.map = source.map;n this.lightMap = source.lightMap;n this.lightMapIntensity = source.lightMapIntensity;n this.aoMap = source.aoMap;n this.aoMapIntensity = source.aoMapIntensity;n this.emissive.copy(source.emissive);n this.emissiveMap = source.emissiveMap;n this.emissiveIntensity = source.emissiveIntensity;n this.bumpMap = source.bumpMap;n this.bumpScale = source.bumpScale;n this.normalMap = source.normalMap;n this.normalMapType = source.normalMapType;n this.normalScale.copy(source.normalScale);n this.displacementMap = source.displacementMap;n this.displacementScale = source.displacementScale;n this.displacementBias = source.displacementBias;n this.specularMap = source.specularMap;n this.alphaMap = source.alphaMap;n this.envMap = source.envMap;n this.combine = source.combine;n this.reflectivity = source.reflectivity;n this.refractionRatio = source.refractionRatio;n this.wireframe = source.wireframe;n this.wireframeLinewidth = source.wireframeLinewidth;n this.wireframeLinecap = source.wireframeLinecap;n this.wireframeLinejoin = source.wireframeLinejoin;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.morphNormals = source.morphNormals;n return this;n};n/**n * @author takahirox / github.com/takahiroxn *n * parameters = {n * gradientMap: new THREE.Texture( <Image> )n * }n */nnnfunction MeshToonMaterial(parameters) {n MeshPhongMaterial.call(this);n this.defines = {n 'TOON': ''n };n this.type = 'MeshToonMaterial';n this.gradientMap = null;n this.setValues(parameters);n}nnMeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);nMeshToonMaterial.prototype.constructor = MeshToonMaterial;nMeshToonMaterial.prototype.isMeshToonMaterial = true;nnMeshToonMaterial.prototype.copy = function (source) {n MeshPhongMaterial.prototype.copy.call(this, source);n this.gradientMap = source.gradientMap;n return this;n};n/**n * @author mrdoob / mrdoob.com/n * @author WestLangley / github.com/WestLangleyn *n * parameters = {n * opacity: <float>,n *n * bumpMap: new THREE.Texture( <Image> ),n * bumpScale: <float>,n *n * normalMap: new THREE.Texture( <Image> ),n * normalMapType: THREE.TangentSpaceNormalMap,n * normalScale: <Vector2>,n *n * displacementMap: new THREE.Texture( <Image> ),n * displacementScale: <float>,n * displacementBias: <float>,n *n * wireframe: <boolean>,n * wireframeLinewidth: <float>n *n * skinning: <bool>,n * morphTargets: <bool>,n * morphNormals: <bool>n * }n */nnnfunction MeshNormalMaterial(parameters) {n Material.call(this);n this.type = 'MeshNormalMaterial';n this.bumpMap = null;n this.bumpScale = 1;n this.normalMap = null;n this.normalMapType = TangentSpaceNormalMap;n this.normalScale = new Vector2(1, 1);n this.displacementMap = null;n this.displacementScale = 1;n this.displacementBias = 0;n this.wireframe = false;n this.wireframeLinewidth = 1;n this.fog = false;n this.lights = false;n this.skinning = false;n this.morphTargets = false;n this.morphNormals = false;n this.setValues(parameters);n}nnMeshNormalMaterial.prototype = Object.create(Material.prototype);nMeshNormalMaterial.prototype.constructor = MeshNormalMaterial;nMeshNormalMaterial.prototype.isMeshNormalMaterial = true;nnMeshNormalMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.bumpMap = source.bumpMap;n this.bumpScale = source.bumpScale;n this.normalMap = source.normalMap;n this.normalMapType = source.normalMapType;n this.normalScale.copy(source.normalScale);n this.displacementMap = source.displacementMap;n this.displacementScale = source.displacementScale;n this.displacementBias = source.displacementBias;n this.wireframe = source.wireframe;n this.wireframeLinewidth = source.wireframeLinewidth;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.morphNormals = source.morphNormals;n return this;n};n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n *n * parameters = {n * color: <hex>,n * opacity: <float>,n *n * map: new THREE.Texture( <Image> ),n *n * lightMap: new THREE.Texture( <Image> ),n * lightMapIntensity: <float>n *n * aoMap: new THREE.Texture( <Image> ),n * aoMapIntensity: <float>n *n * emissive: <hex>,n * emissiveIntensity: <float>n * emissiveMap: new THREE.Texture( <Image> ),n *n * specularMap: new THREE.Texture( <Image> ),n *n * alphaMap: new THREE.Texture( <Image> ),n *n * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),n * combine: THREE.Multiply,n * reflectivity: <float>,n * refractionRatio: <float>,n *n * wireframe: <boolean>,n * wireframeLinewidth: <float>,n *n * skinning: <bool>,n * morphTargets: <bool>,n * morphNormals: <bool>n * }n */nnnfunction MeshLambertMaterial(parameters) {n Material.call(this);n this.type = 'MeshLambertMaterial';n this.color = new Color(0xffffff); // diffusenn this.map = null;n this.lightMap = null;n this.lightMapIntensity = 1.0;n this.aoMap = null;n this.aoMapIntensity = 1.0;n this.emissive = new Color(0x000000);n this.emissiveIntensity = 1.0;n this.emissiveMap = null;n this.specularMap = null;n this.alphaMap = null;n this.envMap = null;n this.combine = MultiplyOperation;n this.reflectivity = 1;n this.refractionRatio = 0.98;n this.wireframe = false;n this.wireframeLinewidth = 1;n this.wireframeLinecap = 'round';n this.wireframeLinejoin = 'round';n this.skinning = false;n this.morphTargets = false;n this.morphNormals = false;n this.setValues(parameters);n}nnMeshLambertMaterial.prototype = Object.create(Material.prototype);nMeshLambertMaterial.prototype.constructor = MeshLambertMaterial;nMeshLambertMaterial.prototype.isMeshLambertMaterial = true;nnMeshLambertMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.color.copy(source.color);n this.map = source.map;n this.lightMap = source.lightMap;n this.lightMapIntensity = source.lightMapIntensity;n this.aoMap = source.aoMap;n this.aoMapIntensity = source.aoMapIntensity;n this.emissive.copy(source.emissive);n this.emissiveMap = source.emissiveMap;n this.emissiveIntensity = source.emissiveIntensity;n this.specularMap = source.specularMap;n this.alphaMap = source.alphaMap;n this.envMap = source.envMap;n this.combine = source.combine;n this.reflectivity = source.reflectivity;n this.refractionRatio = source.refractionRatio;n this.wireframe = source.wireframe;n this.wireframeLinewidth = source.wireframeLinewidth;n this.wireframeLinecap = source.wireframeLinecap;n this.wireframeLinejoin = source.wireframeLinejoin;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.morphNormals = source.morphNormals;n return this;n};n/**n * @author WestLangley / github.com/WestLangleyn *n * parameters = {n * color: <hex>,n * opacity: <float>,n *n * matcap: new THREE.Texture( <Image> ),n *n * map: new THREE.Texture( <Image> ),n *n * bumpMap: new THREE.Texture( <Image> ),n * bumpScale: <float>,n *n * normalMap: new THREE.Texture( <Image> ),n * normalMapType: THREE.TangentSpaceNormalMap,n * normalScale: <Vector2>,n *n * displacementMap: new THREE.Texture( <Image> ),n * displacementScale: <float>,n * displacementBias: <float>,n *n * alphaMap: new THREE.Texture( <Image> ),n *n * skinning: <bool>,n * morphTargets: <bool>,n * morphNormals: <bool>n * }n */nnnfunction MeshMatcapMaterial(parameters) {n Material.call(this);n this.defines = {n 'MATCAP': ''n };n this.type = 'MeshMatcapMaterial';n this.color = new Color(0xffffff); // diffusenn this.matcap = null;n this.map = null;n this.bumpMap = null;n this.bumpScale = 1;n this.normalMap = null;n this.normalMapType = TangentSpaceNormalMap;n this.normalScale = new Vector2(1, 1);n this.displacementMap = null;n this.displacementScale = 1;n this.displacementBias = 0;n this.alphaMap = null;n this.skinning = false;n this.morphTargets = false;n this.morphNormals = false;n this.lights = false;n this.setValues(parameters);n}nnMeshMatcapMaterial.prototype = Object.create(Material.prototype);nMeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;nMeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;nnMeshMatcapMaterial.prototype.copy = function (source) {n Material.prototype.copy.call(this, source);n this.defines = {n 'MATCAP': ''n };n this.color.copy(source.color);n this.matcap = source.matcap;n this.map = source.map;n this.bumpMap = source.bumpMap;n this.bumpScale = source.bumpScale;n this.normalMap = source.normalMap;n this.normalMapType = source.normalMapType;n this.normalScale.copy(source.normalScale);n this.displacementMap = source.displacementMap;n this.displacementScale = source.displacementScale;n this.displacementBias = source.displacementBias;n this.alphaMap = source.alphaMap;n this.skinning = source.skinning;n this.morphTargets = source.morphTargets;n this.morphNormals = source.morphNormals;n return this;n};n/**n * @author alteredq / alteredqualia.com/n *n * parameters = {n * color: <hex>,n * opacity: <float>,n *n * linewidth: <float>,n *n * scale: <float>,n * dashSize: <float>,n * gapSize: <float>n * }n */nnnfunction LineDashedMaterial(parameters) {n LineBasicMaterial.call(this);n this.type = 'LineDashedMaterial';n this.scale = 1;n this.dashSize = 3;n this.gapSize = 1;n this.setValues(parameters);n}nnLineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);nLineDashedMaterial.prototype.constructor = LineDashedMaterial;nLineDashedMaterial.prototype.isLineDashedMaterial = true;nnLineDashedMaterial.prototype.copy = function (source) {n LineBasicMaterial.prototype.copy.call(this, source);n this.scale = source.scale;n this.dashSize = source.dashSize;n this.gapSize = source.gapSize;n return this;n};nnvar Materials =n/*#__PURE__*/nObject.freeze({n ShadowMaterial: ShadowMaterial,n SpriteMaterial: SpriteMaterial,n RawShaderMaterial: RawShaderMaterial,n ShaderMaterial: ShaderMaterial,n PointsMaterial: PointsMaterial,n MeshPhysicalMaterial: MeshPhysicalMaterial,n MeshStandardMaterial: MeshStandardMaterial,n MeshPhongMaterial: MeshPhongMaterial,n MeshToonMaterial: MeshToonMaterial,n MeshNormalMaterial: MeshNormalMaterial,n MeshLambertMaterial: MeshLambertMaterial,n MeshDepthMaterial: MeshDepthMaterial,n MeshDistanceMaterial: MeshDistanceMaterial,n MeshBasicMaterial: MeshBasicMaterial,n MeshMatcapMaterial: MeshMatcapMaterial,n LineDashedMaterial: LineDashedMaterial,n LineBasicMaterial: LineBasicMaterial,n Material: Materialn});n/**n * @author tschwn * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n */nnvar AnimationUtils = {n // same as Array.prototype.slice, but also works on typed arraysn arraySlice: function arraySlice(array, from, to) {n if (AnimationUtils.isTypedArray(array)) {n // in ios9 array.subarray(from, undefined) will return empty arrayn // but array.subarray(from) or array.subarray(from, len) is correctn return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));n }nn return array.slice(from, to);n },n // converts an array to a specific typen convertArray: function convertArray(array, type, forceClone) {n if (!array || // let 'undefined' and 'null' passn !forceClone && array.constructor === type) return array;nn if (typeof type.BYTES_PER_ELEMENT === 'number') {n return new type(array); // create typed arrayn }nn return Array.prototype.slice.call(array); // create Arrayn },n isTypedArray: function isTypedArray(object) {n return ArrayBuffer.isView(object) && !(object instanceof DataView);n },n // returns an array by which times and values can be sortedn getKeyframeOrder: function getKeyframeOrder(times) {n function compareTime(i, j) {n return times - times;n }nn var n = times.length;n var result = new Array(n);nn for (var i = 0; i !== n; ++i) {n result = i;n }nn result.sort(compareTime);n return result;n },n // uses the array previously returned by 'getKeyframeOrder' to sort datan sortedArray: function sortedArray(values, stride, order) {n var nValues = values.length;n var result = new values.constructor(nValues);nn for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {n var srcOffset = order * stride;nn for (var j = 0; j !== stride; ++j) {n result = values[srcOffset + j];n }n }nn return result;n },n // function for parsing AOS keyframe formatsn flattenJSON: function flattenJSON(jsonKeys, times, values, valuePropertyName) {n var i = 1,n key = jsonKeys;nn while (key !== undefined && key === undefined) {n key = jsonKeys;n }nn if (key === undefined) return; // no datann var value = key;n if (value === undefined) return; // no datann if (Array.isArray(value)) {n do {n value = key;nn if (value !== undefined) {n times.push(key.time);n values.push.apply(values, value); // push all elementsn }nn key = jsonKeys;n } while (key !== undefined);n } else if (value.toArray !== undefined) {n // …assume THREE.Math-ishn do {n value = key;nn if (value !== undefined) {n times.push(key.time);n value.toArray(values, values.length);n }nn key = jsonKeys;n } while (key !== undefined);n } else {n // otherwise push as-isn do {n value = key;nn if (value !== undefined) {n times.push(key.time);n values.push(value);n }nn key = jsonKeys;n } while (key !== undefined);n }n }n};n/**n * Abstract base class of interpolants over parametric samples.n *n * The parameter domain is one dimensional, typically the time or a pathn * along a curve defined by the data.n *n * The sample values can have any dimensionality and derived classes mayn * apply special interpretations to the data.n *n * This class provides the interval seek in a Template Method
, deferringn * the actual interpolation to derived classes.n *n * Time complexity is O(1) for linear access crossing at most two pointsn * and O(log N) for random access, where N is the number of positions.n *n * References:n *n * ttwww.oodesign.com/template-method-pattern.htmln *n * @author tschwn */nnfunction Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {n this.parameterPositions = parameterPositions;n this._cachedIndex = 0;n this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);n this.sampleValues = sampleValues;n this.valueSize = sampleSize;n}nnObject.assign(Interpolant.prototype, {n evaluate: function evaluate(t) {n var pp = this.parameterPositions,n i1 = this._cachedIndex,n t1 = pp,n t0 = pp[i1 - 1];nn validate_interval: {n seek: {n var right;nn linear_scan: {n //- See jsperf.com/comparison-to-undefined/3n //- slower code:n //-n //- ttttif ( t >= t1 || t1 === undefined ) {n forward_scan: if (!(t < t1)) {n for (var giveUpAt = i1 + 2;;) {n if (t1 === undefined) {n if (t < t0) break forward_scan; // after endnn i1 = pp.length;n this._cachedIndex = i1;n return this.afterEnd_(i1 - 1, t, t0);n }nn if (i1 === giveUpAt) break; // this loopnn t0 = t1;n t1 = pp;nn if (t < t1) {n // we have arrived at the sought intervaln break seek;n }n } // prepare binary search on the right side of the indexnnn right = pp.length;n break linear_scan;n } //- slower code:n //-tttttif ( t < t0 || t0 === undefined ) {nnn if (!(t >= t0)) {n // looping?n var t1global = pp;nn if (t < t1global) {n i1 = 2; // + 1, using the scan for the detailsnn t0 = t1global;n } // linear reverse scannnn for (var giveUpAt = i1 - 2;;) {n if (t0 === undefined) {n // before startn this._cachedIndex = 0;n return this.beforeStart_(0, t, t1);n }nn if (i1 === giveUpAt) break; // this loopnn t1 = t0;n t0 = pp[–i1 - 1];nn if (t >= t0) {n // we have arrived at the sought intervaln break seek;n }n } // prepare binary search on the left side of the indexnnn right = i1;n i1 = 0;n break linear_scan;n } // the interval is validnnn break validate_interval;n } // linear scann // binary searchnnn while (i1 < right) {n var mid = i1 + right >>> 1;nn if (t < pp) {n right = mid;n } else {n i1 = mid + 1;n }n }nn t1 = pp;n t0 = pp[i1 - 1]; // check boundary cases, againnn if (t0 === undefined) {n this._cachedIndex = 0;n return this.beforeStart_(0, t, t1);n }nn if (t1 === undefined) {n i1 = pp.length;n this._cachedIndex = i1;n return this.afterEnd_(i1 - 1, t0, t);n }n } // seeknnn this._cachedIndex = i1;n this.intervalChanged_(i1, t0, t1);n } // validate_intervalnnn return this.interpolate_(i1, t0, t, t1);n },n settings: null,n // optional, subclass-specific settings structuren // Note: The indirection allows central control of many interpolants.n // — Protected interfacen DefaultSettings_: {},n getSettings_: function getSettings_() {n return this.settings || this.DefaultSettings_;n },n copySampleValue_: function copySampleValue_(index) {n // copies a sample value to the result buffern var result = this.resultBuffer,n values = this.sampleValues,n stride = this.valueSize,n offset = index * stride;nn for (var i = 0; i !== stride; ++i) {n result = values[offset + i];n }nn return result;n },n // Template methods for derived classes:n interpolate_: function interpolate_()n /* i1, t0, t, t1 */n {n throw new Error('call to abstract method'); // implementations shall return this.resultBuffern },n intervalChanged_: function intervalChanged_()n /* i1, t0, t1 */n {// emptyn }n}); //!\ DECLARE ALIAS AFTER assign prototype !nnObject.assign(Interpolant.prototype, {n //( 0, t, t0 ), returns this.resultBuffern beforeStart_: Interpolant.prototype.copySampleValue_,n //( N-1, tN-1, t ), returns this.resultBuffern afterEnd_: Interpolant.prototype.copySampleValue_n});n/**n * Fast and simple cubic spline interpolant.n *n * It was derived from a Hermitian construction setting the first derivativen * at each sample position to the linear slope between neighboring positionsn * over their parameter interval.n *n * @author tschwn */nnfunction CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {n Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);n this._weightPrev = -0;n this._offsetPrev = -0;n this._weightNext = -0;n this._offsetNext = -0;n}nnCubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {n constructor: CubicInterpolant,n DefaultSettings_: {n endingStart: ZeroCurvatureEnding,n endingEnd: ZeroCurvatureEndingn },n intervalChanged_: function intervalChanged_(i1, t0, t1) {n var pp = this.parameterPositions,n iPrev = i1 - 2,n iNext = i1 + 1,n tPrev = pp,n tNext = pp;nn if (tPrev === undefined) {n switch (this.getSettings_().endingStart) {n case ZeroSlopeEnding:n // f'(t0) = 0n iPrev = i1;n tPrev = 2 * t0 - t1;n break;nn case WrapAroundEnding:n // use the other end of the curven iPrev = pp.length - 2;n tPrev = t0 + pp - pp[iPrev + 1];n break;nn default:n // ZeroCurvatureEndingn // f''(t0) = 0 a.k.a. Natural Splinen iPrev = i1;n tPrev = t1;n }n }nn if (tNext === undefined) {n switch (this.getSettings_().endingEnd) {n case ZeroSlopeEnding:n // f'(tN) = 0n iNext = i1;n tNext = 2 * t1 - t0;n break;nn case WrapAroundEnding:n // use the other end of the curven iNext = 1;n tNext = t1 + pp - pp;n break;nn default:n // ZeroCurvatureEndingn // f''(tN) = 0, a.k.a. Natural Splinen iNext = i1 - 1;n tNext = t0;n }n }nn var halfDt = (t1 - t0) * 0.5,n stride = this.valueSize;n this._weightPrev = halfDt / (t0 - tPrev);n this._weightNext = halfDt / (tNext - t1);n this._offsetPrev = iPrev * stride;n this._offsetNext = iNext * stride;n },n interpolate_: function interpolate_(i1, t0, t, t1) {n var result = this.resultBuffer,n values = this.sampleValues,n stride = this.valueSize,n o1 = i1 * stride,n o0 = o1 - stride,n oP = this._offsetPrev,n oN = this._offsetNext,n wP = this._weightPrev,n wN = this._weightNext,n p = (t - t0) / (t1 - t0),n pp = p * p,n ppp = pp * p; // evaluate polynomialsnn var sP = -wP * ppp + 2 * wP * pp - wP * p;n var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;n var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;n var sN = wN * ppp - wN * pp; // combine data linearlynn for (var i = 0; i !== stride; ++i) {n result = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];n }nn return result;n }n});n/**n * @author tschwn */nnfunction LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {n Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);n}nnLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {n constructor: LinearInterpolant,n interpolate_: function interpolate_(i1, t0, t, t1) {n var result = this.resultBuffer,n values = this.sampleValues,n stride = this.valueSize,n offset1 = i1 * stride,n offset0 = offset1 - stride,n weight1 = (t - t0) / (t1 - t0),n weight0 = 1 - weight1;nn for (var i = 0; i !== stride; ++i) {n result = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;n }nn return result;n }n});n/**n *n * Interpolant that evaluates to the sample value at the position preceedingn * the parameter.n *n * @author tschwn */nnfunction DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {n Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);n}nnDiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {n constructor: DiscreteInterpolant,n interpolate_: function interpolate_(i1n /*, t0, t, t1 */n ) {n return this.copySampleValue_(i1 - 1);n }n});n/**n *n * A timed sequence of keyframes for a specific property.n *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction KeyframeTrack(name, times, values, interpolation) {n if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');n if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);n this.name = name;n this.times = AnimationUtils.convertArray(times, this.TimeBufferType);n this.values = AnimationUtils.convertArray(values, this.ValueBufferType);n this.setInterpolation(interpolation || this.DefaultInterpolation);n} // Static methodsnnnObject.assign(KeyframeTrack, {n // Serialization (in static context, because of constructor invocationn // and automatic invocation of .toJSON):n toJSON: function toJSON(track) {n var trackType = track.constructor;n var json; // derived classes can define a static toJSON methodnn if (trackType.toJSON !== undefined) {n json = trackType.toJSON(track);n } else {n // by default, we assume the data can be serialized as-isn json = {n 'name': track.name,n 'times': AnimationUtils.convertArray(track.times, Array),n 'values': AnimationUtils.convertArray(track.values, Array)n };n var interpolation = track.getInterpolation();nn if (interpolation !== track.DefaultInterpolation) {n json.interpolation = interpolation;n }n }nn json.type = track.ValueTypeName; // mandatorynn return json;n }n});nObject.assign(KeyframeTrack.prototype, {n constructor: KeyframeTrack,n TimeBufferType: Float32Array,n ValueBufferType: Float32Array,n DefaultInterpolation: InterpolateLinear,n InterpolantFactoryMethodDiscrete: function InterpolantFactoryMethodDiscrete(result) {n return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);n },n InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {n return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);n },n InterpolantFactoryMethodSmooth: function InterpolantFactoryMethodSmooth(result) {n return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);n },n setInterpolation: function setInterpolation(interpolation) {n var factoryMethod;nn switch (interpolation) {n case InterpolateDiscrete:n factoryMethod = this.InterpolantFactoryMethodDiscrete;n break;nn case InterpolateLinear:n factoryMethod = this.InterpolantFactoryMethodLinear;n break;nn case InterpolateSmooth:n factoryMethod = this.InterpolantFactoryMethodSmooth;n break;n }nn if (factoryMethod === undefined) {n var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;nn if (this.createInterpolant === undefined) {n // fall back to default, unless the default itself is messed upn if (interpolation !== this.DefaultInterpolation) {n this.setInterpolation(this.DefaultInterpolation);n } else {n throw new Error(message); // fatal, in this casen }n }nn console.warn('THREE.KeyframeTrack:', message);n return this;n }nn this.createInterpolant = factoryMethod;n return this;n },n getInterpolation: function getInterpolation() {n switch (this.createInterpolant) {n case this.InterpolantFactoryMethodDiscrete:n return InterpolateDiscrete;nn case this.InterpolantFactoryMethodLinear:n return InterpolateLinear;nn case this.InterpolantFactoryMethodSmooth:n return InterpolateSmooth;n }n },n getValueSize: function getValueSize() {n return this.values.length / this.times.length;n },n // move all keyframes either forwards or backwards in timen shift: function shift(timeOffset) {n if (timeOffset !== 0.0) {n var times = this.times;nn for (var i = 0, n = times.length; i !== n; ++i) {n times += timeOffset;n }n }nn return this;n },n // scale all keyframe times by a factor (useful for frame <-> seconds conversions)n scale: function scale(timeScale) {n if (timeScale !== 1.0) {n var times = this.times;nn for (var i = 0, n = times.length; i !== n; ++i) {n times *= timeScale;n }n }nn return this;n },n // removes keyframes before and after animation without changing any values within the range [startTime, endTime].n // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their valuesn trim: function trim(startTime, endTime) {n var times = this.times,n nKeys = times.length,n from = 0,n to = nKeys - 1;nn while (from !== nKeys && times < startTime) {n ++from;n }nn while (to !== -1 && times > endTime) {n –to;n }nn ++to; // inclusive -> exclusive boundnn if (from !== 0 || to !== nKeys) {n // empty tracks are forbidden, so keep at least one keyframen if (from >= to) to = Math.max(to, 1), from = to - 1;n var stride = this.getValueSize();n this.times = AnimationUtils.arraySlice(times, from, to);n this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);n }nn return this;n },n // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viablen validate: function validate() {n var valid = true;n var valueSize = this.getValueSize();nn if (valueSize - Math.floor(valueSize) !== 0) {n console.error('THREE.KeyframeTrack: Invalid value size in track.', this);n valid = false;n }nn var times = this.times,n values = this.values,n nKeys = times.length;nn if (nKeys === 0) {n console.error('THREE.KeyframeTrack: Track is empty.', this);n valid = false;n }nn var prevTime = null;nn for (var i = 0; i !== nKeys; i++) {n var currTime = times;nn if (typeof currTime === 'number' && isNaN(currTime)) {n console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);n valid = false;n break;n }nn if (prevTime !== null && prevTime > currTime) {n console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);n valid = false;n break;n }nn prevTime = currTime;n }nn if (values !== undefined) {n if (AnimationUtils.isTypedArray(values)) {n for (var i = 0, n = values.length; i !== n; ++i) {n var value = values;nn if (isNaN(value)) {n console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);n valid = false;n break;n }n }n }n }nn return valid;n },n // removes equivalent sequential keys as common in morph target sequencesn // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) –> (0,0,1,1,0,0)n optimize: function optimize() {n var times = this.times,n values = this.values,n stride = this.getValueSize(),n smoothInterpolation = this.getInterpolation() === InterpolateSmooth,n writeIndex = 1,n lastIndex = times.length - 1;nn for (var i = 1; i < lastIndex; ++i) {n var keep = false;n var time = times;n var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same timenn if (time !== timeNext && (i !== 1 || time !== time)) {n if (!smoothInterpolation) {n // remove unnecessary keyframes same as their neighborsn var offset = i * stride,n offsetP = offset - stride,n offsetN = offset + stride;nn for (var j = 0; j !== stride; ++j) {n var value = values[offset + j];nn if (value !== values[offsetP + j] || value !== values[offsetN + j]) {n keep = true;n break;n }n }n } else {n keep = true;n }n } // in-place compactionnnn if (keep) {n if (i !== writeIndex) {n times = times;n var readOffset = i * stride,n writeOffset = writeIndex * stride;nn for (var j = 0; j !== stride; ++j) {n values[writeOffset + j] = values[readOffset + j];n }n }nn ++writeIndex;n }n } // flush last keyframe (compaction looks ahead)nnn if (lastIndex > 0) {n times = times;nn for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {n values[writeOffset + j] = values[readOffset + j];n }nn ++writeIndex;n }nn if (writeIndex !== times.length) {n this.times = AnimationUtils.arraySlice(times, 0, writeIndex);n this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);n }nn return this;n },n clone: function clone() {n var times = AnimationUtils.arraySlice(this.times, 0);n var values = AnimationUtils.arraySlice(this.values, 0);n var TypedKeyframeTrack = this.constructor;n var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.nn track.createInterpolant = this.createInterpolant;n return track;n }n});n/**n *n * A Track of Boolean keyframe values.n *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction BooleanKeyframeTrack(name, times, values) {n KeyframeTrack.call(this, name, times, values);n}nnBooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {n constructor: BooleanKeyframeTrack,n ValueTypeName: 'bool',n ValueBufferType: Array,n DefaultInterpolation: InterpolateDiscrete,n InterpolantFactoryMethodLinear: undefined,n InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressedn // representation of a single value and a custom interpolant thatn // computes "firstValue ^ isOdd( index )".nn});n/**n *n * A Track of keyframe values that represent color.n *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction ColorKeyframeTrack(name, times, values, interpolation) {n KeyframeTrack.call(this, name, times, values, interpolation);n}nnColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {n constructor: ColorKeyframeTrack,n ValueTypeName: 'color' // ValueBufferType is inheritedn // DefaultInterpolation is inheritedn // Note: Very basic implementation and nothing special yet.n // However, this is the place for color space parameterization.nn});n/**n *n * A Track of numeric keyframe values.n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction NumberKeyframeTrack(name, times, values, interpolation) {n KeyframeTrack.call(this, name, times, values, interpolation);n}nnNumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {n constructor: NumberKeyframeTrack,n ValueTypeName: 'number' // ValueBufferType is inheritedn // DefaultInterpolation is inheritednn});n/**n * Spherical linear unit quaternion interpolant.n *n * @author tschwn */nnfunction QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {n Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);n}nnQuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {n constructor: QuaternionLinearInterpolant,n interpolate_: function interpolate_(i1, t0, t, t1) {n var result = this.resultBuffer,n values = this.sampleValues,n stride = this.valueSize,n offset = i1 * stride,n alpha = (t - t0) / (t1 - t0);nn for (var end = offset + stride; offset !== end; offset += 4) {n Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);n }nn return result;n }n});n/**n *n * A Track of quaternion keyframe values.n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction QuaternionKeyframeTrack(name, times, values, interpolation) {n KeyframeTrack.call(this, name, times, values, interpolation);n}nnQuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {n constructor: QuaternionKeyframeTrack,n ValueTypeName: 'quaternion',n // ValueBufferType is inheritedn DefaultInterpolation: InterpolateLinear,n InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {n return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);n },n InterpolantFactoryMethodSmooth: undefined // not yet implementednn});n/**n *n * A Track that interpolates Stringsn *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction StringKeyframeTrack(name, times, values, interpolation) {n KeyframeTrack.call(this, name, times, values, interpolation);n}nnStringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {n constructor: StringKeyframeTrack,n ValueTypeName: 'string',n ValueBufferType: Array,n DefaultInterpolation: InterpolateDiscrete,n InterpolantFactoryMethodLinear: undefined,n InterpolantFactoryMethodSmooth: undefinedn});n/**n *n * A Track of vectored keyframe values.n *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction VectorKeyframeTrack(name, times, values, interpolation) {n KeyframeTrack.call(this, name, times, values, interpolation);n}nnVectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {n constructor: VectorKeyframeTrack,n ValueTypeName: 'vector' // ValueBufferType is inheritedn // DefaultInterpolation is inheritednn});n/**n *n * Reusable set of Tracks that represent an animation.n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n */nnfunction AnimationClip(name, duration, tracks) {n this.name = name;n this.tracks = tracks;n this.duration = duration !== undefined ? duration : -1;n this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracksnn if (this.duration < 0) {n this.resetDuration();n }n}nnfunction getTrackTypeForValueTypeName(typeName) {n switch (typeName.toLowerCase()) {n case 'scalar':n case 'double':n case 'float':n case 'number':n case 'integer':n return NumberKeyframeTrack;nn case 'vector':n case 'vector2':n case 'vector3':n case 'vector4':n return VectorKeyframeTrack;nn case 'color':n return ColorKeyframeTrack;nn case 'quaternion':n return QuaternionKeyframeTrack;nn case 'bool':n case 'boolean':n return BooleanKeyframeTrack;nn case 'string':n return StringKeyframeTrack;n }nn throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);n}nnfunction parseKeyframeTrack(json) {n if (json.type === undefined) {n throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');n }nn var trackType = getTrackTypeForValueTypeName(json.type);nn if (json.times === undefined) {n var times = [],n values = [];n AnimationUtils.flattenJSON(json.keys, times, values, 'value');n json.times = times;n json.values = values;n } // derived classes can define a static parse methodnnn if (trackType.parse !== undefined) {n return trackType.parse(json);n } else {n // by default, we assume a constructor compatible with the basen return new trackType(json.name, json.times, json.values, json.interpolation);n }n}nnObject.assign(AnimationClip, {n parse: function parse(json) {n var tracks = [],n jsonTracks = json.tracks,n frameTime = 1.0 / (json.fps || 1.0);nn for (var i = 0, n = jsonTracks.length; i !== n; ++i) {n tracks.push(parseKeyframeTrack(jsonTracks).scale(frameTime));n }nn return new AnimationClip(json.name, json.duration, tracks);n },n toJSON: function toJSON(clip) {n var tracks = [],n clipTracks = clip.tracks;n var json = {n 'name': clip.name,n 'duration': clip.duration,n 'tracks': tracks,n 'uuid': clip.uuidn };nn for (var i = 0, n = clipTracks.length; i !== n; ++i) {n tracks.push(KeyframeTrack.toJSON(clipTracks));n }nn return json;n },n CreateFromMorphTargetSequence: function CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {n var numMorphTargets = morphTargetSequence.length;n var tracks = [];nn for (var i = 0; i < numMorphTargets; i++) {n var times = [];n var values = [];n times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);n values.push(0, 1, 0);n var order = AnimationUtils.getKeyframeOrder(times);n times = AnimationUtils.sortedArray(times, 1, order);n values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as then // last frame as well for perfect loop.nn if (!noLoop && times === 0) {n times.push(numMorphTargets);n values.push(values);n }nn tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence.name + ']', times, values).scale(1.0 / fps));n }nn return new AnimationClip(name, -1, tracks);n },n findByName: function findByName(objectOrClipArray, name) {n var clipArray = objectOrClipArray;nn if (!Array.isArray(objectOrClipArray)) {n var o = objectOrClipArray;n clipArray = o.geometry && o.geometry.animations || o.animations;n }nn for (var i = 0; i < clipArray.length; i++) {n if (clipArray.name === name) {n return clipArray;n }n }nn return null;n },n CreateClipsFromMorphTargetSequences: function CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {n var animationToMorphTargets = {}; // tested with regex101.com/ on trick sequencesn // such flamingo_flyA_003, flamingo_run1_003, crdeath0059nn var pattern = /^([\w-]*?)(+)$/; // sort morph target names into animation groups basedn // patterns like Walk_001, Walk_002, Run_001, Run_002nn for (var i = 0, il = morphTargets.length; i < il; i++) {n var morphTarget = morphTargets;n var parts = morphTarget.name.match(pattern);nn if (parts && parts.length > 1) {n var name = parts;n var animationMorphTargets = animationToMorphTargets;nn if (!animationMorphTargets) {n animationToMorphTargets = animationMorphTargets = [];n }nn animationMorphTargets.push(morphTarget);n }n }nn var clips = [];nn for (var name in animationToMorphTargets) {n clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets, fps, noLoop));n }nn return clips;n },n // parse the animation.hierarchy formatn parseAnimation: function parseAnimation(animation, bones) {n if (!animation) {n console.error('THREE.AnimationClip: No animation in JSONLoader data.');n return null;n }nn var addNonemptyTrack = function addNonemptyTrack(trackType, trackName, animationKeys, propertyName, destTracks) {n // only return track if there are actually keys.n if (animationKeys.length !== 0) {n var times = [];n var values = [];n AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check againnn if (times.length !== 0) {n destTracks.push(new trackType(trackName, times, values));n }n }n };nn var tracks = [];n var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.nn var duration = animation.length || -1;n var fps = animation.fps || 30;n var hierarchyTracks = animation.hierarchy || [];nn for (var h = 0; h < hierarchyTracks.length; h++) {n var animationKeys = hierarchyTracks.keys; // skip empty tracksnn if (!animationKeys || animationKeys.length === 0) continue; // process morph targetsnn if (animationKeys.morphTargets) {n // figure out all morph targets used in this trackn var morphTargetNames = {};nn for (var k = 0; k < animationKeys.length; k++) {n if (animationKeys.morphTargets) {n for (var m = 0; m < animationKeys.morphTargets.length; m++) {n morphTargetNames[animationKeys.morphTargets] = -1;n }n }n } // create a track for each morph target with all zeron // morphTargetInfluences except for the keys in whichn // the morphTarget is named.nnn for (var morphTargetName in morphTargetNames) {n var times = [];n var values = [];nn for (var m = 0; m !== animationKeys.morphTargets.length; ++m) {n var animationKey = animationKeys;n times.push(animationKey.time);n values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);n }nn tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));n }nn duration = morphTargetNames.length * (fps || 1.0);n } else {n // …assume skeletal animationn var boneName = '.bones[' + bones.name + ']';n addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);n addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);n addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);n }n }nn if (tracks.length === 0) {n return null;n }nn var clip = new AnimationClip(clipName, duration, tracks);n return clip;n }n});nObject.assign(AnimationClip.prototype, {n resetDuration: function resetDuration() {n var tracks = this.tracks,n duration = 0;nn for (var i = 0, n = tracks.length; i !== n; ++i) {n var track = this.tracks;n duration = Math.max(duration, track.times[track.times.length - 1]);n }nn this.duration = duration;n return this;n },n trim: function trim() {n for (var i = 0; i < this.tracks.length; i++) {n this.tracks.trim(0, this.duration);n }nn return this;n },n validate: function validate() {n var valid = true;nn for (var i = 0; i < this.tracks.length; i++) {n valid = valid && this.tracks.validate();n }nn return valid;n },n optimize: function optimize() {n for (var i = 0; i < this.tracks.length; i++) {n this.tracks.optimize();n }nn return this;n },n clone: function clone() {n var tracks = [];nn for (var i = 0; i < this.tracks.length; i++) {n tracks.push(this.tracks.clone());n }nn return new AnimationClip(this.name, this.duration, tracks);n }n});n/**n * @author mrdoob / mrdoob.com/n */nnvar Cache = {n enabled: false,n files: {},n add: function add(key, file) {n if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );nn this.files = file;n },n get: function get(key) {n if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );nn return this.files;n },n remove: function remove(key) {n delete this.files;n },n clear: function clear() {n this.files = {};n }n};n/**n * @author mrdoob / mrdoob.com/n */nnfunction LoadingManager(onLoad, onProgress, onError) {n var scope = this;n var isLoading = false;n var itemsLoaded = 0;n var itemsTotal = 0;n var urlModifier = undefined; // Refer to #5689 for the reason why we don't set .onStartn // in the constructornn this.onStart = undefined;n this.onLoad = onLoad;n this.onProgress = onProgress;n this.onError = onError;nn this.itemStart = function (url) {n itemsTotal++;nn if (isLoading === false) {n if (scope.onStart !== undefined) {n scope.onStart(url, itemsLoaded, itemsTotal);n }n }nn isLoading = true;n };nn this.itemEnd = function (url) {n itemsLoaded++;nn if (scope.onProgress !== undefined) {n scope.onProgress(url, itemsLoaded, itemsTotal);n }nn if (itemsLoaded === itemsTotal) {n isLoading = false;nn if (scope.onLoad !== undefined) {n scope.onLoad();n }n }n };nn this.itemError = function (url) {n if (scope.onError !== undefined) {n scope.onError(url);n }n };nn this.resolveURL = function (url) {n if (urlModifier) {n return urlModifier(url);n }nn return url;n };nn this.setURLModifier = function (transform) {n urlModifier = transform;n return this;n };n}nnvar DefaultLoadingManager = new LoadingManager();n/**n * @author alteredq / alteredqualia.com/n */nnfunction Loader(manager) {n this.manager = manager !== undefined ? manager : DefaultLoadingManager;n this.crossOrigin = 'anonymous';n this.path = '';n this.resourcePath = '';n}nnObject.assign(Loader.prototype, {n load: function load()n /* url, onLoad, onProgress, onError */n {},n parse: function parse()n /* data */n {},n setCrossOrigin: function setCrossOrigin(crossOrigin) {n this.crossOrigin = crossOrigin;n return this;n },n setPath: function setPath(path) {n this.path = path;n return this;n },n setResourcePath: function setResourcePath(resourcePath) {n this.resourcePath = resourcePath;n return this;n }n}); //nnLoader.Handlers = {n handlers: [],n add: function add(regex, loader) {n this.handlers.push(regex, loader);n },n get: function get(file) {n var handlers = this.handlers;nn for (var i = 0, l = handlers.length; i < l; i += 2) {n var regex = handlers;n var loader = handlers[i + 1];nn if (regex.test(file)) {n return loader;n }n }nn return null;n }n};n/**n * @author mrdoob / mrdoob.com/n */nnvar loading = {};nnfunction FileLoader(manager) {n Loader.call(this, manager);n}nnFileLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: FileLoader,n load: function load(url, onLoad, onProgress, onError) {n if (url === undefined) url = '';n if (this.path !== undefined) url = this.path + url;n url = this.manager.resolveURL(url);n var scope = this;n var cached = Cache.get(url);nn if (cached !== undefined) {n scope.manager.itemStart(url);n setTimeout(function () {n if (onLoad) onLoad(cached);n scope.manager.itemEnd(url);n }, 0);n return cached;n } // Check if request is duplicatennn if (loading !== undefined) {n loading.push({n onLoad: onLoad,n onProgress: onProgress,n onError: onErrorn });n return;n } // Check for data: URInnn var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;n var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manuallynn if (dataUriRegexResult) {n var mimeType = dataUriRegexResult;n var isBase64 = !!dataUriRegexResult;n var data = dataUriRegexResult;n data = decodeURIComponent(data);n if (isBase64) data = atob(data);nn try {n var response;n var responseType = (this.responseType || '').toLowerCase();nn switch (responseType) {n case 'arraybuffer':n case 'blob':n var view = new Uint8Array(data.length);nn for (var i = 0; i < data.length; i++) {n view = data.charCodeAt(i);n }nn if (responseType === 'blob') {n response = new Blob(, {n type: mimeTypen });n } else {n response = view.buffer;n }nn break;nn case 'document':n var parser = new DOMParser();n response = parser.parseFromString(data, mimeType);n break;nn case 'json':n response = JSON.parse(data);n break;nn default:n // 'text' or othern response = data;n break;n } // Wait for next browser tick like standard XMLHttpRequest event dispatching doesnnn setTimeout(function () {n if (onLoad) onLoad(response);n scope.manager.itemEnd(url);n }, 0);n } catch (error) {n // Wait for next browser tick like standard XMLHttpRequest event dispatching doesn setTimeout(function () {n if (onError) onError(error);n scope.manager.itemError(url);n scope.manager.itemEnd(url);n }, 0);n }n } else {n // Initialise array for duplicate requestsn loading = [];n loading.push({n onLoad: onLoad,n onProgress: onProgress,n onError: onErrorn });n var request = new XMLHttpRequest();n request.open('GET', url, true);n request.addEventListener('load', function (event) {n var response = this.response;n Cache.add(url, response);n var callbacks = loading;n delete loading;nn if (this.status === 200 || this.status === 0) {n // Some browsers return HTTP Status 0 when using non-http protocoln // e.g. 'file://' or 'data://'. Handle as success.n if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');nn for (var i = 0, il = callbacks.length; i < il; i++) {n var callback = callbacks;n if (callback.onLoad) callback.onLoad(response);n }nn scope.manager.itemEnd(url);n } else {n for (var i = 0, il = callbacks.length; i < il; i++) {n var callback = callbacks;n if (callback.onError) callback.onError(event);n }nn scope.manager.itemError(url);n scope.manager.itemEnd(url);n }n }, false);n request.addEventListener('progress', function (event) {n var callbacks = loading;nn for (var i = 0, il = callbacks.length; i < il; i++) {n var callback = callbacks;n if (callback.onProgress) callback.onProgress(event);n }n }, false);n request.addEventListener('error', function (event) {n var callbacks = loading;n delete loading;nn for (var i = 0, il = callbacks.length; i < il; i++) {n var callback = callbacks;n if (callback.onError) callback.onError(event);n }nn scope.manager.itemError(url);n scope.manager.itemEnd(url);n }, false);n request.addEventListener('abort', function (event) {n var callbacks = loading;n delete loading;nn for (var i = 0, il = callbacks.length; i < il; i++) {n var callback = callbacks;n if (callback.onError) callback.onError(event);n }nn scope.manager.itemError(url);n scope.manager.itemEnd(url);n }, false);n if (this.responseType !== undefined) request.responseType = this.responseType;n if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;n if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');nn for (var header in this.requestHeader) {n request.setRequestHeader(header, this.requestHeader);n }nn request.send(null);n }nn scope.manager.itemStart(url);n return request;n },n setResponseType: function setResponseType(value) {n this.responseType = value;n return this;n },n setWithCredentials: function setWithCredentials(value) {n this.withCredentials = value;n return this;n },n setMimeType: function setMimeType(value) {n this.mimeType = value;n return this;n },n setRequestHeader: function setRequestHeader(value) {n this.requestHeader = value;n return this;n }n});n/**n * @author bhouston / clara.io/n */nnfunction AnimationLoader(manager) {n Loader.call(this, manager);n}nnAnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: AnimationLoader,n load: function load(url, onLoad, onProgress, onError) {n var scope = this;n var loader = new FileLoader(scope.manager);n loader.setPath(scope.path);n loader.load(url, function (text) {n onLoad(scope.parse(JSON.parse(text)));n }, onProgress, onError);n },n parse: function parse(json) {n var animations = [];nn for (var i = 0; i < json.length; i++) {n var clip = AnimationClip.parse(json);n animations.push(clip);n }nn return animations;n }n});n/**n * @author mrdoob / mrdoob.com/n *n * Abstract Base class to block based textures loader (dds, pvr, …)n */nnfunction CompressedTextureLoader(manager) {n Loader.call(this, manager); // override in sub classesnn this._parser = null;n}nnCompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: CompressedTextureLoader,n load: function load(url, onLoad, onProgress, onError) {n var scope = this;n var images = [];n var texture = new CompressedTexture();n texture.image = images;n var loader = new FileLoader(this.manager);n loader.setPath(this.path);n loader.setResponseType('arraybuffer');nn function loadTexture(i) {n loader.load(url, function (buffer) {n var texDatas = scope._parser(buffer, true);nn images = {n width: texDatas.width,n height: texDatas.height,n format: texDatas.format,n mipmaps: texDatas.mipmapsn };n loaded += 1;nn if (loaded === 6) {n if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;n texture.format = texDatas.format;n texture.needsUpdate = true;n if (onLoad) onLoad(texture);n }n }, onProgress, onError);n }nn if (Array.isArray(url)) {n var loaded = 0;nn for (var i = 0, il = url.length; i < il; ++i) {n loadTexture(i);n }n } else {n // compressed cubemap texture stored in a single DDS filen loader.load(url, function (buffer) {n var texDatas = scope._parser(buffer, true);nn if (texDatas.isCubemap) {n var faces = texDatas.mipmaps.length / texDatas.mipmapCount;nn for (var f = 0; f < faces; f++) {n images = {n mipmaps: []n };nn for (var i = 0; i < texDatas.mipmapCount; i++) {n images.mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);n images.format = texDatas.format;n images.width = texDatas.width;n images.height = texDatas.height;n }n }n } else {n texture.image.width = texDatas.width;n texture.image.height = texDatas.height;n texture.mipmaps = texDatas.mipmaps;n }nn if (texDatas.mipmapCount === 1) {n texture.minFilter = LinearFilter;n }nn texture.format = texDatas.format;n texture.needsUpdate = true;n if (onLoad) onLoad(texture);n }, onProgress, onError);n }nn return texture;n }n});n/**n * @author Nikos M. / github.com/foo123/n *n * Abstract Base class to load generic binary textures formats (rgbe, hdr, …)n */nnfunction DataTextureLoader(manager) {n Loader.call(this, manager); // override in sub classesnn this._parser = null;n}nnDataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: DataTextureLoader,n load: function load(url, onLoad, onProgress, onError) {n var scope = this;n var texture = new DataTexture();n var loader = new FileLoader(this.manager);n loader.setResponseType('arraybuffer');n loader.setPath(this.path);n loader.load(url, function (buffer) {n var texData = scope._parser(buffer);nn if (!texData) return;nn if (texData.image !== undefined) {n texture.image = texData.image;n } else if (texData.data !== undefined) {n texture.image.width = texData.width;n texture.image.height = texData.height;n texture.image.data = texData.data;n }nn texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;n texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;n texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;n texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;n texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;nn if (texData.format !== undefined) {n texture.format = texData.format;n }nn if (texData.type !== undefined) {n texture.type = texData.type;n }nn if (texData.mipmaps !== undefined) {n texture.mipmaps = texData.mipmaps;n }nn if (texData.mipmapCount === 1) {n texture.minFilter = LinearFilter;n }nn texture.needsUpdate = true;n if (onLoad) onLoad(texture, texData);n }, onProgress, onError);n return texture;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction ImageLoader(manager) {n Loader.call(this, manager);n}nnImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: ImageLoader,n load: function load(url, onLoad, onProgress, onError) {n if (this.path !== undefined) url = this.path + url;n url = this.manager.resolveURL(url);n var scope = this;n var cached = Cache.get(url);nn if (cached !== undefined) {n scope.manager.itemStart(url);n setTimeout(function () {n if (onLoad) onLoad(cached);n scope.manager.itemEnd(url);n }, 0);n return cached;n }nn var image = document.createElementNS('www.w3.org/1999/xhtml', 'img');nn function onImageLoad() {n image.removeEventListener('load', onImageLoad, false);n image.removeEventListener('error', onImageError, false);n Cache.add(url, this);n if (onLoad) onLoad(this);n scope.manager.itemEnd(url);n }nn function onImageError(event) {n image.removeEventListener('load', onImageLoad, false);n image.removeEventListener('error', onImageError, false);n if (onError) onError(event);n scope.manager.itemError(url);n scope.manager.itemEnd(url);n }nn image.addEventListener('load', onImageLoad, false);n image.addEventListener('error', onImageError, false);nn if (url.substr(0, 5) !== 'data:') {n if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;n }nn scope.manager.itemStart(url);n image.src = url;n return image;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction CubeTextureLoader(manager) {n Loader.call(this, manager);n}nnCubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: CubeTextureLoader,n load: function load(urls, onLoad, onProgress, onError) {n var texture = new CubeTexture();n var loader = new ImageLoader(this.manager);n loader.setCrossOrigin(this.crossOrigin);n loader.setPath(this.path);n var loaded = 0;nn function loadTexture(i) {n loader.load(urls, function (image) {n texture.images = image;n loaded++;nn if (loaded === 6) {n texture.needsUpdate = true;n if (onLoad) onLoad(texture);n }n }, undefined, onError);n }nn for (var i = 0; i < urls.length; ++i) {n loadTexture(i);n }nn return texture;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction TextureLoader(manager) {n Loader.call(this, manager);n}nnTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: TextureLoader,n load: function load(url, onLoad, onProgress, onError) {n var texture = new Texture();n var loader = new ImageLoader(this.manager);n loader.setCrossOrigin(this.crossOrigin);n loader.setPath(this.path);n loader.load(url, function (image) {n texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.nn var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;n texture.format = isJPEG ? RGBFormat : RGBAFormat;n texture.needsUpdate = true;nn if (onLoad !== undefined) {n onLoad(texture);n }n }, onProgress, onError);n return texture;n }n});n/**n * @author zz85 / www.lab4games.net/zz85/blogn * Extensible curve objectn *n * Some common of curve methods:n * .getPoint( t, optionalTarget ), .getTangent( t )n * .getPointAt( u, optionalTarget ), .getTangentAt( u )n * .getPoints(), .getSpacedPoints()n * .getLength()n * .updateArcLengths()n *n * This following curves inherit from THREE.Curve:n *n * – 2D curves –n * THREE.ArcCurven * THREE.CubicBezierCurven * THREE.EllipseCurven * THREE.LineCurven * THREE.QuadraticBezierCurven * THREE.SplineCurven *n * – 3D curves –n * THREE.CatmullRomCurve3n * THREE.CubicBezierCurve3n * THREE.LineCurve3n * THREE.QuadraticBezierCurve3n *n * A series of curves can be represented as a THREE.CurvePath.n *n **/nn/**************************************************************n *tAbstract Curve base classn **************************************************************/nnfunction Curve() {n this.type = 'Curve';n this.arcLengthDivisions = 200;n}nnObject.assign(Curve.prototype, {n // Virtual base class method to overwrite and implement in subclassesn //t- t [0 .. 1]n getPoint: function getPoint()n /* t, optionalTarget */n {n console.warn('THREE.Curve: .getPoint() not implemented.');n return null;n },n // Get point at relative position in curve according to arc lengthn // - u [0 .. 1]n getPointAt: function getPointAt(u, optionalTarget) {n var t = this.getUtoTmapping(u);n return this.getPoint(t, optionalTarget);n },n // Get sequence of points using getPoint( t )n getPoints: function getPoints(divisions) {n if (divisions === undefined) divisions = 5;n var points = [];nn for (var d = 0; d <= divisions; d++) {n points.push(this.getPoint(d / divisions));n }nn return points;n },n // Get sequence of points using getPointAt( u )n getSpacedPoints: function getSpacedPoints(divisions) {n if (divisions === undefined) divisions = 5;n var points = [];nn for (var d = 0; d <= divisions; d++) {n points.push(this.getPointAt(d / divisions));n }nn return points;n },n // Get total curve arc lengthn getLength: function getLength() {n var lengths = this.getLengths();n return lengths[lengths.length - 1];n },n // Get list of cumulative segment lengthsn getLengths: function getLengths(divisions) {n if (divisions === undefined) divisions = this.arcLengthDivisions;nn if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {n return this.cacheArcLengths;n }nn this.needsUpdate = false;n var cache = [];n var current,n last = this.getPoint(0);n var p,n sum = 0;n cache.push(0);nn for (p = 1; p <= divisions; p++) {n current = this.getPoint(p / divisions);n sum += current.distanceTo(last);n cache.push(sum);n last = current;n }nn this.cacheArcLengths = cache;n return cache; // { sums: cache, sum: sum }; Sum is in the last element.n },n updateArcLengths: function updateArcLengths() {n this.needsUpdate = true;n this.getLengths();n },n // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistantn getUtoTmapping: function getUtoTmapping(u, distance) {n var arcLengths = this.getLengths();n var i = 0,n il = arcLengths.length;n var targetArcLength; // The targeted u distance value to getnn if (distance) {n targetArcLength = distance;n } else {n targetArcLength = u * arcLengths[il - 1];n } // binary search for the index with largest value smaller than target u distancennn var low = 0,n high = il - 1,n comparison;nn while (low <= high) {n 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 floatsnn comparison = arcLengths - targetArcLength;nn if (comparison < 0) {n low = i + 1;n } else if (comparison > 0) {n high = i - 1;n } else {n high = i;n break; // DONEn }n }nn i = high;nn if (arcLengths === targetArcLength) {n return i / (il - 1);n } // we could get finer grain at lengths, or use simple interpolation between two pointsnnn var lengthBefore = arcLengths;n var lengthAfter = arcLengths[i + 1];n var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' pointsnn var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to tnn var t = (i + segmentFraction) / (il - 1);n return t;n },n // Returns a unit vector tangent at tn // In case any sub curve does not implement its tangent derivation,n // 2 points a small delta apart will be used to find its gradientn // which seems to give a reasonable approximationn getTangent: function getTangent(t) {n var delta = 0.0001;n var t1 = t - delta;n var t2 = t + delta; // Capping in case of dangernn if (t1 < 0) t1 = 0;n if (t2 > 1) t2 = 1;n var pt1 = this.getPoint(t1);n var pt2 = this.getPoint(t2);n var vec = pt2.clone().sub(pt1);n return vec.normalize();n },n getTangentAt: function getTangentAt(u) {n var t = this.getUtoTmapping(u);n return this.getTangent(t);n },n computeFrenetFrames: function computeFrenetFrames(segments, closed) {n // see www.cs.indiana.edu/pub/techreports/TR425.pdfn var normal = new Vector3();n var tangents = [];n var normals = [];n var binormals = [];n var vec = new Vector3();n var mat = new Matrix4();n var i, u, theta; // compute the tangent vectors for each segment on the curvenn for (i = 0; i <= segments; i++) {n u = i / segments;n tangents = this.getTangentAt(u);n tangents.normalize();n } // select an initial normal vector perpendicular to the first tangent vector,n // and in the direction of the minimum tangent xyz componentnnn normals = new Vector3();n binormals = new Vector3();n var min = Number
.MAX_VALUE;n var tx = Math.abs(tangents.x);n var ty = Math.abs(tangents.y);n var tz = Math.abs(tangents.z);nn if (tx <= min) {n min = tx;n normal.set(1, 0, 0);n }nn if (ty <= min) {n min = ty;n normal.set(0, 1, 0);n }nn if (tz <= min) {n normal.set(0, 0, 1);n }nn vec.crossVectors(tangents, normal).normalize();n normals.crossVectors(tangents, vec);n binormals.crossVectors(tangents, normals); // compute the slowly-varying normal and binormal vectors for each segment on the curvenn for (i = 1; i <= segments; i++) {n normals = normals[i - 1].clone();n binormals = binormals[i - 1].clone();n vec.crossVectors(tangents[i - 1], tangents);nn if (vec.length() > Number
.EPSILON) {n vec.normalize();n theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents), -1, 1)); // clamp for floating pt errorsnn normals.applyMatrix4(mat.makeRotationAxis(vec, theta));n }nn binormals.crossVectors(tangents, normals);n } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the samennn if (closed === true) {n theta = Math.acos(_Math.clamp(normals.dot(normals), -1, 1));n theta /= segments;nn if (tangents.dot(vec.crossVectors(normals, normals)) > 0) {n theta = -theta;n }nn for (i = 1; i <= segments; i++) {n // twist a little…n normals.applyMatrix4(mat.makeRotationAxis(tangents, theta * i));n binormals.crossVectors(tangents, normals);n }n }nn return {n tangents: tangents,n normals: normals,n binormals: binormalsn };n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(source) {n this.arcLengthDivisions = source.arcLengthDivisions;n return this;n },n toJSON: function toJSON() {n var data = {n metadata: {n version: 4.5,n type: 'Curve',n generator: 'Curve.toJSON'n }n };n data.arcLengthDivisions = this.arcLengthDivisions;n data.type = this.type;n return data;n },n fromJSON: function fromJSON(json) {n this.arcLengthDivisions = json.arcLengthDivisions;n return this;n }n});nnfunction EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {n Curve.call(this);n this.type = 'EllipseCurve';n this.aX = aX || 0;n this.aY = aY || 0;n this.xRadius = xRadius || 1;n this.yRadius = yRadius || 1;n this.aStartAngle = aStartAngle || 0;n this.aEndAngle = aEndAngle || 2 * Math.PI;n this.aClockwise = aClockwise || false;n this.aRotation = aRotation || 0;n}nnEllipseCurve.prototype = Object.create(Curve.prototype);nEllipseCurve.prototype.constructor = EllipseCurve;nEllipseCurve.prototype.isEllipseCurve = true;nnEllipseCurve.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector2();n var twoPi = Math.PI * 2;n var deltaAngle = this.aEndAngle - this.aStartAngle;n var samePoints = Math.abs(deltaAngle) < Number
.EPSILON; // ensures that deltaAngle is 0 .. 2 PInn while (deltaAngle < 0) {n deltaAngle += twoPi;n }nn while (deltaAngle > twoPi) {n deltaAngle -= twoPi;n }nn if (deltaAngle < Number
.EPSILON) {n if (samePoints) {n deltaAngle = 0;n } else {n deltaAngle = twoPi;n }n }nn if (this.aClockwise === true && !samePoints) {n if (deltaAngle === twoPi) {n deltaAngle = -twoPi;n } else {n deltaAngle = deltaAngle - twoPi;n }n }nn var angle = this.aStartAngle + t * deltaAngle;n var x = this.aX + this.xRadius * Math.cos(angle);n var y = this.aY + this.yRadius * Math.sin(angle);nn if (this.aRotation !== 0) {n var cos = Math.cos(this.aRotation);n var sin = Math.sin(this.aRotation);n var tx = x - this.aX;n var ty = y - this.aY; // Rotate the point about the center of the ellipse.nn x = tx * cos - ty * sin + this.aX;n y = tx * sin + ty * cos + this.aY;n }nn return point.set(x, y);n};nnEllipseCurve.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.aX = source.aX;n this.aY = source.aY;n this.xRadius = source.xRadius;n this.yRadius = source.yRadius;n this.aStartAngle = source.aStartAngle;n this.aEndAngle = source.aEndAngle;n this.aClockwise = source.aClockwise;n this.aRotation = source.aRotation;n return this;n};nnEllipseCurve.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.aX = this.aX;n data.aY = this.aY;n data.xRadius = this.xRadius;n data.yRadius = this.yRadius;n data.aStartAngle = this.aStartAngle;n data.aEndAngle = this.aEndAngle;n data.aClockwise = this.aClockwise;n data.aRotation = this.aRotation;n return data;n};nnEllipseCurve.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.aX = json.aX;n this.aY = json.aY;n this.xRadius = json.xRadius;n this.yRadius = json.yRadius;n this.aStartAngle = json.aStartAngle;n this.aEndAngle = json.aEndAngle;n this.aClockwise = json.aClockwise;n this.aRotation = json.aRotation;n return this;n};nnfunction ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {n EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);n this.type = 'ArcCurve';n}nnArcCurve.prototype = Object.create(EllipseCurve.prototype);nArcCurve.prototype.constructor = ArcCurve;nArcCurve.prototype.isArcCurve = true;n/**n * @author zz85 github.com/zz85n *n * Centripetal CatmullRom Curve - which is useful for avoidingn * cusps and self-intersections in non-uniform catmull rom curves.n * www.cemyuksel.com/research/catmullrom_param/catmullrom.pdfn *n * curve.type accepts centripetal(default), chordal and catmullromn * curve.tension is used for catmullrom which defaults to 0.5n */nn/*nBased on an optimized c++ solution inn - stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/n - ideone.com/NoEbVMnnThis CubicPoly class could be used for reusing some variables and calculations,nbut for three.js curve use, it could be possible inlined and flatten into a single function callnwhich can be placed in CurveUtils.n*/nnfunction CubicPoly() {n var c0 = 0,n c1 = 0,n c2 = 0,n c3 = 0;n /*n * Compute coefficients for a cubic polynomialn * p(s) = c0 + c1*s + c2*s^2 + c3*s^3n * such thatn * p(0) = x0, p(1) = x1n * andn * p'(0) = t0, p'(1) = t1.n */nn function init(x0, x1, t0, t1) {n c0 = x0;n c1 = t0;n c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;n c3 = 2 * x0 - 2 * x1 + t0 + t1;n }nn return {n initCatmullRom: function initCatmullRom(x0, x1, x2, x3, tension) {n init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));n },n initNonuniformCatmullRom: function initNonuniformCatmullRom(x0, x1, x2, x3, dt0, dt1, dt2) {n // compute tangents when parameterized in [t1,t2]n var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;n var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]nn t1 *= dt1;n t2 *= dt1;n init(x1, x2, t1, t2);n },n calc: function calc(t) {n var t2 = t * t;n var t3 = t2 * t;n return c0 + c1 * t + c2 * t2 + c3 * t3;n }n };n} //nnnvar tmp = new Vector3();nvar px = new CubicPoly(),n py = new CubicPoly(),n pz = new CubicPoly();nnfunction CatmullRomCurve3(points, closed, curveType, tension) {n Curve.call(this);n this.type = 'CatmullRomCurve3';n this.points = points || [];n this.closed = closed || false;n this.curveType = curveType || 'centripetal';n this.tension = tension || 0.5;n}nnCatmullRomCurve3.prototype = Object.create(Curve.prototype);nCatmullRomCurve3.prototype.constructor = CatmullRomCurve3;nCatmullRomCurve3.prototype.isCatmullRomCurve3 = true;nnCatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector3();n var points = this.points;n var l = points.length;n var p = (l - (this.closed ? 0 : 1)) * t;n var intPoint = Math.floor(p);n var weight = p - intPoint;nn if (this.closed) {n intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;n } else if (weight === 0 && intPoint === l - 1) {n intPoint = l - 2;n weight = 1;n }nn var p0, p1, p2, p3; // 4 pointsnn if (this.closed || intPoint > 0) {n p0 = points[(intPoint - 1) % l];n } else {n // extrapolate first pointn tmp.subVectors(points, points).add(points);n p0 = tmp;n }nn p1 = points[intPoint % l];n p2 = points[(intPoint + 1) % l];nn if (this.closed || intPoint + 2 < l) {n p3 = points[(intPoint + 2) % l];n } else {n // extrapolate last pointn tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);n p3 = tmp;n }nn if (this.curveType === 'centripetal' || this.curveType === 'chordal') {n // init Centripetal / Chordal Catmull-Romn var pow = this.curveType === 'chordal' ? 0.5 : 0.25;n var dt0 = Math.pow(p0.distanceToSquared(p1), pow);n var dt1 = Math.pow(p1.distanceToSquared(p2), pow);n var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated pointsnn if (dt1 < 1e-4) dt1 = 1.0;n if (dt0 < 1e-4) dt0 = dt1;n if (dt2 < 1e-4) dt2 = dt1;n px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);n py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);n pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);n } else if (this.curveType === 'catmullrom') {n px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);n py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);n pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);n }nn point.set(px.calc(weight), py.calc(weight), pz.calc(weight));n return point;n};nnCatmullRomCurve3.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.points = [];nn for (var i = 0, l = source.points.length; i < l; i++) {n var point = source.points;n this.points.push(point.clone());n }nn this.closed = source.closed;n this.curveType = source.curveType;n this.tension = source.tension;n return this;n};nnCatmullRomCurve3.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.points = [];nn for (var i = 0, l = this.points.length; i < l; i++) {n var point = this.points;n data.points.push(point.toArray());n }nn data.closed = this.closed;n data.curveType = this.curveType;n data.tension = this.tension;n return data;n};nnCatmullRomCurve3.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.points = [];nn for (var i = 0, l = json.points.length; i < l; i++) {n var point = json.points;n this.points.push(new Vector3().fromArray(point));n }nn this.closed = json.closed;n this.curveType = json.curveType;n this.tension = json.tension;n return this;n};n/**n * @author zz85 / www.lab4games.net/zz85/blogn *n * Bezier Curves formulas obtained fromn * en.wikipedia.org/wiki/Bézier_curven */nnnfunction CatmullRom(t, p0, p1, p2, p3) {n var v0 = (p2 - p0) * 0.5;n var v1 = (p3 - p1) * 0.5;n var t2 = t * t;n var t3 = t * t2;n return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;n} //nnnfunction QuadraticBezierP0(t, p) {n var k = 1 - t;n return k * k * p;n}nnfunction QuadraticBezierP1(t, p) {n return 2 * (1 - t) * t * p;n}nnfunction QuadraticBezierP2(t, p) {n return t * t * p;n}nnfunction QuadraticBezier(t, p0, p1, p2) {n return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);n} //nnnfunction CubicBezierP0(t, p) {n var k = 1 - t;n return k * k * k * p;n}nnfunction CubicBezierP1(t, p) {n var k = 1 - t;n return 3 * k * k * t * p;n}nnfunction CubicBezierP2(t, p) {n return 3 * (1 - t) * t * t * p;n}nnfunction CubicBezierP3(t, p) {n return t * t * t * p;n}nnfunction CubicBezier(t, p0, p1, p2, p3) {n return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);n}nnfunction CubicBezierCurve(v0, v1, v2, v3) {n Curve.call(this);n this.type = 'CubicBezierCurve';n this.v0 = v0 || new Vector2();n this.v1 = v1 || new Vector2();n this.v2 = v2 || new Vector2();n this.v3 = v3 || new Vector2();n}nnCubicBezierCurve.prototype = Object.create(Curve.prototype);nCubicBezierCurve.prototype.constructor = CubicBezierCurve;nCubicBezierCurve.prototype.isCubicBezierCurve = true;nnCubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector2();n var v0 = this.v0,n v1 = this.v1,n v2 = this.v2,n v3 = this.v3;n point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));n return point;n};nnCubicBezierCurve.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.v0.copy(source.v0);n this.v1.copy(source.v1);n this.v2.copy(source.v2);n this.v3.copy(source.v3);n return this;n};nnCubicBezierCurve.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.v0 = this.v0.toArray();n data.v1 = this.v1.toArray();n data.v2 = this.v2.toArray();n data.v3 = this.v3.toArray();n return data;n};nnCubicBezierCurve.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.v0.fromArray(json.v0);n this.v1.fromArray(json.v1);n this.v2.fromArray(json.v2);n this.v3.fromArray(json.v3);n return this;n};nnfunction CubicBezierCurve3(v0, v1, v2, v3) {n Curve.call(this);n this.type = 'CubicBezierCurve3';n this.v0 = v0 || new Vector3();n this.v1 = v1 || new Vector3();n this.v2 = v2 || new Vector3();n this.v3 = v3 || new Vector3();n}nnCubicBezierCurve3.prototype = Object.create(Curve.prototype);nCubicBezierCurve3.prototype.constructor = CubicBezierCurve3;nCubicBezierCurve3.prototype.isCubicBezierCurve3 = true;nnCubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector3();n var v0 = this.v0,n v1 = this.v1,n v2 = this.v2,n v3 = this.v3;n 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));n return point;n};nnCubicBezierCurve3.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.v0.copy(source.v0);n this.v1.copy(source.v1);n this.v2.copy(source.v2);n this.v3.copy(source.v3);n return this;n};nnCubicBezierCurve3.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.v0 = this.v0.toArray();n data.v1 = this.v1.toArray();n data.v2 = this.v2.toArray();n data.v3 = this.v3.toArray();n return data;n};nnCubicBezierCurve3.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.v0.fromArray(json.v0);n this.v1.fromArray(json.v1);n this.v2.fromArray(json.v2);n this.v3.fromArray(json.v3);n return this;n};nnfunction LineCurve(v1, v2) {n Curve.call(this);n this.type = 'LineCurve';n this.v1 = v1 || new Vector2();n this.v2 = v2 || new Vector2();n}nnLineCurve.prototype = Object.create(Curve.prototype);nLineCurve.prototype.constructor = LineCurve;nLineCurve.prototype.isLineCurve = true;nnLineCurve.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector2();nn if (t === 1) {n point.copy(this.v2);n } else {n point.copy(this.v2).sub(this.v1);n point.multiplyScalar(t).add(this.v1);n }nn return point;n}; // Line curve is linear, so we can overwrite default getPointAtnnnLineCurve.prototype.getPointAt = function (u, optionalTarget) {n return this.getPoint(u, optionalTarget);n};nnLineCurve.prototype.getTangent = function ()n/* t */n{n var tangent = this.v2.clone().sub(this.v1);n return tangent.normalize();n};nnLineCurve.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.v1.copy(source.v1);n this.v2.copy(source.v2);n return this;n};nnLineCurve.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.v1 = this.v1.toArray();n data.v2 = this.v2.toArray();n return data;n};nnLineCurve.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.v1.fromArray(json.v1);n this.v2.fromArray(json.v2);n return this;n};nnfunction LineCurve3(v1, v2) {n Curve.call(this);n this.type = 'LineCurve3';n this.v1 = v1 || new Vector3();n this.v2 = v2 || new Vector3();n}nnLineCurve3.prototype = Object.create(Curve.prototype);nLineCurve3.prototype.constructor = LineCurve3;nLineCurve3.prototype.isLineCurve3 = true;nnLineCurve3.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector3();nn if (t === 1) {n point.copy(this.v2);n } else {n point.copy(this.v2).sub(this.v1);n point.multiplyScalar(t).add(this.v1);n }nn return point;n}; // Line curve is linear, so we can overwrite default getPointAtnnnLineCurve3.prototype.getPointAt = function (u, optionalTarget) {n return this.getPoint(u, optionalTarget);n};nnLineCurve3.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.v1.copy(source.v1);n this.v2.copy(source.v2);n return this;n};nnLineCurve3.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.v1 = this.v1.toArray();n data.v2 = this.v2.toArray();n return data;n};nnLineCurve3.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.v1.fromArray(json.v1);n this.v2.fromArray(json.v2);n return this;n};nnfunction QuadraticBezierCurve(v0, v1, v2) {n Curve.call(this);n this.type = 'QuadraticBezierCurve';n this.v0 = v0 || new Vector2();n this.v1 = v1 || new Vector2();n this.v2 = v2 || new Vector2();n}nnQuadraticBezierCurve.prototype = Object.create(Curve.prototype);nQuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;nQuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;nnQuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector2();n var v0 = this.v0,n v1 = this.v1,n v2 = this.v2;n point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));n return point;n};nnQuadraticBezierCurve.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.v0.copy(source.v0);n this.v1.copy(source.v1);n this.v2.copy(source.v2);n return this;n};nnQuadraticBezierCurve.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.v0 = this.v0.toArray();n data.v1 = this.v1.toArray();n data.v2 = this.v2.toArray();n return data;n};nnQuadraticBezierCurve.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.v0.fromArray(json.v0);n this.v1.fromArray(json.v1);n this.v2.fromArray(json.v2);n return this;n};nnfunction QuadraticBezierCurve3(v0, v1, v2) {n Curve.call(this);n this.type = 'QuadraticBezierCurve3';n this.v0 = v0 || new Vector3();n this.v1 = v1 || new Vector3();n this.v2 = v2 || new Vector3();n}nnQuadraticBezierCurve3.prototype = Object.create(Curve.prototype);nQuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;nQuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;nnQuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector3();n var v0 = this.v0,n v1 = this.v1,n v2 = this.v2;n 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));n return point;n};nnQuadraticBezierCurve3.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.v0.copy(source.v0);n this.v1.copy(source.v1);n this.v2.copy(source.v2);n return this;n};nnQuadraticBezierCurve3.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.v0 = this.v0.toArray();n data.v1 = this.v1.toArray();n data.v2 = this.v2.toArray();n return data;n};nnQuadraticBezierCurve3.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.v0.fromArray(json.v0);n this.v1.fromArray(json.v1);n this.v2.fromArray(json.v2);n return this;n};nnfunction SplineCurve(pointsn/* array of Vector2 */n) {n Curve.call(this);n this.type = 'SplineCurve';n this.points = points || [];n}nnSplineCurve.prototype = Object.create(Curve.prototype);nSplineCurve.prototype.constructor = SplineCurve;nSplineCurve.prototype.isSplineCurve = true;nnSplineCurve.prototype.getPoint = function (t, optionalTarget) {n var point = optionalTarget || new Vector2();n var points = this.points;n var p = (points.length - 1) * t;n var intPoint = Math.floor(p);n var weight = p - intPoint;n var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];n var p1 = points;n var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];n var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];n point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));n return point;n};nnSplineCurve.prototype.copy = function (source) {n Curve.prototype.copy.call(this, source);n this.points = [];nn for (var i = 0, l = source.points.length; i < l; i++) {n var point = source.points;n this.points.push(point.clone());n }nn return this;n};nnSplineCurve.prototype.toJSON = function () {n var data = Curve.prototype.toJSON.call(this);n data.points = [];nn for (var i = 0, l = this.points.length; i < l; i++) {n var point = this.points;n data.points.push(point.toArray());n }nn return data;n};nnSplineCurve.prototype.fromJSON = function (json) {n Curve.prototype.fromJSON.call(this, json);n this.points = [];nn for (var i = 0, l = json.points.length; i < l; i++) {n var point = json.points;n this.points.push(new Vector2().fromArray(point));n }nn return this;n};nnvar Curves =n/*#__PURE__*/nObject.freeze({n ArcCurve: ArcCurve,n CatmullRomCurve3: CatmullRomCurve3,n CubicBezierCurve: CubicBezierCurve,n CubicBezierCurve3: CubicBezierCurve3,n EllipseCurve: EllipseCurve,n LineCurve: LineCurve,n LineCurve3: LineCurve3,n QuadraticBezierCurve: QuadraticBezierCurve,n QuadraticBezierCurve3: QuadraticBezierCurve3,n SplineCurve: SplineCurven});n/**n * @author zz85 / www.lab4games.net/zz85/blogn *n **/nn/**************************************************************n *tCurved Path - a curve path is simply a array of connectedn * curves, but retains the api of a curven **************************************************************/nnfunction CurvePath() {n Curve.call(this);n this.type = 'CurvePath';n this.curves = [];n this.autoClose = false; // Automatically closes the pathn}nnCurvePath.prototype = Object.assign(Object.create(Curve.prototype), {n constructor: CurvePath,n add: function add(curve) {n this.curves.push(curve);n },n closePath: function closePath() {n // Add a line curve if start and end of lines are not connectedn var startPoint = this.curves.getPoint(0);n var endPoint = this.curves[this.curves.length - 1].getPoint(1);nn if (!startPoint.equals(endPoint)) {n this.curves.push(new LineCurve(endPoint, startPoint));n }n },n // To get accurate point with reference ton // entire path distance at time t,n // following has to be done:n // 1. Length of each sub path have to be knownn // 2. Locate and identify type of curven // 3. Get t for the curven // 4. Return curve.getPointAt(t')n getPoint: function getPoint(t) {n var d = t * this.getLength();n var curveLengths = this.getCurveLengths();n var i = 0; // To think about boundaries points.nn while (i < curveLengths.length) {n if (curveLengths >= d) {n var diff = curveLengths - d;n var curve = this.curves;n var segmentLength = curve.getLength();n var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;n return curve.getPointAt(u);n }nn i++;n }nn return null; // loop where sum != 0, sum > d , sum+1 <dn },n // We cannot use the default THREE.Curve getPoint() with getLength() because inn // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePathn // getPoint() depends on getLengthn getLength: function getLength() {n var lens = this.getCurveLengths();n return lens[lens.length - 1];n },n // cacheLengths must be recalculated.n updateArcLengths: function updateArcLengths() {n this.needsUpdate = true;n this.cacheLengths = null;n this.getCurveLengths();n },n // Compute lengths and cache themn // We cannot overwrite getLengths() because UtoT mapping uses it.n getCurveLengths: function getCurveLengths() {n // We use cache values if curves and cache array are same lengthn if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {n return this.cacheLengths;n } // Get length of sub-curven // Push sums into cached arraynnn var lengths = [],n sums = 0;nn for (var i = 0, l = this.curves.length; i < l; i++) {n sums += this.curves.getLength();n lengths.push(sums);n }nn this.cacheLengths = lengths;n return lengths;n },n getSpacedPoints: function getSpacedPoints(divisions) {n if (divisions === undefined) divisions = 40;n var points = [];nn for (var i = 0; i <= divisions; i++) {n points.push(this.getPoint(i / divisions));n }nn if (this.autoClose) {n points.push(points);n }nn return points;n },n getPoints: function getPoints(divisions) {n divisions = divisions || 12;n var points = [],n last;nn for (var i = 0, curves = this.curves; i < curves.length; i++) {n var curve = curves;n var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;n var pts = curve.getPoints(resolution);nn for (var j = 0; j < pts.length; j++) {n var point = pts;n if (last && last.equals(point)) continue; // ensures no consecutive points are duplicatesnn points.push(point);n last = point;n }n }nn if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points)) {n points.push(points);n }nn return points;n },n copy: function copy(source) {n Curve.prototype.copy.call(this, source);n this.curves = [];nn for (var i = 0, l = source.curves.length; i < l; i++) {n var curve = source.curves;n this.curves.push(curve.clone());n }nn this.autoClose = source.autoClose;n return this;n },n toJSON: function toJSON() {n var data = Curve.prototype.toJSON.call(this);n data.autoClose = this.autoClose;n data.curves = [];nn for (var i = 0, l = this.curves.length; i < l; i++) {n var curve = this.curves;n data.curves.push(curve.toJSON());n }nn return data;n },n fromJSON: function fromJSON(json) {n Curve.prototype.fromJSON.call(this, json);n this.autoClose = json.autoClose;n this.curves = [];nn for (var i = 0, l = json.curves.length; i < l; i++) {n var curve = json.curves;n this.curves.push(new Curves().fromJSON(curve));n }nn return this;n }n});n/**n * @author zz85 / www.lab4games.net/zz85/blogn * Creates free form 2d path using series of points, lines or curves.n **/nnfunction Path(points) {n CurvePath.call(this);n this.type = 'Path';n this.currentPoint = new Vector2();nn if (points) {n this.setFromPoints(points);n }n}nnPath.prototype = Object.assign(Object.create(CurvePath.prototype), {n constructor: Path,n setFromPoints: function setFromPoints(points) {n this.moveTo(points.x, points.y);nn for (var i = 1, l = points.length; i < l; i++) {n this.lineTo(points.x, points.y);n }n },n moveTo: function moveTo(x, y) {n this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?n },n lineTo: function lineTo(x, y) {n var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));n this.curves.push(curve);n this.currentPoint.set(x, y);n },n quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {n var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));n this.curves.push(curve);n this.currentPoint.set(aX, aY);n },n bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {n var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));n this.curves.push(curve);n this.currentPoint.set(aX, aY);n },n splineThru: function splineThru(ptsn /*Array of Vector*/n ) {n var npts = [this.currentPoint.clone()].concat(pts);n var curve = new SplineCurve(npts);n this.curves.push(curve);n this.currentPoint.copy(pts[pts.length - 1]);n },n arc: function arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {n var x0 = this.currentPoint.x;n var y0 = this.currentPoint.y;n this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);n },n absarc: function absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {n this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);n },n ellipse: function ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {n var x0 = this.currentPoint.x;n var y0 = this.currentPoint.y;n this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);n },n absellipse: function absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {n var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);nn if (this.curves.length > 0) {n // if a previous curve is present, attempt to joinn var firstPoint = curve.getPoint(0);nn if (!firstPoint.equals(this.currentPoint)) {n this.lineTo(firstPoint.x, firstPoint.y);n }n }nn this.curves.push(curve);n var lastPoint = curve.getPoint(1);n this.currentPoint.copy(lastPoint);n },n copy: function copy(source) {n CurvePath.prototype.copy.call(this, source);n this.currentPoint.copy(source.currentPoint);n return this;n },n toJSON: function toJSON() {n var data = CurvePath.prototype.toJSON.call(this);n data.currentPoint = this.currentPoint.toArray();n return data;n },n fromJSON: function fromJSON(json) {n CurvePath.prototype.fromJSON.call(this, json);n this.currentPoint.fromArray(json.currentPoint);n return this;n }n});n/**n * @author zz85 / www.lab4games.net/zz85/blogn * Defines a 2d shape plane using paths.n **/n// STEP 1 Create a path.n// STEP 2 Turn path into shape.n// STEP 3 ExtrudeGeometry takes in Shape/Shapesn// STEP 3a - Extract points from each shape, turn to verticesn// STEP 3b - Triangulate each shape, add faces.nnfunction Shape(points) {n Path.call(this, points);n this.uuid = _Math.generateUUID();n this.type = 'Shape';n this.holes = [];n}nnShape.prototype = Object.assign(Object.create(Path.prototype), {n constructor: Shape,n getPointsHoles: function getPointsHoles(divisions) {n var holesPts = [];nn for (var i = 0, l = this.holes.length; i < l; i++) {n holesPts = this.holes.getPoints(divisions);n }nn return holesPts;n },n // get points of shape and holes (keypoints based on segments parameter)n extractPoints: function extractPoints(divisions) {n return {n shape: this.getPoints(divisions),n holes: this.getPointsHoles(divisions)n };n },n copy: function copy(source) {n Path.prototype.copy.call(this, source);n this.holes = [];nn for (var i = 0, l = source.holes.length; i < l; i++) {n var hole = source.holes;n this.holes.push(hole.clone());n }nn return this;n },n toJSON: function toJSON() {n var data = Path.prototype.toJSON.call(this);n data.uuid = this.uuid;n data.holes = [];nn for (var i = 0, l = this.holes.length; i < l; i++) {n var hole = this.holes;n data.holes.push(hole.toJSON());n }nn return data;n },n fromJSON: function fromJSON(json) {n Path.prototype.fromJSON.call(this, json);n this.uuid = json.uuid;n this.holes = [];nn for (var i = 0, l = json.holes.length; i < l; i++) {n var hole = json.holes;n this.holes.push(new Path().fromJSON(hole));n }nn return this;n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n */nnfunction Light(color, intensity) {n Object3D.call(this);n this.type = 'Light';n this.color = new Color(color);n this.intensity = intensity !== undefined ? intensity : 1;n this.receiveShadow = undefined;n}nnLight.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Light,n isLight: true,n copy: function copy(source) {n Object3D.prototype.copy.call(this, source);n this.color.copy(source.color);n this.intensity = source.intensity;n return this;n },n toJSON: function toJSON(meta) {n var data = Object3D.prototype.toJSON.call(this, meta);n data.object.color = this.color.getHex();n data.object.intensity = this.intensity;n if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();n if (this.distance !== undefined) data.object.distance = this.distance;n if (this.angle !== undefined) data.object.angle = this.angle;n if (this.decay !== undefined) data.object.decay = this.decay;n if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;n if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();n return data;n }n});n/**n * @author alteredq / alteredqualia.com/n */nnfunction HemisphereLight(skyColor, groundColor, intensity) {n Light.call(this, skyColor, intensity);n this.type = 'HemisphereLight';n this.castShadow = undefined;n this.position.copy(Object3D.DefaultUp);n this.updateMatrix();n this.groundColor = new Color(groundColor);n}nnHemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {n constructor: HemisphereLight,n isHemisphereLight: true,n copy: function copy(source) {n Light.prototype.copy.call(this, source);n this.groundColor.copy(source.groundColor);n return this;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction LightShadow(camera) {n this.camera = camera;n this.bias = 0;n this.radius = 1;n this.mapSize = new Vector2(512, 512);n this.map = null;n this.mapPass = null;n this.matrix = new Matrix4();n this._frustum = new Frustum();n this._frameExtents = new Vector2(1, 1);n this._viewportCount = 1;n this._viewports = [new Vector4(0, 0, 1, 1)];n}nnObject.assign(LightShadow.prototype, {n _projScreenMatrix: new Matrix4(),n _lightPositionWorld: new Vector3(),n _lookTarget: new Vector3(),n getViewportCount: function getViewportCount() {n return this._viewportCount;n },n getFrustum: function getFrustum() {n return this._frustum;n },n updateMatrices: function updateMatrices(light) {n var shadowCamera = this.camera,n shadowMatrix = this.matrix,n projScreenMatrix = this._projScreenMatrix,n lookTarget = this._lookTarget,n lightPositionWorld = this._lightPositionWorld;n lightPositionWorld.setFromMatrixPosition(light.matrixWorld);n shadowCamera.position.copy(lightPositionWorld);n lookTarget.setFromMatrixPosition(light.target.matrixWorld);n shadowCamera.lookAt(lookTarget);n shadowCamera.updateMatrixWorld();n projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);nn this._frustum.setFromMatrix(projScreenMatrix);nn 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);n shadowMatrix.multiply(shadowCamera.projectionMatrix);n shadowMatrix.multiply(shadowCamera.matrixWorldInverse);n },n getViewport: function getViewport(viewportIndex) {n return this._viewports;n },n getFrameExtents: function getFrameExtents() {n return this._frameExtents;n },n copy: function copy(source) {n this.camera = source.camera.clone();n this.bias = source.bias;n this.radius = source.radius;n this.mapSize.copy(source.mapSize);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n toJSON: function toJSON() {n var object = {};n if (this.bias !== 0) object.bias = this.bias;n if (this.radius !== 1) object.radius = this.radius;n if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();n object.camera = this.camera.toJSON(false).object;n delete object.camera.matrix;n return object;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction SpotLightShadow() {n LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));n}nnSpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {n constructor: SpotLightShadow,n isSpotLightShadow: true,n updateMatrices: function updateMatrices(light, viewCamera, viewportIndex) {n var camera = this.camera;n var fov = _Math.RAD2DEG * 2 * light.angle;n var aspect = this.mapSize.width / this.mapSize.height;n var far = light.distance || camera.far;nn if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {n camera.fov = fov;n camera.aspect = aspect;n camera.far = far;n camera.updateProjectionMatrix();n }nn LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);n }n});n/**n * @author alteredq / alteredqualia.com/n */nnfunction SpotLight(color, intensity, distance, angle, penumbra, decay) {n Light.call(this, color, intensity);n this.type = 'SpotLight';n this.position.copy(Object3D.DefaultUp);n this.updateMatrix();n this.target = new Object3D();n Object.defineProperty(this, 'power', {n get: function get() {n // intensity = power per solid angle.n // ref: equation (17) from seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdfn return this.intensity * Math.PI;n },n set: function set(power) {n // intensity = power per solid angle.n // ref: equation (17) from seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdfn this.intensity = power / Math.PI;n }n });n this.distance = distance !== undefined ? distance : 0;n this.angle = angle !== undefined ? angle : Math.PI / 3;n this.penumbra = penumbra !== undefined ? penumbra : 0;n this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.nn this.shadow = new SpotLightShadow();n}nnSpotLight.prototype = Object.assign(Object.create(Light.prototype), {n constructor: SpotLight,n isSpotLight: true,n copy: function copy(source) {n Light.prototype.copy.call(this, source);n this.distance = source.distance;n this.angle = source.angle;n this.penumbra = source.penumbra;n this.decay = source.decay;n this.target = source.target.clone();n this.shadow = source.shadow.clone();n return this;n }n});nnfunction PointLightShadow() {n LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));n this._frameExtents = new Vector2(4, 2);n this._viewportCount = 6;n this._viewports = [// These viewports map a cube-map onto a 2D texture with then // following orientation:n //n // xzXZn // y Yn //n // X - Positive x directionn // x - Negative x directionn // Y - Positive y directionn // y - Negative y directionn // Z - Positive z directionn // z - Negative z directionn // positive Xn new Vector4(2, 1, 1, 1), // negative Xn new Vector4(0, 1, 1, 1), // positive Zn new Vector4(3, 1, 1, 1), // negative Zn new Vector4(1, 1, 1, 1), // positive Yn new Vector4(3, 0, 1, 1), // negative Yn new Vector4(1, 0, 1, 1)];n 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)];n 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)];n}nnPointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {n constructor: PointLightShadow,n isPointLightShadow: true,n updateMatrices: function updateMatrices(light, viewCamera, viewportIndex) {n var camera = this.camera,n shadowMatrix = this.matrix,n lightPositionWorld = this._lightPositionWorld,n lookTarget = this._lookTarget,n projScreenMatrix = this._projScreenMatrix;n lightPositionWorld.setFromMatrixPosition(light.matrixWorld);n camera.position.copy(lightPositionWorld);n lookTarget.copy(camera.position);n lookTarget.add(this._cubeDirections);n camera.up.copy(this._cubeUps);n camera.lookAt(lookTarget);n camera.updateMatrixWorld();n shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);n projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);nn this._frustum.setFromMatrix(projScreenMatrix);n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction PointLight(color, intensity, distance, decay) {n Light.call(this, color, intensity);n this.type = 'PointLight';n Object.defineProperty(this, 'power', {n get: function get() {n // intensity = power per solid angle.n // ref: equation (15) from seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdfn return this.intensity * 4 * Math.PI;n },n set: function set(power) {n // intensity = power per solid angle.n // ref: equation (15) from seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdfn this.intensity = power / (4 * Math.PI);n }n });n this.distance = distance !== undefined ? distance : 0;n this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.nn this.shadow = new PointLightShadow();n}nnPointLight.prototype = Object.assign(Object.create(Light.prototype), {n constructor: PointLight,n isPointLight: true,n copy: function copy(source) {n Light.prototype.copy.call(this, source);n this.distance = source.distance;n this.decay = source.decay;n this.shadow = source.shadow.clone();n return this;n }n});n/**n * @author alteredq / alteredqualia.com/n * @author arose / github.com/arosen */nnfunction OrthographicCamera(left, right, top, bottom, near, far) {n Camera.call(this);n this.type = 'OrthographicCamera';n this.zoom = 1;n this.view = null;n this.left = left !== undefined ? left : -1;n this.right = right !== undefined ? right : 1;n this.top = top !== undefined ? top : 1;n this.bottom = bottom !== undefined ? bottom : -1;n this.near = near !== undefined ? near : 0.1;n this.far = far !== undefined ? far : 2000;n this.updateProjectionMatrix();n}nnOrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {n constructor: OrthographicCamera,n isOrthographicCamera: true,n copy: function copy(source, recursive) {n Camera.prototype.copy.call(this, source, recursive);n this.left = source.left;n this.right = source.right;n this.top = source.top;n this.bottom = source.bottom;n this.near = source.near;n this.far = source.far;n this.zoom = source.zoom;n this.view = source.view === null ? null : Object.assign({}, source.view);n return this;n },n setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {n if (this.view === null) {n this.view = {n enabled: true,n fullWidth: 1,n fullHeight: 1,n offsetX: 0,n offsetY: 0,n width: 1,n height: 1n };n }nn this.view.enabled = true;n this.view.fullWidth = fullWidth;n this.view.fullHeight = fullHeight;n this.view.offsetX = x;n this.view.offsetY = y;n this.view.width = width;n this.view.height = height;n this.updateProjectionMatrix();n },n clearViewOffset: function clearViewOffset() {n if (this.view !== null) {n this.view.enabled = false;n }nn this.updateProjectionMatrix();n },n updateProjectionMatrix: function updateProjectionMatrix() {n var dx = (this.right - this.left) / (2 * this.zoom);n var dy = (this.top - this.bottom) / (2 * this.zoom);n var cx = (this.right + this.left) / 2;n var cy = (this.top + this.bottom) / 2;n var left = cx - dx;n var right = cx + dx;n var top = cy + dy;n var bottom = cy - dy;nn if (this.view !== null && this.view.enabled) {n var zoomW = this.zoom / (this.view.width / this.view.fullWidth);n var zoomH = this.zoom / (this.view.height / this.view.fullHeight);n var scaleW = (this.right - this.left) / this.view.width;n var scaleH = (this.top - this.bottom) / this.view.height;n left += scaleW * (this.view.offsetX / zoomW);n right = left + scaleW * (this.view.width / zoomW);n top -= scaleH * (this.view.offsetY / zoomH);n bottom = top - scaleH * (this.view.height / zoomH);n }nn this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);n this.projectionMatrixInverse.getInverse(this.projectionMatrix);n },n toJSON: function toJSON(meta) {n var data = Object3D.prototype.toJSON.call(this, meta);n data.object.zoom = this.zoom;n data.object.left = this.left;n data.object.right = this.right;n data.object.top = this.top;n data.object.bottom = this.bottom;n data.object.near = this.near;n data.object.far = this.far;n if (this.view !== null) data.object.view = Object.assign({}, this.view);n return data;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction DirectionalLightShadow() {n LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));n}nnDirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {n constructor: DirectionalLightShadow,n isDirectionalLightShadow: true,n updateMatrices: function updateMatrices(light, viewCamera, viewportIndex) {n LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);n }n});n/**n * @author mrdoob / mrdoob.com/n * @author alteredq / alteredqualia.com/n */nnfunction DirectionalLight(color, intensity) {n Light.call(this, color, intensity);n this.type = 'DirectionalLight';n this.position.copy(Object3D.DefaultUp);n this.updateMatrix();n this.target = new Object3D();n this.shadow = new DirectionalLightShadow();n}nnDirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {n constructor: DirectionalLight,n isDirectionalLight: true,n copy: function copy(source) {n Light.prototype.copy.call(this, source);n this.target = source.target.clone();n this.shadow = source.shadow.clone();n return this;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction AmbientLight(color, intensity) {n Light.call(this, color, intensity);n this.type = 'AmbientLight';n this.castShadow = undefined;n}nnAmbientLight.prototype = Object.assign(Object.create(Light.prototype), {n constructor: AmbientLight,n isAmbientLight: truen});n/**n * @author abelnation / github.com/abelnationn */nnfunction RectAreaLight(color, intensity, width, height) {n Light.call(this, color, intensity);n this.type = 'RectAreaLight';n this.width = width !== undefined ? width : 10;n this.height = height !== undefined ? height : 10;n}nnRectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {n constructor: RectAreaLight,n isRectAreaLight: true,n copy: function copy(source) {n Light.prototype.copy.call(this, source);n this.width = source.width;n this.height = source.height;n return this;n },n toJSON: function toJSON(meta) {n var data = Light.prototype.toJSON.call(this, meta);n data.object.width = this.width;n data.object.height = this.height;n return data;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction MaterialLoader(manager) {n Loader.call(this, manager);n this.textures = {};n}nnMaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: MaterialLoader,n load: function load(url, onLoad, onProgress, onError) {n var scope = this;n var loader = new FileLoader(scope.manager);n loader.setPath(scope.path);n loader.load(url, function (text) {n onLoad(scope.parse(JSON.parse(text)));n }, onProgress, onError);n },n parse: function parse(json) {n var textures = this.textures;nn function getTexture(name) {n if (textures === undefined) {n console.warn('THREE.MaterialLoader: Undefined texture', name);n }nn return textures;n }nn var material = new Materials();n if (json.uuid !== undefined) material.uuid = json.uuid;n if (json.name !== undefined) material.name = json.name;n if (json.color !== undefined) material.color.setHex(json.color);n if (json.roughness !== undefined) material.roughness = json.roughness;n if (json.metalness !== undefined) material.metalness = json.metalness;n if (json.emissive !== undefined) material.emissive.setHex(json.emissive);n if (json.specular !== undefined) material.specular.setHex(json.specular);n if (json.shininess !== undefined) material.shininess = json.shininess;n if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;n if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;n if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;n if (json.fog !== undefined) material.fog = json.fog;n if (json.flatShading !== undefined) material.flatShading = json.flatShading;n if (json.blending !== undefined) material.blending = json.blending;n if (json.combine !== undefined) material.combine = json.combine;n if (json.side !== undefined) material.side = json.side;n if (json.opacity !== undefined) material.opacity = json.opacity;n if (json.transparent !== undefined) material.transparent = json.transparent;n if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;n if (json.depthTest !== undefined) material.depthTest = json.depthTest;n if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;n if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;n if (json.wireframe !== undefined) material.wireframe = json.wireframe;n if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;n if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;n if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;n if (json.rotation !== undefined) material.rotation = json.rotation;n if (json.linewidth !== 1) material.linewidth = json.linewidth;n if (json.dashSize !== undefined) material.dashSize = json.dashSize;n if (json.gapSize !== undefined) material.gapSize = json.gapSize;n if (json.scale !== undefined) material.scale = json.scale;n if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;n if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;n if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;n if (json.skinning !== undefined) material.skinning = json.skinning;n if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;n if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;n if (json.dithering !== undefined) material.dithering = json.dithering;n if (json.visible !== undefined) material.visible = json.visible;n if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;n if (json.userData !== undefined) material.userData = json.userData; // Shader Materialnn if (json.uniforms !== undefined) {n for (var name in json.uniforms) {n var uniform = json.uniforms;n material.uniforms = {};nn switch (uniform.type) {n case 't':n material.uniforms.value = getTexture(uniform.value);n break;nn case 'c':n material.uniforms.value = new Color().setHex(uniform.value);n break;nn case 'v2':n material.uniforms.value = new Vector2().fromArray(uniform.value);n break;nn case 'v3':n material.uniforms.value = new Vector3().fromArray(uniform.value);n break;nn case 'v4':n material.uniforms.value = new Vector4().fromArray(uniform.value);n break;nn case 'm3':n material.uniforms.value = new Matrix3().fromArray(uniform.value);nn case 'm4':n material.uniforms.value = new Matrix4().fromArray(uniform.value);n break;nn default:n material.uniforms.value = uniform.value;n }n }n }nn if (json.defines !== undefined) material.defines = json.defines;n if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;n if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;nn if (json.extensions !== undefined) {n for (var key in json.extensions) {n material.extensions = json.extensions;n }n } // Deprecatednnn if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShadingn // for PointsMaterialnn if (json.size !== undefined) material.size = json.size;n if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // mapsnn if (json.map !== undefined) material.map = getTexture(json.map);n if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);nn if (json.alphaMap !== undefined) {n material.alphaMap = getTexture(json.alphaMap);n material.transparent = true;n }nn if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);n if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;n if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);n if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;nn if (json.normalScale !== undefined) {n var normalScale = json.normalScale;nn if (Array.isArray(normalScale) === false) {n // Blender exporter used to export a scalar. See #7459n normalScale = [normalScale, normalScale];n }nn material.normalScale = new Vector2().fromArray(normalScale);n }nn if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);n if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;n if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;n if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);n if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);n if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);n if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;n if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);n if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);n if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;n if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;n if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;n if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);n if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;n if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);n if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;n if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);n if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);n if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);n return material;n },n setTextures: function setTextures(value) {n this.textures = value;n return this;n }n});n/**n * @author Don McCurdy / www.donmccurdy.comn */nnvar LoaderUtils = {n decodeText: function decodeText(array) {n if (typeof TextDecoder !== 'undefined') {n return new TextDecoder().decode(array);n } // Avoid the String.fromCharCode.apply(null, array) shortcut, whichn // throws a "maximum call stack size exceeded" error for large arrays.nnn var s = '';nn for (var i = 0, il = array.length; i < il; i++) {n // Implicitly assumes little-endian.n s += String.fromCharCode(array);n }nn try {n // merges multi-byte utf-8 characters.n return decodeURIComponent(escape(s));n } catch (e) {n // see #16358n return s;n }n },n extractUrlBase: function extractUrlBase(url) {n var index = url.lastIndexOf('/');n if (index === -1) return './';n return url.substr(0, index + 1);n }n};n/**n * @author benaadams / twitter.com/ben_a_adamsn */nnfunction InstancedBufferGeometry() {n BufferGeometry.call(this);n this.type = 'InstancedBufferGeometry';n this.maxInstancedCount = undefined;n}nnInstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {n constructor: InstancedBufferGeometry,n isInstancedBufferGeometry: true,n copy: function copy(source) {n BufferGeometry.prototype.copy.call(this, source);n this.maxInstancedCount = source.maxInstancedCount;n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n toJSON: function toJSON() {n var data = BufferGeometry.prototype.toJSON.call(this);n data.maxInstancedCount = this.maxInstancedCount;n data.isInstancedBufferGeometry = true;n return data;n }n});n/**n * @author benaadams / twitter.com/ben_a_adamsn */nnfunction InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {n if (typeof normalized === 'number') {n meshPerAttribute = normalized;n normalized = false;n console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');n }nn BufferAttribute.call(this, array, itemSize, normalized);n this.meshPerAttribute = meshPerAttribute || 1;n}nnInstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {n constructor: InstancedBufferAttribute,n isInstancedBufferAttribute: true,n copy: function copy(source) {n BufferAttribute.prototype.copy.call(this, source);n this.meshPerAttribute = source.meshPerAttribute;n return this;n },n toJSON: function toJSON() {n var data = BufferAttribute.prototype.toJSON.call(this);n data.meshPerAttribute = this.meshPerAttribute;n data.isInstancedBufferAttribute = true;n return data;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction BufferGeometryLoader(manager) {n Loader.call(this, manager);n}nnBufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: BufferGeometryLoader,n load: function load(url, onLoad, onProgress, onError) {n var scope = this;n var loader = new FileLoader(scope.manager);n loader.setPath(scope.path);n loader.load(url, function (text) {n onLoad(scope.parse(JSON.parse(text)));n }, onProgress, onError);n },n parse: function parse(json) {n var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();n var index = json.data.index;nn if (index !== undefined) {n var typedArray = new TYPED_ARRAYS(index.array);n geometry.setIndex(new BufferAttribute(typedArray, 1));n }nn var attributes = json.data.attributes;nn for (var key in attributes) {n var attribute = attributes;n var typedArray = new TYPED_ARRAYS(attribute.array);n var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;n var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);n if (attribute.name !== undefined) bufferAttribute.name = attribute.name;n geometry.addAttribute(key, bufferAttribute);n }nn var morphAttributes = json.data.morphAttributes;nn if (morphAttributes) {n for (var key in morphAttributes) {n var attributeArray = morphAttributes;n var array = [];nn for (var i = 0, il = attributeArray.length; i < il; i++) {n var attribute = attributeArray;n var typedArray = new TYPED_ARRAYS(attribute.array);n var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);n if (attribute.name !== undefined) bufferAttribute.name = attribute.name;n array.push(bufferAttribute);n }nn geometry.morphAttributes = array;n }n }nn var groups = json.data.groups || json.data.drawcalls || json.data.offsets;nn if (groups !== undefined) {n for (var i = 0, n = groups.length; i !== n; ++i) {n var group = groups;n geometry.addGroup(group.start, group.count, group.materialIndex);n }n }nn var boundingSphere = json.data.boundingSphere;nn if (boundingSphere !== undefined) {n var center = new Vector3();nn if (boundingSphere.center !== undefined) {n center.fromArray(boundingSphere.center);n }nn geometry.boundingSphere = new Sphere(center, boundingSphere.radius);n }nn if (json.name) geometry.name = json.name;n if (json.userData) geometry.userData = json.userData;n return geometry;n }n});nvar TYPED_ARRAYS = {n Int8Array: Int8Array,n Uint8Array: Uint8Array,n // Workaround for IE11 pre KB2929437. See #11440n Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,n Int16Array: Int16Array,n Uint16Array: Uint16Array,n Int32Array: Int32Array,n Uint32Array: Uint32Array,n Float32Array: Float32Array,n Float64Array: Float64Arrayn};n/**n * @author mrdoob / mrdoob.com/n */nnfunction ObjectLoader(manager) {n Loader.call(this, manager);n}nnObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: ObjectLoader,n load: function load(url, onLoad, onProgress, onError) {n var scope = this;n var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;n this.resourcePath = this.resourcePath || path;n var loader = new FileLoader(scope.manager);n loader.setPath(this.path);n loader.load(url, function (text) {n var json = null;nn try {n json = JSON.parse(text);n } catch (error) {n if (onError !== undefined) onError(error);n console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);n return;n }nn var metadata = json.metadata;nn if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {n console.error('THREE.ObjectLoader: Can\'t load ' + url);n return;n }nn scope.parse(json, onLoad);n }, onProgress, onError);n },n parse: function parse(json, onLoad) {n var shapes = this.parseShape(json.shapes);n var geometries = this.parseGeometries(json.geometries, shapes);n var images = this.parseImages(json.images, function () {n if (onLoad !== undefined) onLoad(object);n });n var textures = this.parseTextures(json.textures, images);n var materials = this.parseMaterials(json.materials, textures);n var object = this.parseObject(json.object, geometries, materials);nn if (json.animations) {n object.animations = this.parseAnimations(json.animations);n }nn if (json.images === undefined || json.images.length === 0) {n if (onLoad !== undefined) onLoad(object);n }nn return object;n },n parseShape: function parseShape(json) {n var shapes = {};nn if (json !== undefined) {n for (var i = 0, l = json.length; i < l; i++) {n var shape = new Shape().fromJSON(json);n shapes = shape;n }n }nn return shapes;n },n parseGeometries: function parseGeometries(json, shapes) {n var geometries = {};nn if (json !== undefined) {n var bufferGeometryLoader = new BufferGeometryLoader();nn for (var i = 0, l = json.length; i < l; i++) {n var geometry;n var data = json;nn switch (data.type) {n case 'PlaneGeometry':n case 'PlaneBufferGeometry':n geometry = new Geometries(data.width, data.height, data.widthSegments, data.heightSegments);n break;nn case 'BoxGeometry':n case 'BoxBufferGeometry':n case 'CubeGeometry':n // backwards compatiblen geometry = new Geometries(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);n break;nn case 'CircleGeometry':n case 'CircleBufferGeometry':n geometry = new Geometries(data.radius, data.segments, data.thetaStart, data.thetaLength);n break;nn case 'CylinderGeometry':n case 'CylinderBufferGeometry':n geometry = new Geometries(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);n break;nn case 'ConeGeometry':n case 'ConeBufferGeometry':n geometry = new Geometries(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);n break;nn case 'SphereGeometry':n case 'SphereBufferGeometry':n geometry = new Geometries(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);n break;nn case 'DodecahedronGeometry':n case 'DodecahedronBufferGeometry':n case 'IcosahedronGeometry':n case 'IcosahedronBufferGeometry':n case 'OctahedronGeometry':n case 'OctahedronBufferGeometry':n case 'TetrahedronGeometry':n case 'TetrahedronBufferGeometry':n geometry = new Geometries(data.radius, data.detail);n break;nn case 'RingGeometry':n case 'RingBufferGeometry':n geometry = new Geometries(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);n break;nn case 'TorusGeometry':n case 'TorusBufferGeometry':n geometry = new Geometries(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);n break;nn case 'TorusKnotGeometry':n case 'TorusKnotBufferGeometry':n geometry = new Geometries(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);n break;nn case 'TubeGeometry':n case 'TubeBufferGeometry':n // This only works for built-in curves (e.g. CatmullRomCurve3).n // User defined curves or instances of CurvePath will not be deserialized.n geometry = new Geometries(new Curves().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);n break;nn case 'LatheGeometry':n case 'LatheBufferGeometry':n geometry = new Geometries(data.points, data.segments, data.phiStart, data.phiLength);n break;nn case 'PolyhedronGeometry':n case 'PolyhedronBufferGeometry':n geometry = new Geometries(data.vertices, data.indices, data.radius, data.details);n break;nn case 'ShapeGeometry':n case 'ShapeBufferGeometry':n var geometryShapes = [];nn for (var j = 0, jl = data.shapes.length; j < jl; j++) {n var shape = shapes[data.shapes];n geometryShapes.push(shape);n }nn geometry = new Geometries(geometryShapes, data.curveSegments);n break;nn case 'ExtrudeGeometry':n case 'ExtrudeBufferGeometry':n var geometryShapes = [];nn for (var j = 0, jl = data.shapes.length; j < jl; j++) {n var shape = shapes[data.shapes];n geometryShapes.push(shape);n }nn var extrudePath = data.options.extrudePath;nn if (extrudePath !== undefined) {n data.options.extrudePath = new Curves().fromJSON(extrudePath);n }nn geometry = new Geometries(geometryShapes, data.options);n break;nn case 'BufferGeometry':n case 'InstancedBufferGeometry':n geometry = bufferGeometryLoader.parse(data);n break;nn case 'Geometry':n if ('THREE' in window && 'LegacyJSONLoader' in THREE) {n var geometryLoader = new THREE.LegacyJSONLoader();n geometry = geometryLoader.parse(data, this.resourcePath).geometry;n } else {n console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');n }nn break;nn default:n console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');n continue;n }nn geometry.uuid = data.uuid;n if (data.name !== undefined) geometry.name = data.name;n if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;n geometries = geometry;n }n }nn return geometries;n },n parseMaterials: function parseMaterials(json, textures) {n var cache = {}; // MultiMaterialnn var materials = {};nn if (json !== undefined) {n var loader = new MaterialLoader();n loader.setTextures(textures);nn for (var i = 0, l = json.length; i < l; i++) {n var data = json;nn if (data.type === 'MultiMaterial') {n // Deprecatedn var array = [];nn for (var j = 0; j < data.materials.length; j++) {n var material = data.materials;nn if (cache === undefined) {n cache = loader.parse(material);n }nn array.push(cache);n }nn materials = array;n } else {n if (cache === undefined) {n cache = loader.parse(data);n }nn materials = cache;n }n }n }nn return materials;n },n parseAnimations: function parseAnimations(json) {n var animations = [];nn for (var i = 0; i < json.length; i++) {n var data = json;n var clip = AnimationClip.parse(data);n if (data.uuid !== undefined) clip.uuid = data.uuid;n animations.push(clip);n }nn return animations;n },n parseImages: function parseImages(json, onLoad) {n var scope = this;n var images = {};nn function loadImage(url) {n scope.manager.itemStart(url);n return loader.load(url, function () {n scope.manager.itemEnd(url);n }, undefined, function () {n scope.manager.itemError(url);n scope.manager.itemEnd(url);n });n }nn if (json !== undefined && json.length > 0) {n var manager = new LoadingManager(onLoad);n var loader = new ImageLoader(manager);n loader.setCrossOrigin(this.crossOrigin);nn for (var i = 0, il = json.length; i < il; i++) {n var image = json;n var url = image.url;nn if (Array.isArray(url)) {n // load array of images e.g CubeTexturen images = [];nn for (var j = 0, jl = url.length; j < jl; j++) {n var currentUrl = url;n var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;n images.push(loadImage(path));n }n } else {n // load single imagen var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;n images = loadImage(path);n }n }n }nn return images;n },n parseTextures: function parseTextures(json, images) {n function parseConstant(value, type) {n if (typeof value === 'number') return value;n console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);n return type;n }nn var textures = {};nn if (json !== undefined) {n for (var i = 0, l = json.length; i < l; i++) {n var data = json;nn if (data.image === undefined) {n console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);n }nn if (images === undefined) {n console.warn('THREE.ObjectLoader: Undefined image', data.image);n }nn var texture;nn if (Array.isArray(images)) {n texture = new CubeTexture(images);n } else {n texture = new Texture(images);n }nn texture.needsUpdate = true;n texture.uuid = data.uuid;n if (data.name !== undefined) texture.name = data.name;n if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);n if (data.offset !== undefined) texture.offset.fromArray(data.offset);n if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);n if (data.center !== undefined) texture.center.fromArray(data.center);n if (data.rotation !== undefined) texture.rotation = data.rotation;nn if (data.wrap !== undefined) {n texture.wrapS = parseConstant(data.wrap, TEXTURE_WRAPPING);n texture.wrapT = parseConstant(data.wrap, TEXTURE_WRAPPING);n }nn if (data.format !== undefined) texture.format = data.format;n if (data.type !== undefined) texture.type = data.type;n if (data.encoding !== undefined) texture.encoding = data.encoding;n if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);n if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);n if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;n if (data.flipY !== undefined) texture.flipY = data.flipY;n if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;n if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;n textures = texture;n }n }nn return textures;n },n parseObject: function parseObject(data, geometries, materials) {n var object;nn function getGeometry(name) {n if (geometries === undefined) {n console.warn('THREE.ObjectLoader: Undefined geometry', name);n }nn return geometries;n }nn function getMaterial(name) {n if (name === undefined) return undefined;nn if (Array.isArray(name)) {n var array = [];nn for (var i = 0, l = name.length; i < l; i++) {n var uuid = name;nn if (materials === undefined) {n console.warn('THREE.ObjectLoader: Undefined material', uuid);n }nn array.push(materials);n }nn return array;n }nn if (materials === undefined) {n console.warn('THREE.ObjectLoader: Undefined material', name);n }nn return materials;n }nn switch (data.type) {n case 'Scene':n object = new Scene();nn if (data.background !== undefined) {n if (Number.isInteger(data.background)) {n object.background = new Color(data.background);n }n }nn if (data.fog !== undefined) {n if (data.fog.type === 'Fog') {n object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);n } else if (data.fog.type === 'FogExp2') {n object.fog = new FogExp2(data.fog.color, data.fog.density);n }n }nn break;nn case 'PerspectiveCamera':n object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);n if (data.focus !== undefined) object.focus = data.focus;n if (data.zoom !== undefined) object.zoom = data.zoom;n if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;n if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;n if (data.view !== undefined) object.view = Object.assign({}, data.view);n break;nn case 'OrthographicCamera':n object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);n if (data.zoom !== undefined) object.zoom = data.zoom;n if (data.view !== undefined) object.view = Object.assign({}, data.view);n break;nn case 'AmbientLight':n object = new AmbientLight(data.color, data.intensity);n break;nn case 'DirectionalLight':n object = new DirectionalLight(data.color, data.intensity);n break;nn case 'PointLight':n object = new PointLight(data.color, data.intensity, data.distance, data.decay);n break;nn case 'RectAreaLight':n object = new RectAreaLight(data.color, data.intensity, data.width, data.height);n break;nn case 'SpotLight':n object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);n break;nn case 'HemisphereLight':n object = new HemisphereLight(data.color, data.groundColor, data.intensity);n break;nn case 'SkinnedMesh':n console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');nn case 'Mesh':n var geometry = getGeometry(data.geometry);n var material = getMaterial(data.material);nn if (geometry.bones && geometry.bones.length > 0) {n object = new SkinnedMesh(geometry, material);n } else {n object = new Mesh(geometry, material);n }nn if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);n break;nn case 'LOD':n object = new LOD();n break;nn case 'Line':n object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);n break;nn case 'LineLoop':n object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));n break;nn case 'LineSegments':n object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));n break;nn case 'PointCloud':n case 'Points':n object = new Points(getGeometry(data.geometry), getMaterial(data.material));n break;nn case 'Sprite':n object = new Sprite(getMaterial(data.material));n break;nn case 'Group':n object = new Group();n break;nn default:n object = new Object3D();n }nn object.uuid = data.uuid;n if (data.name !== undefined) object.name = data.name;nn if (data.matrix !== undefined) {n object.matrix.fromArray(data.matrix);n if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;n if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);n } else {n if (data.position !== undefined) object.position.fromArray(data.position);n if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);n if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);n if (data.scale !== undefined) object.scale.fromArray(data.scale);n }nn if (data.castShadow !== undefined) object.castShadow = data.castShadow;n if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;nn if (data.shadow) {n if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;n if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;n if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);n if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);n }nn if (data.visible !== undefined) object.visible = data.visible;n if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;n if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;n if (data.userData !== undefined) object.userData = data.userData;n if (data.layers !== undefined) object.layers.mask = data.layers;nn if (data.children !== undefined) {n var children = data.children;nn for (var i = 0; i < children.length; i++) {n object.add(this.parseObject(children, geometries, materials));n }n }nn if (data.type === 'LOD') {n var levels = data.levels;nn for (var l = 0; l < levels.length; l++) {n var level = levels;n var child = object.getObjectByProperty('uuid', level.object);nn if (child !== undefined) {n object.addLevel(child, level.distance);n }n }n }nn return object;n }n});nvar TEXTURE_MAPPING = {n UVMapping: UVMapping,n CubeReflectionMapping: CubeReflectionMapping,n CubeRefractionMapping: CubeRefractionMapping,n EquirectangularReflectionMapping: EquirectangularReflectionMapping,n EquirectangularRefractionMapping: EquirectangularRefractionMapping,n SphericalReflectionMapping: SphericalReflectionMapping,n CubeUVReflectionMapping: CubeUVReflectionMapping,n CubeUVRefractionMapping: CubeUVRefractionMappingn};nvar TEXTURE_WRAPPING = {n RepeatWrapping: RepeatWrapping,n ClampToEdgeWrapping: ClampToEdgeWrapping,n MirroredRepeatWrapping: MirroredRepeatWrappingn};nvar TEXTURE_FILTER = {n NearestFilter: NearestFilter,n NearestMipmapNearestFilter: NearestMipmapNearestFilter,n NearestMipmapLinearFilter: NearestMipmapLinearFilter,n LinearFilter: LinearFilter,n LinearMipmapNearestFilter: LinearMipmapNearestFilter,n LinearMipmapLinearFilter: LinearMipmapLinearFiltern};n/**n * @author thespite / clicktorelease.com/n */nnfunction ImageBitmapLoader(manager) {n if (typeof createImageBitmap === 'undefined') {n console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');n }nn if (typeof fetch === 'undefined') {n console.warn('THREE.ImageBitmapLoader: fetch() not supported.');n }nn Loader.call(this, manager);n this.options = undefined;n}nnImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: ImageBitmapLoader,n setOptions: function setOptions(options) {n this.options = options;n return this;n },n load: function load(url, onLoad, onProgress, onError) {n if (url === undefined) url = '';n if (this.path !== undefined) url = this.path + url;n url = this.manager.resolveURL(url);n var scope = this;n var cached = Cache.get(url);nn if (cached !== undefined) {n scope.manager.itemStart(url);n setTimeout(function () {n if (onLoad) onLoad(cached);n scope.manager.itemEnd(url);n }, 0);n return cached;n }nn fetch(url).then(function (res) {n return res.blob();n }).then(function (blob) {n if (scope.options === undefined) {n // Workaround for FireFox. It causes an error if you pass options.n return createImageBitmap(blob);n } else {n return createImageBitmap(blob, scope.options);n }n }).then(function (imageBitmap) {n Cache.add(url, imageBitmap);n if (onLoad) onLoad(imageBitmap);n scope.manager.itemEnd(url);n })["catch"](function (e) {n if (onError) onError(e);n scope.manager.itemError(url);n scope.manager.itemEnd(url);n });n scope.manager.itemStart(url);n }n});n/**n * @author zz85 / www.lab4games.net/zz85/blogn * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"n **/nnfunction ShapePath() {n this.type = 'ShapePath';n this.color = new Color();n this.subPaths = [];n this.currentPath = null;n}nnObject.assign(ShapePath.prototype, {n moveTo: function moveTo(x, y) {n this.currentPath = new Path();n this.subPaths.push(this.currentPath);n this.currentPath.moveTo(x, y);n },n lineTo: function lineTo(x, y) {n this.currentPath.lineTo(x, y);n },n quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {n this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);n },n bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {n this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);n },n splineThru: function splineThru(pts) {n this.currentPath.splineThru(pts);n },n toShapes: function toShapes(isCCW, noHoles) {n function toShapesNoHoles(inSubpaths) {n var shapes = [];nn for (var i = 0, l = inSubpaths.length; i < l; i++) {n var tmpPath = inSubpaths;n var tmpShape = new Shape();n tmpShape.curves = tmpPath.curves;n shapes.push(tmpShape);n }nn return shapes;n }nn function isPointInsidePolygon(inPt, inPolygon) {n var polyLen = inPolygon.length; // inPt on polygon contour => immediate success orn // toggling of inside/outside at every single! intersection point of an edgen // with the horizontal line through inPt, left of inPtn // not counting lowerY endpoints of edges and whole edges on that linenn var inside = false;nn for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {n var edgeLowPt = inPolygon;n var edgeHighPt = inPolygon;n var edgeDx = edgeHighPt.x - edgeLowPt.x;n var edgeDy = edgeHighPt.y - edgeLowPt.y;nn if (Math.abs(edgeDy) > Number
.EPSILON) {n // not paralleln if (edgeDy < 0) {n edgeLowPt = inPolygon;n edgeDx = -edgeDx;n edgeHighPt = inPolygon;n edgeDy = -edgeDy;n }nn if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;nn if (inPt.y === edgeLowPt.y) {n if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?n // continue;tttt// no intersection or edgeLowPt => doesn't count !!!n } else {n var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);n if (perpEdge === 0) return true; // inPt is on contour ?nn if (perpEdge < 0) continue;n inside = !inside; // true intersection left of inPtn }n } else {n // parallel or collinearn if (inPt.y !== edgeLowPt.y) continue; // paralleln // edge lies on the same horizontal line as inPtnn if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !n // continue;n }n }nn return inside;n }nn var isClockWise = ShapeUtils.isClockWise;n var subPaths = this.subPaths;n if (subPaths.length === 0) return [];n if (noHoles === true) return toShapesNoHoles(subPaths);n var solid,n tmpPath,n tmpShape,n shapes = [];nn if (subPaths.length === 1) {n tmpPath = subPaths;n tmpShape = new Shape();n tmpShape.curves = tmpPath.curves;n shapes.push(tmpShape);n return shapes;n }nn var holesFirst = !isClockWise(subPaths.getPoints());n holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);nn var betterShapeHoles = [];n var newShapes = [];n var newShapeHoles = [];n var mainIdx = 0;n var tmpPoints;n newShapes = undefined;n newShapeHoles = [];nn for (var i = 0, l = subPaths.length; i < l; i++) {n tmpPath = subPaths;n tmpPoints = tmpPath.getPoints();n solid = isClockWise(tmpPoints);n solid = isCCW ? !solid : solid;nn if (solid) {n if (!holesFirst && newShapes) mainIdx++;n newShapes = {n s: new Shape(),n p: tmpPointsn };n newShapes.s.curves = tmpPath.curves;n if (holesFirst) mainIdx++;n newShapeHoles = []; //console.log('cw', i);n } else {n newShapeHoles.push({n h: tmpPath,n p: tmpPointsn }); //console.log('ccw', i);n }n } // only Holes? -> probably all Shapes with wrong orientationnnn if (!newShapes) return toShapesNoHoles(subPaths);nn if (newShapes.length > 1) {n var ambiguous = false;n var toChange = [];nn for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {n betterShapeHoles = [];n }nn for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {n var sho = newShapeHoles;nn for (var hIdx = 0; hIdx < sho.length; hIdx++) {n var ho = sho;n var hole_unassigned = true;nn for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {n if (isPointInsidePolygon(ho.p, newShapes.p)) {n if (sIdx !== s2Idx) toChange.push({n froms: sIdx,n tos: s2Idx,n hole: hIdxn });nn if (hole_unassigned) {n hole_unassigned = false;n betterShapeHoles.push(ho);n } else {n ambiguous = true;n }n }n }nn if (hole_unassigned) {n betterShapeHoles.push(ho);n }n }n } // console.log("ambiguous: ", ambiguous);nnn if (toChange.length > 0) {n // console.log("to change: ", toChange);n if (!ambiguous) newShapeHoles = betterShapeHoles;n }n }nn var tmpHoles;nn for (var i = 0, il = newShapes.length; i < il; i++) {n tmpShape = newShapes.s;n shapes.push(tmpShape);n tmpHoles = newShapeHoles;nn for (var j = 0, jl = tmpHoles.length; j < jl; j++) {n tmpShape.holes.push(tmpHoles.h);n }n } //console.log("shape", shapes);nnn return shapes;n }n});n/**n * @author zz85 / www.lab4games.net/zz85/blogn * @author mrdoob / mrdoob.com/n */nnfunction Font(data) {n this.type = 'Font';n this.data = data;n}nnObject.assign(Font.prototype, {n isFont: true,n generateShapes: function generateShapes(text, size) {n if (size === undefined) size = 100;n var shapes = [];n var paths = createPaths(text, size, this.data);nn for (var p = 0, pl = paths.length; p < pl; p++) {n Array.prototype.push.apply(shapes, paths.toShapes());n }nn return shapes;n }n});nnfunction createPaths(text, size, data) {n var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988nn var scale = size / data.resolution;n var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;n var paths = [];n var offsetX = 0,n offsetY = 0;nn for (var i = 0; i < chars.length; i++) {n var _char = chars;nn if (_char === '\n') {n offsetX = 0;n offsetY -= line_height;n } else {n var ret = createPath(_char, scale, offsetX, offsetY, data);n offsetX += ret.offsetX;n paths.push(ret.path);n }n }nn return paths;n}nnfunction createPath(_char2, scale, offsetX, offsetY, data) {n var glyph = data.glyphs || data.glyphs;nn if (!glyph) {n console.error('THREE.Font: character "' + _char2 + '" does not exists in font family ' + data.familyName + '.');n return;n }nn var path = new ShapePath();n var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;nn if (glyph.o) {n var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));nn for (var i = 0, l = outline.length; i < l;) {n var action = outline;nn switch (action) {n case 'm':n // moveTon x = outline * scale + offsetX;n y = outline * scale + offsetY;n path.moveTo(x, y);n break;nn case 'l':n // lineTon x = outline * scale + offsetX;n y = outline * scale + offsetY;n path.lineTo(x, y);n break;nn case 'q':n // quadraticCurveTon cpx = outline * scale + offsetX;n cpy = outline * scale + offsetY;n cpx1 = outline * scale + offsetX;n cpy1 = outline * scale + offsetY;n path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);n break;nn case 'b':n // bezierCurveTon cpx = outline * scale + offsetX;n cpy = outline * scale + offsetY;n cpx1 = outline * scale + offsetX;n cpy1 = outline * scale + offsetY;n cpx2 = outline * scale + offsetX;n cpy2 = outline * scale + offsetY;n path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);n break;n }n }n }nn return {n offsetX: glyph.ha * scale,n path: pathn };n}n/**n * @author mrdoob / mrdoob.com/n */nnnfunction FontLoader(manager) {n Loader.call(this, manager);n}nnFontLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: FontLoader,n load: function load(url, onLoad, onProgress, onError) {n var scope = this;n var loader = new FileLoader(this.manager);n loader.setPath(this.path);n loader.load(url, function (text) {n var json;nn try {n json = JSON.parse(text);n } catch (e) {n console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');n json = JSON.parse(text.substring(65, text.length - 2));n }nn var font = scope.parse(json);n if (onLoad) onLoad(font);n }, onProgress, onError);n },n parse: function parse(json) {n return new Font(json);n }n});n/**n * @author mrdoob / mrdoob.com/n */nnvar _context;nnvar AudioContext = {n getContext: function getContext() {n if (_context === undefined) {n _context = new (window.AudioContext || window.webkitAudioContext)();n }nn return _context;n },n setContext: function setContext(value) {n _context = value;n }n};n/**n * @author Reece Aaron Lecrivain / reecenotes.com/n */nnfunction AudioLoader(manager) {n Loader.call(this, manager);n}nnAudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {n constructor: AudioLoader,n load: function load(url, onLoad, onProgress, onError) {n var loader = new FileLoader(this.manager);n loader.setResponseType('arraybuffer');n loader.setPath(this.path);n loader.load(url, function (buffer) {n // Create a copy of the buffer. The `decodeAudioData` methodn // detaches the buffer when complete, preventing reuse.n var bufferCopy = buffer.slice(0);n var context = AudioContext.getContext();n context.decodeAudioData(bufferCopy, function (audioBuffer) {n onLoad(audioBuffer);n });n }, onProgress, onError);n }n});n/**n * @author bhouston / clara.ion * @author WestLangley / github.com/WestLangleyn *n * Primary reference:n * graphics.stanford.edu/papers/envmap/envmap.pdfn *n * Secondary reference:n * www.ppsloan.org/publications/StupidSH36.pdfn */n// 3-band SH defined by 9 coefficientsnnfunction SphericalHarmonics3() {n this.coefficients = [];nn for (var i = 0; i < 9; i++) {n this.coefficients.push(new Vector3());n }n}nnObject.assign(SphericalHarmonics3.prototype, {n isSphericalHarmonics3: true,n set: function set(coefficients) {n for (var i = 0; i < 9; i++) {n this.coefficients.copy(coefficients);n }nn return this;n },n zero: function zero() {n for (var i = 0; i < 9; i++) {n this.coefficients.set(0, 0, 0);n }nn return this;n },n // get the radiance in the direction of the normaln // target is a Vector3n getAt: function getAt(normal, target) {n // normal is assumed to be unit lengthn var x = normal.x,n y = normal.y,n z = normal.z;n var coeff = this.coefficients; // band 0nn target.copy(coeff).multiplyScalar(0.282095); // band 1nn target.addScale(coeff, 0.488603 * y);n target.addScale(coeff, 0.488603 * z);n target.addScale(coeff, 0.488603 * x); // band 2nn target.addScale(coeff, 1.092548 * (x * y));n target.addScale(coeff, 1.092548 * (y * z));n target.addScale(coeff, 0.315392 * (3.0 * z * z - 1.0));n target.addScale(coeff, 1.092548 * (x * z));n target.addScale(coeff, 0.546274 * (x * x - y * y));n return target;n },n // get the irradiance (radiance convolved with cosine lobe) in the direction of the normaln // target is a Vector3n // graphics.stanford.edu/papers/envmap/envmap.pdfn getIrradianceAt: function getIrradianceAt(normal, target) {n // normal is assumed to be unit lengthn var x = normal.x,n y = normal.y,n z = normal.z;n var coeff = this.coefficients; // band 0nn target.copy(coeff).multiplyScalar(0.886227); // π * 0.282095n // band 1nn target.addScale(coeff, 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603nn target.addScale(coeff, 2.0 * 0.511664 * z);n target.addScale(coeff, 2.0 * 0.511664 * x); // band 2nn target.addScale(coeff, 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548nn target.addScale(coeff, 2.0 * 0.429043 * y * z);n target.addScale(coeff, 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3nn target.addScale(coeff, 2.0 * 0.429043 * x * z);n target.addScale(coeff, 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274nn return target;n },n add: function add(sh) {n for (var i = 0; i < 9; i++) {n this.coefficients.add(sh.coefficients);n }nn return this;n },n scale: function scale(s) {n for (var i = 0; i < 9; i++) {n this.coefficients.multiplyScalar(s);n }nn return this;n },n lerp: function lerp(sh, alpha) {n for (var i = 0; i < 9; i++) {n this.coefficients.lerp(sh.coefficients, alpha);n }nn return this;n },n equals: function equals(sh) {n for (var i = 0; i < 9; i++) {n if (!this.coefficients.equals(sh.coefficients)) {n return false;n }n }nn return true;n },n copy: function copy(sh) {n return this.set(sh.coefficients);n },n clone: function clone() {n return new this.constructor().copy(this);n },n fromArray: function fromArray(array, offset) {n if (offset === undefined) offset = 0;n var coefficients = this.coefficients;nn for (var i = 0; i < 9; i++) {n coefficients.fromArray(array, offset + i * 3);n }nn return this;n },n toArray: function toArray(array, offset) {n if (array === undefined) array = [];n if (offset === undefined) offset = 0;n var coefficients = this.coefficients;nn for (var i = 0; i < 9; i++) {n coefficients.toArray(array, offset + i * 3);n }nn return array;n }n});nObject.assign(SphericalHarmonics3, {n // evaluate the basis functionsn // shBasis is an Array[ 9 ]n getBasisAt: function getBasisAt(normal, shBasis) {n // normal is assumed to be unit lengthn var x = normal.x,n y = normal.y,n z = normal.z; // band 0nn shBasis = 0.282095; // band 1nn shBasis = 0.488603 * y;n shBasis = 0.488603 * z;n shBasis = 0.488603 * x; // band 2nn shBasis = 1.092548 * x * y;n shBasis = 1.092548 * y * z;n shBasis = 0.315392 * (3 * z * z - 1);n shBasis = 1.092548 * x * z;n shBasis = 0.546274 * (x * x - y * y);n }n});n/**n * @author WestLangley / github.com/WestLangleyn *n * A LightProbe is a source of indirect-diffuse lightn */nnfunction LightProbe(sh, intensity) {n Light.call(this, undefined, intensity);n this.sh = sh !== undefined ? sh : new SphericalHarmonics3();n}nnLightProbe.prototype = Object.assign(Object.create(Light.prototype), {n constructor: LightProbe,n isLightProbe: true,n copy: function copy(source) {n Light.prototype.copy.call(this, source);n this.sh.copy(source.sh);n this.intensity = source.intensity;n return this;n },n toJSON: function toJSON(meta) {n var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todonn return data;n }n});n/**n * @author WestLangley / github.com/WestLangleyn */nnfunction HemisphereLightProbe(skyColor, groundColor, intensity) {n LightProbe.call(this, undefined, intensity);n var color1 = new Color().set(skyColor);n var color2 = new Color().set(groundColor);n var sky = new Vector3(color1.r, color1.g, color1.b);n var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );nn var c0 = Math.sqrt(Math.PI);n var c1 = c0 * Math.sqrt(0.75);n this.sh.coefficients.copy(sky).add(ground).multiplyScalar(c0);n this.sh.coefficients.copy(sky).sub(ground).multiplyScalar(c1);n}nnHemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {n constructor: HemisphereLightProbe,n isHemisphereLightProbe: true,n copy: function copy(source) {n // modifying colors not currently supportedn LightProbe.prototype.copy.call(this, source);n return this;n },n toJSON: function toJSON(meta) {n var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todonn return data;n }n});n/**n * @author WestLangley / github.com/WestLangleyn */nnfunction AmbientLightProbe(color, intensity) {n LightProbe.call(this, undefined, intensity);n var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );nn this.sh.coefficients.set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));n}nnAmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {n constructor: AmbientLightProbe,n isAmbientLightProbe: true,n copy: function copy(source) {n // modifying color not currently supportedn LightProbe.prototype.copy.call(this, source);n return this;n },n toJSON: function toJSON(meta) {n var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todonn return data;n }n});nnvar _eyeRight = new Matrix4();nnvar _eyeLeft = new Matrix4();n/**n * @author mrdoob / mrdoob.com/n */nnnfunction StereoCamera() {n this.type = 'StereoCamera';n this.aspect = 1;n this.eyeSep = 0.064;n this.cameraL = new PerspectiveCamera();n this.cameraL.layers.enable(1);n this.cameraL.matrixAutoUpdate = false;n this.cameraR = new PerspectiveCamera();n this.cameraR.layers.enable(2);n this.cameraR.matrixAutoUpdate = false;n this._cache = {n focus: null,n fov: null,n aspect: null,n near: null,n far: null,n zoom: null,n eyeSep: nulln };n}nnObject.assign(StereoCamera.prototype, {n update: function update(camera) {n var cache = this._cache;n var 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;nn if (needsUpdate) {n cache.focus = camera.focus;n cache.fov = camera.fov;n cache.aspect = camera.aspect * this.aspect;n cache.near = camera.near;n cache.far = camera.far;n cache.zoom = camera.zoom;n cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based onn // paulbourke.net/stereographics/stereorender/nn var projectionMatrix = camera.projectionMatrix.clone();n var eyeSepHalf = cache.eyeSep / 2;n var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;n var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;n var xmin, xmax; // translate xOffsetnn _eyeLeft.elements = -eyeSepHalf;n _eyeRight.elements = eyeSepHalf; // for left eyenn xmin = -ymax * cache.aspect + eyeSepOnProjection;n xmax = ymax * cache.aspect + eyeSepOnProjection;n projectionMatrix.elements = 2 * cache.near / (xmax - xmin);n projectionMatrix.elements = (xmax + xmin) / (xmax - xmin);n this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eyenn xmin = -ymax * cache.aspect - eyeSepOnProjection;n xmax = ymax * cache.aspect - eyeSepOnProjection;n projectionMatrix.elements = 2 * cache.near / (xmax - xmin);n projectionMatrix.elements = (xmax + xmin) / (xmax - xmin);n this.cameraR.projectionMatrix.copy(projectionMatrix);n }nn this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);n this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);n }n});n/**n * @author alteredq / alteredqualia.com/n */nnfunction Clock(autoStart) {n this.autoStart = autoStart !== undefined ? autoStart : true;n this.startTime = 0;n this.oldTime = 0;n this.elapsedTime = 0;n this.running = false;n}nnObject.assign(Clock.prototype, {n start: function start() {n this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732nn this.oldTime = this.startTime;n this.elapsedTime = 0;n this.running = true;n },n stop: function stop() {n this.getElapsedTime();n this.running = false;n this.autoStart = false;n },n getElapsedTime: function getElapsedTime() {n this.getDelta();n return this.elapsedTime;n },n getDelta: function getDelta() {n var diff = 0;nn if (this.autoStart && !this.running) {n this.start();n return 0;n }nn if (this.running) {n var newTime = (typeof performance === 'undefined' ? Date : performance).now();n diff = (newTime - this.oldTime) / 1000;n this.oldTime = newTime;n this.elapsedTime += diff;n }nn return diff;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnvar _position$2 = new Vector3();nnvar _quaternion$3 = new Quaternion();nnvar _scale$1 = new Vector3();nnvar _orientation = new Vector3();nnfunction AudioListener() {n Object3D.call(this);n this.type = 'AudioListener';n this.context = AudioContext.getContext();n this.gain = this.context.createGain();n this.gain.connect(this.context.destination);n this.filter = null;n this.timeDelta = 0; // privatenn this._clock = new Clock();n}nnAudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: AudioListener,n getInput: function getInput() {n return this.gain;n },n removeFilter: function removeFilter() {n if (this.filter !== null) {n this.gain.disconnect(this.filter);n this.filter.disconnect(this.context.destination);n this.gain.connect(this.context.destination);n this.filter = null;n }nn return this;n },n getFilter: function getFilter() {n return this.filter;n },n setFilter: function setFilter(value) {n if (this.filter !== null) {n this.gain.disconnect(this.filter);n this.filter.disconnect(this.context.destination);n } else {n this.gain.disconnect(this.context.destination);n }nn this.filter = value;n this.gain.connect(this.filter);n this.filter.connect(this.context.destination);n return this;n },n getMasterVolume: function getMasterVolume() {n return this.gain.gain.value;n },n setMasterVolume: function setMasterVolume(value) {n this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);n return this;n },n updateMatrixWorld: function updateMatrixWorld(force) {n Object3D.prototype.updateMatrixWorld.call(this, force);n var listener = this.context.listener;n var up = this.up;n this.timeDelta = this._clock.getDelta();n this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);nn _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);nn if (listener.positionX) {n // code path for Chrome (see #14393)n var endTime = this.context.currentTime + this.timeDelta;n listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);n listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);n listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);n listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);n listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);n listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);n listener.upX.linearRampToValueAtTime(up.x, endTime);n listener.upY.linearRampToValueAtTime(up.y, endTime);n listener.upZ.linearRampToValueAtTime(up.z, endTime);n } else {n listener.setPosition(_position$2.x, _position$2.y, _position$2.z);n listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);n }n }n});n/**n * @author mrdoob / mrdoob.com/n * @author Reece Aaron Lecrivain / reecenotes.com/n */nnfunction Audio(listener) {n Object3D.call(this);n this.type = 'Audio';n this.listener = listener;n this.context = listener.context;n this.gain = this.context.createGain();n this.gain.connect(listener.getInput());n this.autoplay = false;n this.buffer = null;n this.detune = 0;n this.loop = false;n this.startTime = 0;n this.offset = 0;n this.duration = undefined;n this.playbackRate = 1;n this.isPlaying = false;n this.hasPlaybackControl = true;n this.sourceType = 'empty';n this.filters = [];n}nnAudio.prototype = Object.assign(Object.create(Object3D.prototype), {n constructor: Audio,n getOutput: function getOutput() {n return this.gain;n },n setNodeSource: function setNodeSource(audioNode) {n this.hasPlaybackControl = false;n this.sourceType = 'audioNode';n this.source = audioNode;n this.connect();n return this;n },n setMediaElementSource: function setMediaElementSource(mediaElement) {n this.hasPlaybackControl = false;n this.sourceType = 'mediaNode';n this.source = this.context.createMediaElementSource(mediaElement);n this.connect();n return this;n },n setBuffer: function setBuffer(audioBuffer) {n this.buffer = audioBuffer;n this.sourceType = 'buffer';n if (this.autoplay) this.play();n return this;n },n play: function play() {n if (this.isPlaying === true) {n console.warn('THREE.Audio: Audio is already playing.');n return;n }nn if (this.hasPlaybackControl === false) {n console.warn('THREE.Audio: this Audio has no playback control.');n return;n }nn var source = this.context.createBufferSource();n source.buffer = this.buffer;n source.loop = this.loop;n source.onended = this.onEnded.bind(this);n this.startTime = this.context.currentTime;n source.start(this.startTime, this.offset, this.duration);n this.isPlaying = true;n this.source = source;n this.setDetune(this.detune);n this.setPlaybackRate(this.playbackRate);n return this.connect();n },n pause: function pause() {n if (this.hasPlaybackControl === false) {n console.warn('THREE.Audio: this Audio has no playback control.');n return;n }nn if (this.isPlaying === true) {n this.source.stop();n this.source.onended = null;n this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;n this.isPlaying = false;n }nn return this;n },n stop: function stop() {n if (this.hasPlaybackControl === false) {n console.warn('THREE.Audio: this Audio has no playback control.');n return;n }nn this.source.stop();n this.source.onended = null;n this.offset = 0;n this.isPlaying = false;n return this;n },n connect: function connect() {n if (this.filters.length > 0) {n this.source.connect(this.filters);nn for (var i = 1, l = this.filters.length; i < l; i++) {n this.filters[i - 1].connect(this.filters);n }nn this.filters[this.filters.length - 1].connect(this.getOutput());n } else {n this.source.connect(this.getOutput());n }nn return this;n },n disconnect: function disconnect() {n if (this.filters.length > 0) {n this.source.disconnect(this.filters);nn for (var i = 1, l = this.filters.length; i < l; i++) {n this.filters[i - 1].disconnect(this.filters);n }nn this.filters[this.filters.length - 1].disconnect(this.getOutput());n } else {n this.source.disconnect(this.getOutput());n }nn return this;n },n getFilters: function getFilters() {n return this.filters;n },n setFilters: function setFilters(value) {n if (!value) value = [];nn if (this.isPlaying === true) {n this.disconnect();n this.filters = value;n this.connect();n } else {n this.filters = value;n }nn return this;n },n setDetune: function setDetune(value) {n this.detune = value;n if (this.source.detune === undefined) return; // only set detune when availablenn if (this.isPlaying === true) {n this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);n }nn return this;n },n getDetune: function getDetune() {n return this.detune;n },n getFilter: function getFilter() {n return this.getFilters();n },n setFilter: function setFilter(filter) {n return this.setFilters(filter ? [filter] : []);n },n setPlaybackRate: function setPlaybackRate(value) {n if (this.hasPlaybackControl === false) {n console.warn('THREE.Audio: this Audio has no playback control.');n return;n }nn this.playbackRate = value;nn if (this.isPlaying === true) {n this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);n }nn return this;n },n getPlaybackRate: function getPlaybackRate() {n return this.playbackRate;n },n onEnded: function onEnded() {n this.isPlaying = false;n },n getLoop: function getLoop() {n if (this.hasPlaybackControl === false) {n console.warn('THREE.Audio: this Audio has no playback control.');n return false;n }nn return this.loop;n },n setLoop: function setLoop(value) {n if (this.hasPlaybackControl === false) {n console.warn('THREE.Audio: this Audio has no playback control.');n return;n }nn this.loop = value;nn if (this.isPlaying === true) {n this.source.loop = this.loop;n }nn return this;n },n getVolume: function getVolume() {n return this.gain.gain.value;n },n setVolume: function setVolume(value) {n this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);n return this;n }n});n/**n * @author mrdoob / mrdoob.com/n */nnvar _position$3 = new Vector3();nnvar _quaternion$4 = new Quaternion();nnvar _scale$2 = new Vector3();nnvar _orientation$1 = new Vector3();nnfunction PositionalAudio(listener) {n Audio.call(this, listener);n this.panner = this.context.createPanner();n this.panner.panningModel = 'HRTF';n this.panner.connect(this.gain);n}nnPositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {n constructor: PositionalAudio,n getOutput: function getOutput() {n return this.panner;n },n getRefDistance: function getRefDistance() {n return this.panner.refDistance;n },n setRefDistance: function setRefDistance(value) {n this.panner.refDistance = value;n return this;n },n getRolloffFactor: function getRolloffFactor() {n return this.panner.rolloffFactor;n },n setRolloffFactor: function setRolloffFactor(value) {n this.panner.rolloffFactor = value;n return this;n },n getDistanceModel: function getDistanceModel() {n return this.panner.distanceModel;n },n setDistanceModel: function setDistanceModel(value) {n this.panner.distanceModel = value;n return this;n },n getMaxDistance: function getMaxDistance() {n return this.panner.maxDistance;n },n setMaxDistance: function setMaxDistance(value) {n this.panner.maxDistance = value;n return this;n },n setDirectionalCone: function setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {n this.panner.coneInnerAngle = coneInnerAngle;n this.panner.coneOuterAngle = coneOuterAngle;n this.panner.coneOuterGain = coneOuterGain;n return this;n },n updateMatrixWorld: function updateMatrixWorld(force) {n Object3D.prototype.updateMatrixWorld.call(this, force);n if (this.hasPlaybackControl === true && this.isPlaying === false) return;n this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);nn _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);nn var panner = this.panner;nn if (panner.positionX) {n // code path for Chrome and Firefox (see #14393)n var endTime = this.context.currentTime + this.listener.timeDelta;n panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);n panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);n panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);n panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);n panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);n panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);n } else {n panner.setPosition(_position$3.x, _position$3.y, _position$3.z);n panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);n }n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction AudioAnalyser(audio, fftSize) {n this.analyser = audio.context.createAnalyser();n this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;n this.data = new Uint8Array(this.analyser.frequencyBinCount);n audio.getOutput().connect(this.analyser);n}nnObject.assign(AudioAnalyser.prototype, {n getFrequencyData: function getFrequencyData() {n this.analyser.getByteFrequencyData(this.data);n return this.data;n },n getAverageFrequency: function getAverageFrequency() {n var value = 0,n data = this.getFrequencyData();nn for (var i = 0; i < data.length; i++) {n value += data;n }nn return value / data.length;n }n});n/**n *n * Buffered scene graph property that allows weighted accumulation.n *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction PropertyMixer(binding, typeName, valueSize) {n this.binding = binding;n this.valueSize = valueSize;n var bufferType = Float64Array,n mixFunction;nn switch (typeName) {n case 'quaternion':n mixFunction = this._slerp;n break;nn case 'string':n case 'bool':n bufferType = Array;n mixFunction = this._select;n break;nn default:n mixFunction = this._lerp;n }nn this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]n //n // interpolators can use .buffer as their .resultn // the data then goes to 'incoming'n //n // 'accu0' and 'accu1' are used frame-interleaved forn // the cumulative result and are compared to detectn // changesn //n // 'orig' stores the original state of the propertynn this._mixBufferRegion = mixFunction;n this.cumulativeWeight = 0;n this.useCount = 0;n this.referenceCount = 0;n}nnObject.assign(PropertyMixer.prototype, {n // accumulate data in the 'incoming' region into 'accu<i>'n accumulate: function accumulate(accuIndex, weight) {n // note: happily accumulating nothing when weight = 0, the caller knowsn // the weight and shouldn't have made the call in the first placen var buffer = this.buffer,n stride = this.valueSize,n offset = accuIndex * stride + stride,n currentWeight = this.cumulativeWeight;nn if (currentWeight === 0) {n // accuN := incoming * weightn for (var i = 0; i !== stride; ++i) {n buffer[offset + i] = buffer;n }nn currentWeight = weight;n } else {n // accuN := accuN + incoming * weightn currentWeight += weight;n var mix = weight / currentWeight;nn this._mixBufferRegion(buffer, offset, 0, mix, stride);n }nn this.cumulativeWeight = currentWeight;n },n // apply the state of 'accu<i>' to the binding when accus differn apply: function apply(accuIndex) {n var stride = this.valueSize,n buffer = this.buffer,n offset = accuIndex * stride + stride,n weight = this.cumulativeWeight,n binding = this.binding;n this.cumulativeWeight = 0;nn if (weight < 1) {n // accuN := accuN + original * ( 1 - cumulativeWeight )n var originalValueOffset = stride * 3;nn this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);n }nn for (var i = stride, e = stride + stride; i !== e; ++i) {n if (buffer !== buffer[i + stride]) {n // value has changed -> update scene graphn binding.setValue(buffer, offset);n break;n }n }n },n // remember the state of the bound property and copy it to both accusn saveOriginalState: function saveOriginalState() {n var binding = this.binding;n var buffer = this.buffer,n stride = this.valueSize,n originalValueOffset = stride * 3;n binding.getValue(buffer, originalValueOffset); // accu := orig – initially detect changes against the originalnn for (var i = stride, e = originalValueOffset; i !== e; ++i) {n buffer = buffer[originalValueOffset + i % stride];n }nn this.cumulativeWeight = 0;n },n // apply the state previously taken via 'saveOriginalState' to the bindingn restoreOriginalState: function restoreOriginalState() {n var originalValueOffset = this.valueSize * 3;n this.binding.setValue(this.buffer, originalValueOffset);n },n // mix functionsn _select: function _select(buffer, dstOffset, srcOffset, t, stride) {n if (t >= 0.5) {n for (var i = 0; i !== stride; ++i) {n buffer[dstOffset + i] = buffer[srcOffset + i];n }n }n },n _slerp: function _slerp(buffer, dstOffset, srcOffset, t) {n Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);n },n _lerp: function _lerp(buffer, dstOffset, srcOffset, t, stride) {n var s = 1 - t;nn for (var i = 0; i !== stride; ++i) {n var j = dstOffset + i;n buffer = buffer * s + buffer[srcOffset + i] * t;n }n }n});n/**n *n * A reference to a real property in the scene graph.n *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */n// Characters [].:/ are reserved for track binding syntax.nnvar _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';nnvar _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matchesn// only latin characters, and the unicode \p{L} is not yet supported. Son// instead, we exclude reserved characters and match everything else.nnnvar _wordChar = '[^' + _RESERVED_CHARS_RE + ']';nnvar _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but mustn// be matched to parse the rest of the track name.nnnvar _directoryRe = /((?:WC+)*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.nnnvar _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object
on target node, and accessor. May not contain reservedn// characters. Accessor may contain any character except closing bracket.nnnvar _objectRe = /(?:\.(WC+)(?:\)?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor mayn// contain any non-bracket characters.nnnvar _propertyRe = /\.(WC+)(?:\)?/.source.replace('WC', _wordChar);nnvar _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');nnvar _supportedObjectNames = ['material', 'materials', 'bones'];nnfunction Composite(targetGroup, path, optionalParsedPath) {n var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);n this._targetGroup = targetGroup;n this._bindings = targetGroup.subscribe_(path, parsedPath);n}nnObject.assign(Composite.prototype, {n getValue: function getValue(array, offset) {n this.bind(); // bind all bindingnn var firstValidIndex = this.targetGroup.nCachedObjects,n binding = this._bindings; // and only call .getValue on the firstnn if (binding !== undefined) binding.getValue(array, offset);n },n setValue: function setValue(array, offset) {n var bindings = this._bindings;nn for (var i = this.targetGroup.nCachedObjects, n = bindings.length; i !== n; ++i) {n bindings.setValue(array, offset);n }n },n bind: function bind() {n var bindings = this._bindings;nn for (var i = this.targetGroup.nCachedObjects, n = bindings.length; i !== n; ++i) {n bindings.bind();n }n },n unbind: function unbind() {n var bindings = this._bindings;nn for (var i = this.targetGroup.nCachedObjects, n = bindings.length; i !== n; ++i) {n bindings.unbind();n }n }n});nnfunction PropertyBinding(rootNode, path, parsedPath) {n this.path = path;n this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);n this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;n this.rootNode = rootNode;n}nnObject.assign(PropertyBinding, {n Composite: Composite,n create: function create(root, path, parsedPath) {n if (!(root && root.isAnimationObjectGroup)) {n return new PropertyBinding(root, path, parsedPath);n } else {n return new PropertyBinding.Composite(root, path, parsedPath);n }n },nn /**n * Replaces spaces with underscores and removes unsupported characters fromn * node names, to ensure compatibility with parseTrackName().n *n * @param {string} name Node name to be sanitized.n * @return {string}n */n sanitizeNodeName: function sanitizeNodeName(name) {n return name.replace(/\s/g, '_').replace(_reservedRe, '');n },n parseTrackName: function parseTrackName(trackName) {n var matches = _trackRe.exec(trackName);nn if (!matches) {n throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);n }nn var results = {n // directoryName: matches[ 1 ], // (tschw) currently unusedn nodeName: matches,n objectName: matches,n objectIndex: matches,n propertyName: matches,n // requiredn propertyIndex: matchesn };n var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');nn if (lastDot !== undefined && lastDot !== -1) {n var objectName = results.nodeName.substring(lastDot + 1); // Object
names must be checked against a whitelist. Otherwise, theren // is no way to parse 'foo.bar.baz': 'baz' must be a property, butn // 'bar' could be the objectName, or part of a nodeName (which cann // include '.' characters).nn if (_supportedObjectNames.indexOf(objectName) !== -1) {n results.nodeName = results.nodeName.substring(0, lastDot);n results.objectName = objectName;n }n }nn if (results.propertyName === null || results.propertyName.length === 0) {n throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);n }nn return results;n },n findNode: function findNode(root, nodeName) {n if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {n return root;n } // search into skeleton bones.nnn if (root.skeleton) {n var bone = root.skeleton.getBoneByName(nodeName);nn if (bone !== undefined) {n return bone;n }n } // search into node subtree.nnn if (root.children) {n var searchNodeSubtree = function searchNodeSubtree(children) {n for (var i = 0; i < children.length; i++) {n var childNode = children;nn if (childNode.name === nodeName || childNode.uuid === nodeName) {n return childNode;n }nn var result = searchNodeSubtree(childNode.children);n if (result) return result;n }nn return null;n };nn var subTreeNode = searchNodeSubtree(root.children);nn if (subTreeNode) {n return subTreeNode;n }n }nn return null;n }n});nObject.assign(PropertyBinding.prototype, {n // prototype, continuedn // these are used to "bind" a nonexistent propertyn _getValue_unavailable: function _getValue_unavailable() {},n _setValue_unavailable: function _setValue_unavailable() {},n BindingType: {n Direct: 0,n EntireArray: 1,n ArrayElement: 2,n HasFromToArray: 3n },n Versioning: {n None: 0,n NeedsUpdate: 1,n MatrixWorldNeedsUpdate: 2n },n GetterByBindingType: [function getValue_direct(buffer, offset) {n buffer = this.node;n }, function getValue_array(buffer, offset) {n var source = this.resolvedProperty;nn for (var i = 0, n = source.length; i !== n; ++i) {n buffer = source;n }n }, function getValue_arrayElement(buffer, offset) {n buffer = this.resolvedProperty;n }, function getValue_toArray(buffer, offset) {n this.resolvedProperty.toArray(buffer, offset);n }],n SetterByBindingTypeAndVersioning: [[// Directn function setValue_direct(buffer, offset) {n this.targetObject = buffer;n }, function setValue_direct_setNeedsUpdate(buffer, offset) {n this.targetObject = buffer;n this.targetObject.needsUpdate = true;n }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {n this.targetObject = buffer;n this.targetObject.matrixWorldNeedsUpdate = true;n }], [// EntireArrayn function setValue_array(buffer, offset) {n var dest = this.resolvedProperty;nn for (var i = 0, n = dest.length; i !== n; ++i) {n dest = buffer;n }n }, function setValue_array_setNeedsUpdate(buffer, offset) {n var dest = this.resolvedProperty;nn for (var i = 0, n = dest.length; i !== n; ++i) {n dest = buffer;n }nn this.targetObject.needsUpdate = true;n }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {n var dest = this.resolvedProperty;nn for (var i = 0, n = dest.length; i !== n; ++i) {n dest = buffer;n }nn this.targetObject.matrixWorldNeedsUpdate = true;n }], [// ArrayElementn function setValue_arrayElement(buffer, offset) {n this.resolvedProperty = buffer;n }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {n this.resolvedProperty = buffer;n this.targetObject.needsUpdate = true;n }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {n this.resolvedProperty = buffer;n this.targetObject.matrixWorldNeedsUpdate = true;n }], [// HasToFromArrayn function setValue_fromArray(buffer, offset) {n this.resolvedProperty.fromArray(buffer, offset);n }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {n this.resolvedProperty.fromArray(buffer, offset);n this.targetObject.needsUpdate = true;n }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {n this.resolvedProperty.fromArray(buffer, offset);n this.targetObject.matrixWorldNeedsUpdate = true;n }]],n getValue: function getValue_unbound(targetArray, offset) {n this.bind();n this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:n // 'bind' sets 'this.getValue' / 'setValue' and shadows then // prototype version of these methods with one that representsn // the bound state. When the property is not found, the methodsn // become no-ops.n },n setValue: function getValue_unbound(sourceArray, offset) {n this.bind();n this.setValue(sourceArray, offset);n },n // create getter / setter pair for a property in the scene graphn bind: function bind() {n var targetObject = this.node,n parsedPath = this.parsedPath,n objectName = parsedPath.objectName,n propertyName = parsedPath.propertyName,n propertyIndex = parsedPath.propertyIndex;nn if (!targetObject) {n targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;n this.node = targetObject;n } // set fail state so we can just 'return' on errornnn this.getValue = this._getValue_unavailable;n this.setValue = this._setValue_unavailable; // ensure there is a value nodenn if (!targetObject) {n console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');n return;n }nn if (objectName) {n var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials.…nn switch (objectName) {n case 'materials':n if (!targetObject.material) {n console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);n return;n }nn if (!targetObject.material.materials) {n console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);n return;n }nn targetObject = targetObject.material.materials;n break;nn case 'bones':n if (!targetObject.skeleton) {n console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);n return;n } // potential future optimization: skip this if propertyIndex is already an integern // and convert the integer string to a true integer.nnn targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.nn for (var i = 0; i < targetObject.length; i++) {n if (targetObject.name === objectIndex) {n objectIndex = i;n break;n }n }nn break;nn default:n if (targetObject === undefined) {n console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);n return;n }nn targetObject = targetObject;n }nn if (objectIndex !== undefined) {n if (targetObject === undefined) {n console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);n return;n }nn targetObject = targetObject;n }n } // resolve propertynnn var nodeProperty = targetObject;nn if (nodeProperty === undefined) {n var nodeName = parsedPath.nodeName;n console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);n return;n } // determine versioning schemennn var versioning = this.Versioning.None;n this.targetObject = targetObject;nn if (targetObject.needsUpdate !== undefined) {n // materialn versioning = this.Versioning.NeedsUpdate;n } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {n // node transformn versioning = this.Versioning.MatrixWorldNeedsUpdate;n } // determine how the property gets boundnnn var bindingType = this.BindingType.Direct;nn if (propertyIndex !== undefined) {n // access a sub element of the property array (only primitives are supported right now)n if (propertyName === "morphTargetInfluences") {n // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.n // support resolving morphTarget names into indices.n if (!targetObject.geometry) {n console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);n return;n }nn if (targetObject.geometry.isBufferGeometry) {n if (!targetObject.geometry.morphAttributes) {n console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);n return;n }nn for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {n if (targetObject.geometry.morphAttributes.position.name === propertyIndex) {n propertyIndex = i;n break;n }n }n } else {n if (!targetObject.geometry.morphTargets) {n console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);n return;n }nn for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {n if (targetObject.geometry.morphTargets.name === propertyIndex) {n propertyIndex = i;n break;n }n }n }n }nn bindingType = this.BindingType.ArrayElement;n this.resolvedProperty = nodeProperty;n this.propertyIndex = propertyIndex;n } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {n // must use copy for Object3D.Euler/Quaternionn bindingType = this.BindingType.HasFromToArray;n this.resolvedProperty = nodeProperty;n } else if (Array.isArray(nodeProperty)) {n bindingType = this.BindingType.EntireArray;n this.resolvedProperty = nodeProperty;n } else {n this.propertyName = propertyName;n } // select getter / setternnn this.getValue = this.GetterByBindingType;n this.setValue = this.SetterByBindingTypeAndVersioning[versioning];n },n unbind: function unbind() {n this.node = null; // back to the prototype version of getValue / setValuen // note: avoiding to mutate the shape of 'this' via 'delete'nn this.getValue = this._getValue_unbound;n this.setValue = this._setValue_unbound;n }n}); //!\ DECLARE ALIAS AFTER assign prototype !nnObject.assign(PropertyBinding.prototype, {n // initial state of these methods that calls 'bind'n _getValue_unbound: PropertyBinding.prototype.getValue,n _setValue_unbound: PropertyBinding.prototype.setValuen});n/**n *n * A group of objects that receives a shared animation state.n *n * Usage:n *n * - Add objects you would otherwise pass as 'root' to then * constructor or the .clipAction method of AnimationMixer.n *n * - Instead pass this object as 'root'.n *n * - You can also add and remove objects later when the mixern * is running.n *n * Note:n *n * Objects of this class appear as one object to the mixer,n * so cache control of the individual objects must be donen * on the group.n *n * Limitation:n *n * - The animated properties must be compatible among then * all objects in the group.n *n * - A single property can either be controlled through an * target group or directly, but not both.n *n * @author tschwn */nnfunction AnimationObjectGroup() {n this.uuid = _Math.generateUUID(); // cached objects followed by the active onesnn this._objects = Array.prototype.slice.call(arguments);n this.nCachedObjects_ = 0; // thresholdn // note: read by PropertyBinding.Compositenn var indices = {};n this._indicesByUUID = indices; // for bookkeepingnn for (var i = 0, n = arguments.length; i !== n; ++i) {n indices[arguments.uuid] = i;n }nn this._paths = []; // inside: stringnn this._parsedPaths = []; // inside: { we don't care, here }nn this._bindings = []; // inside: Array< PropertyBinding >nn this._bindingsIndicesByPath = {}; // inside: indices in these arraysnn var scope = this;n this.stats = {n objects: {n get total() {n return scope._objects.length;n },nn get inUse() {n return this.total - scope.nCachedObjects_;n }nn },nn get bindingsPerObject() {n return scope._bindings.length;n }nn };n}nnObject.assign(AnimationObjectGroup.prototype, {n isAnimationObjectGroup: true,n add: function add() {n var objects = this._objects,n nObjects = objects.length,n nCachedObjects = this.nCachedObjects_,n indicesByUUID = this._indicesByUUID,n paths = this._paths,n parsedPaths = this._parsedPaths,n bindings = this._bindings,n nBindings = bindings.length,n knownObject = undefined;nn for (var i = 0, n = arguments.length; i !== n; ++i) {n var object = arguments,n uuid = object.uuid,n index = indicesByUUID;nn if (index === undefined) {n // unknown object -> add it to the ACTIVE regionn index = nObjects++;n indicesByUUID = index;n objects.push(object); // accounting is done, now do the same for all bindingsnn for (var j = 0, m = nBindings; j !== m; ++j) {n bindings.push(new PropertyBinding(object, paths, parsedPaths));n }n } else if (index < nCachedObjects) {n knownObject = objects; // move existing object to the ACTIVE regionnn var firstActiveIndex = –nCachedObjects,n lastCachedObject = objects;n indicesByUUID = index;n objects = lastCachedObject;n indicesByUUID = firstActiveIndex;n objects = object; // accounting is done, now do the same for all bindingsnn for (var j = 0, m = nBindings; j !== m; ++j) {n var bindingsForPath = bindings,n lastCached = bindingsForPath,n binding = bindingsForPath;n bindingsForPath = lastCached;nn if (binding === undefined) {n // since we do not bother to create new bindingsn // for objects that are cached, the binding mayn // or may not existn binding = new PropertyBinding(object, paths, parsedPaths);n }nn bindingsForPath = binding;n }n } else if (objects !== knownObject) {n console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');n } // else the object is already where we want it to benn } // for argumentsnnn this.nCachedObjects_ = nCachedObjects;n },n remove: function remove() {n var objects = this._objects,n nCachedObjects = this.nCachedObjects_,n indicesByUUID = this._indicesByUUID,n bindings = this._bindings,n nBindings = bindings.length;nn for (var i = 0, n = arguments.length; i !== n; ++i) {n var object = arguments,n uuid = object.uuid,n index = indicesByUUID;nn if (index !== undefined && index >= nCachedObjects) {n // move existing object into the CACHED regionn var lastCachedIndex = nCachedObjects++,n firstActiveObject = objects;n indicesByUUID = index;n objects = firstActiveObject;n indicesByUUID = lastCachedIndex;n objects = object; // accounting is done, now do the same for all bindingsnn for (var j = 0, m = nBindings; j !== m; ++j) {n var bindingsForPath = bindings,n firstActive = bindingsForPath,n binding = bindingsForPath;n bindingsForPath = firstActive;n bindingsForPath = binding;n }n }n } // for argumentsnnn this.nCachedObjects_ = nCachedObjects;n },n // remove & forgetn uncache: function uncache() {n var objects = this._objects,n nObjects = objects.length,n nCachedObjects = this.nCachedObjects_,n indicesByUUID = this._indicesByUUID,n bindings = this._bindings,n nBindings = bindings.length;nn for (var i = 0, n = arguments.length; i !== n; ++i) {n var object = arguments,n uuid = object.uuid,n index = indicesByUUID;nn if (index !== undefined) {n delete indicesByUUID;nn if (index < nCachedObjects) {n // object is cached, shrink the CACHED regionn var firstActiveIndex = –nCachedObjects,n lastCachedObject = objects,n lastIndex = –nObjects,n lastObject = objects; // last cached object takes this object's placenn indicesByUUID = index;n objects = lastCachedObject; // last object goes to the activated slot and popnn indicesByUUID = firstActiveIndex;n objects = lastObject;n objects.pop(); // accounting is done, now do the same for all bindingsnn for (var j = 0, m = nBindings; j !== m; ++j) {n var bindingsForPath = bindings,n lastCached = bindingsForPath,n last = bindingsForPath;n bindingsForPath = lastCached;n bindingsForPath = last;n bindingsForPath.pop();n }n } else {n // object is active, just swap with the last and popn var lastIndex = –nObjects,n lastObject = objects;n indicesByUUID = index;n objects = lastObject;n objects.pop(); // accounting is done, now do the same for all bindingsnn for (var j = 0, m = nBindings; j !== m; ++j) {n var bindingsForPath = bindings;n bindingsForPath = bindingsForPath;n bindingsForPath.pop();n }n } // cached or activenn } // if object is knownnn } // for argumentsnnn this.nCachedObjects_ = nCachedObjects;n },n // Internal interface used by befriended PropertyBinding.Composite:n subscribe_: function subscribe_(path, parsedPath) {n // returns an array of bindings for the given path that is changedn // according to the contained objects in the groupn var indicesByPath = this._bindingsIndicesByPath,n index = indicesByPath,n bindings = this._bindings;n if (index !== undefined) return bindings;n var paths = this._paths,n parsedPaths = this._parsedPaths,n objects = this._objects,n nObjects = objects.length,n nCachedObjects = this.nCachedObjects_,n bindingsForPath = new Array(nObjects);n index = bindings.length;n indicesByPath = index;n paths.push(path);n parsedPaths.push(parsedPath);n bindings.push(bindingsForPath);nn for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {n var object = objects;n bindingsForPath = new PropertyBinding(object, path, parsedPath);n }nn return bindingsForPath;n },n unsubscribe_: function unsubscribe_(path) {n // tells the group to forget about a property path and no longern // update the array previously obtained with 'subscribe_'n var indicesByPath = this._bindingsIndicesByPath,n index = indicesByPath;nn if (index !== undefined) {n var paths = this._paths,n parsedPaths = this._parsedPaths,n bindings = this._bindings,n lastBindingsIndex = bindings.length - 1,n lastBindings = bindings,n lastBindingsPath = path;n indicesByPath = index;n bindings = lastBindings;n bindings.pop();n parsedPaths = parsedPaths;n parsedPaths.pop();n paths = paths;n paths.pop();n }n }n});n/**n *n * Action provided by AnimationMixer for scheduling clip playback on specificn * objects.n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn *n */nnfunction AnimationAction(mixer, clip, localRoot) {n this._mixer = mixer;n this._clip = clip;n this._localRoot = localRoot || null;n var tracks = clip.tracks,n nTracks = tracks.length,n interpolants = new Array(nTracks);n var interpolantSettings = {n endingStart: ZeroCurvatureEnding,n endingEnd: ZeroCurvatureEndingn };nn for (var i = 0; i !== nTracks; ++i) {n var interpolant = tracks.createInterpolant(null);n interpolants = interpolant;n interpolant.settings = interpolantSettings;n }nn this._interpolantSettings = interpolantSettings;n this._interpolants = interpolants; // bound by the mixern // inside: PropertyMixer (managed by the mixer)nn this._propertyBindings = new Array(nTracks);n this._cacheIndex = null; // for the memory managernn this._byClipCacheIndex = null; // for the memory managernn this._timeScaleInterpolant = null;n this._weightInterpolant = null;n this.loop = LoopRepeat;n this._loopCount = -1; // global mixer time when the action is to be startedn // it's set back to 'null' upon start of the actionnn this._startTime = null; // scaled local time of the actionn // gets clamped or wrapped to 0..clip.duration according to loopnn this.time = 0;n this.timeScale = 1;n this._effectiveTimeScale = 1;n this.weight = 1;n this._effectiveWeight = 1;n this.repetitions = Infinity; // no. of repetitions when loopingnn this.paused = false; // true -> zero effective time scalenn this.enabled = true; // false -> zero effective weightnn this.clampWhenFinished = false; // keep feeding the last frame?nn this.zeroSlopeAtStart = true; // for smooth interpolation w/o separatenn this.zeroSlopeAtEnd = true; // clips for start, loop and endn}nnObject.assign(AnimationAction.prototype, {n // State & Schedulingn play: function play() {n this._mixer._activateAction(this);nn return this;n },n stop: function stop() {n this._mixer._deactivateAction(this);nn return this.reset();n },n reset: function reset() {n this.paused = false;n this.enabled = true;n this.time = 0; // restart clipnn this._loopCount = -1; // forget previous loopsnn this._startTime = null; // forget schedulingnn return this.stopFading().stopWarping();n },n isRunning: function isRunning() {n return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);n },n // return true when play has been calledn isScheduled: function isScheduled() {n return this._mixer._isActiveAction(this);n },n startAt: function startAt(time) {n this._startTime = time;n return this;n },n setLoop: function setLoop(mode, repetitions) {n this.loop = mode;n this.repetitions = repetitions;n return this;n },n // Weightn // set the weight stopping any scheduled fadingn // although .enabled = false yields an effective weight of zero, thisn // method does not change .enabled, because it would be confusingn setEffectiveWeight: function setEffectiveWeight(weight) {n this.weight = weight; // note: same logic as when updated at runtimenn this._effectiveWeight = this.enabled ? weight : 0;n return this.stopFading();n },n // return the weight considering fading and .enabledn getEffectiveWeight: function getEffectiveWeight() {n return this._effectiveWeight;n },n fadeIn: function fadeIn(duration) {n return this._scheduleFading(duration, 0, 1);n },n fadeOut: function fadeOut(duration) {n return this._scheduleFading(duration, 1, 0);n },n crossFadeFrom: function crossFadeFrom(fadeOutAction, duration, warp) {n fadeOutAction.fadeOut(duration);n this.fadeIn(duration);nn if (warp) {n var fadeInDuration = this._clip.duration,n fadeOutDuration = fadeOutAction._clip.duration,n startEndRatio = fadeOutDuration / fadeInDuration,n endStartRatio = fadeInDuration / fadeOutDuration;n fadeOutAction.warp(1.0, startEndRatio, duration);n this.warp(endStartRatio, 1.0, duration);n }nn return this;n },n crossFadeTo: function crossFadeTo(fadeInAction, duration, warp) {n return fadeInAction.crossFadeFrom(this, duration, warp);n },n stopFading: function stopFading() {n var weightInterpolant = this._weightInterpolant;nn if (weightInterpolant !== null) {n this._weightInterpolant = null;nn this._mixer._takeBackControlInterpolant(weightInterpolant);n }nn return this;n },n // Time Scale Controln // set the time scale stopping any scheduled warpingn // although .paused = true yields an effective time scale of zero, thisn // method does not change .paused, because it would be confusingn setEffectiveTimeScale: function setEffectiveTimeScale(timeScale) {n this.timeScale = timeScale;n this._effectiveTimeScale = this.paused ? 0 : timeScale;n return this.stopWarping();n },n // return the time scale considering warping and .pausedn getEffectiveTimeScale: function getEffectiveTimeScale() {n return this._effectiveTimeScale;n },n setDuration: function setDuration(duration) {n this.timeScale = this._clip.duration / duration;n return this.stopWarping();n },n syncWith: function syncWith(action) {n this.time = action.time;n this.timeScale = action.timeScale;n return this.stopWarping();n },n halt: function halt(duration) {n return this.warp(this._effectiveTimeScale, 0, duration);n },n warp: function warp(startTimeScale, endTimeScale, duration) {n var mixer = this._mixer,n now = mixer.time,n interpolant = this._timeScaleInterpolant,n timeScale = this.timeScale;nn if (interpolant === null) {n interpolant = mixer._lendControlInterpolant();n this._timeScaleInterpolant = interpolant;n }nn var times = interpolant.parameterPositions,n values = interpolant.sampleValues;n times = now;n times = now + duration;n values = startTimeScale / timeScale;n values = endTimeScale / timeScale;n return this;n },n stopWarping: function stopWarping() {n var timeScaleInterpolant = this._timeScaleInterpolant;nn if (timeScaleInterpolant !== null) {n this._timeScaleInterpolant = null;nn this._mixer._takeBackControlInterpolant(timeScaleInterpolant);n }nn return this;n },n // Object
Accessorsn getMixer: function getMixer() {n return this._mixer;n },n getClip: function getClip() {n return this._clip;n },n getRoot: function getRoot() {n return this._localRoot || this._mixer._root;n },n // Internan _update: function _update(time, deltaTime, timeDirection, accuIndex) {n // called by the mixern if (!this.enabled) {n // call ._updateWeight() to update ._effectiveWeightn this._updateWeight(time);nn return;n }nn var startTime = this._startTime;nn if (startTime !== null) {n // check for scheduled start of actionn var timeRunning = (time - startTime) * timeDirection;nn if (timeRunning < 0 || timeDirection === 0) {n return; // yet to come / don't decide when delta = 0n } // startnnn this._startTime = null; // unschedulenn deltaTime = timeDirection * timeRunning;n } // apply time scale and advance timennn deltaTime *= this._updateTimeScale(time);nn var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting inn // an effective weight of 0nnn var weight = this._updateWeight(time);nn if (weight > 0) {n var interpolants = this._interpolants;n var propertyMixers = this._propertyBindings;nn for (var j = 0, m = interpolants.length; j !== m; ++j) {n interpolants.evaluate(clipTime);n propertyMixers.accumulate(accuIndex, weight);n }n }n },n _updateWeight: function _updateWeight(time) {n var weight = 0;nn if (this.enabled) {n weight = this.weight;n var interpolant = this._weightInterpolant;nn if (interpolant !== null) {n var interpolantValue = interpolant.evaluate(time);n weight *= interpolantValue;nn if (time > interpolant.parameterPositions) {n this.stopFading();nn if (interpolantValue === 0) {n // faded out, disablen this.enabled = false;n }n }n }n }nn this._effectiveWeight = weight;n return weight;n },n _updateTimeScale: function _updateTimeScale(time) {n var timeScale = 0;nn if (!this.paused) {n timeScale = this.timeScale;n var interpolant = this._timeScaleInterpolant;nn if (interpolant !== null) {n var interpolantValue = interpolant.evaluate(time);n timeScale *= interpolantValue;nn if (time > interpolant.parameterPositions) {n this.stopWarping();nn if (timeScale === 0) {n // motion has halted, pausen this.paused = true;n } else {n // warp done - apply final time scalen this.timeScale = timeScale;n }n }n }n }nn this._effectiveTimeScale = timeScale;n return timeScale;n },n _updateTime: function _updateTime(deltaTime) {n var time = this.time + deltaTime;n var duration = this._clip.duration;n var loop = this.loop;n var loopCount = this._loopCount;n var pingPong = loop === LoopPingPong;nn if (deltaTime === 0) {n if (loopCount === -1) return time;n return pingPong && (loopCount & 1) === 1 ? duration - time : time;n }nn if (loop === LoopOnce) {n if (loopCount === -1) {n // just startedn this._loopCount = 0;nn this._setEndings(true, true, false);n }nn handle_stop: {n if (time >= duration) {n time = duration;n } else if (time < 0) {n time = 0;n } else {n this.time = time;n break handle_stop;n }nn if (this.clampWhenFinished) this.paused = true;else this.enabled = false;n this.time = time;nn this._mixer.dispatchEvent({n type: 'finished',n action: this,n direction: deltaTime < 0 ? -1 : 1n });n }n } else {n // repetitive Repeat or PingPongn if (loopCount === -1) {n // just startedn if (deltaTime >= 0) {n loopCount = 0;nn this._setEndings(true, this.repetitions === 0, pingPong);n } else {n // when looping in reverse direction, the initialn // transition through zero counts as a repetition,n // so leave loopCount at -1n this._setEndings(this.repetitions === 0, true, pingPong);n }n }nn if (time >= duration || time < 0) {n // wrap aroundn var loopDelta = Math.floor(time / duration); // signednn time -= duration * loopDelta;n loopCount += Math.abs(loopDelta);n var pending = this.repetitions - loopCount;nn if (pending <= 0) {n // have to stop (switch state, clamp time, fire event)n if (this.clampWhenFinished) this.paused = true;else this.enabled = false;n time = deltaTime > 0 ? duration : 0;n this.time = time;nn this._mixer.dispatchEvent({n type: 'finished',n action: this,n direction: deltaTime > 0 ? 1 : -1n });n } else {n // keep runningn if (pending === 1) {n // entering the last roundn var atStart = deltaTime < 0;nn this._setEndings(atStart, !atStart, pingPong);n } else {n this._setEndings(false, false, pingPong);n }nn this._loopCount = loopCount;n this.time = time;nn this._mixer.dispatchEvent({n type: 'loop',n action: this,n loopDelta: loopDeltan });n }n } else {n this.time = time;n }nn if (pingPong && (loopCount & 1) === 1) {n // invert time for the "pong round"n return duration - time;n }n }nn return time;n },n _setEndings: function _setEndings(atStart, atEnd, pingPong) {n var settings = this._interpolantSettings;nn if (pingPong) {n settings.endingStart = ZeroSlopeEnding;n settings.endingEnd = ZeroSlopeEnding;n } else {n // assuming for LoopOnce atStart == atEnd == truen if (atStart) {n settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;n } else {n settings.endingStart = WrapAroundEnding;n }nn if (atEnd) {n settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;n } else {n settings.endingEnd = WrapAroundEnding;n }n }n },n _scheduleFading: function _scheduleFading(duration, weightNow, weightThen) {n var mixer = this._mixer,n now = mixer.time,n interpolant = this._weightInterpolant;nn if (interpolant === null) {n interpolant = mixer._lendControlInterpolant();n this._weightInterpolant = interpolant;n }nn var times = interpolant.parameterPositions,n values = interpolant.sampleValues;n times = now;n values = weightNow;n times = now + duration;n values = weightThen;n return this;n }n});n/**n *n * Player for AnimationClips.n *n *n * @author Ben Houston / clara.io/n * @author David Sarno / lighthaus.us/n * @author tschwn */nnfunction AnimationMixer(root) {n this._root = root;nn this._initMemoryManager();nn this._accuIndex = 0;n this.time = 0;n this.timeScale = 1.0;n}nnAnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {n constructor: AnimationMixer,n _bindAction: function _bindAction(action, prototypeAction) {n var root = action._localRoot || this._root,n tracks = action._clip.tracks,n nTracks = tracks.length,n bindings = action._propertyBindings,n interpolants = action._interpolants,n rootUuid = root.uuid,n bindingsByRoot = this._bindingsByRootAndName,n bindingsByName = bindingsByRoot;nn if (bindingsByName === undefined) {n bindingsByName = {};n bindingsByRoot = bindingsByName;n }nn for (var i = 0; i !== nTracks; ++i) {n var track = tracks,n trackName = track.name,n binding = bindingsByName;nn if (binding !== undefined) {n bindings = binding;n } else {n binding = bindings;nn if (binding !== undefined) {n // existing binding, make sure the cache knowsn if (binding._cacheIndex === null) {n ++binding.referenceCount;nn this._addInactiveBinding(binding, rootUuid, trackName);n }nn continue;n }nn var path = prototypeAction && prototypeAction._propertyBindings.binding.parsedPath;n binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());n ++binding.referenceCount;nn this._addInactiveBinding(binding, rootUuid, trackName);nn bindings = binding;n }nn interpolants.resultBuffer = binding.buffer;n }n },n _activateAction: function _activateAction(action) {n if (!this._isActiveAction(action)) {n if (action._cacheIndex === null) {n // this action has been forgotten by the cache, but the usern // appears to be still using it -> rebindn var rootUuid = (action._localRoot || this._root).uuid,n clipUuid = action._clip.uuid,n actionsForClip = this._actionsByClip;nn this._bindAction(action, actionsForClip && actionsForClip.knownActions);nn this._addInactiveAction(action, clipUuid, rootUuid);n }nn var bindings = action._propertyBindings; // increment reference counts / sort out statenn for (var i = 0, n = bindings.length; i !== n; ++i) {n var binding = bindings;nn if (binding.useCount++ === 0) {n this._lendBinding(binding);nn binding.saveOriginalState();n }n }nn this._lendAction(action);n }n },n _deactivateAction: function _deactivateAction(action) {n if (this._isActiveAction(action)) {n var bindings = action._propertyBindings; // decrement reference counts / sort out statenn for (var i = 0, n = bindings.length; i !== n; ++i) {n var binding = bindings;nn if (–binding.useCount === 0) {n binding.restoreOriginalState();nn this._takeBackBinding(binding);n }n }nn this._takeBackAction(action);n }n },n // Memory managern _initMemoryManager: function _initMemoryManager() {n this._actions = []; // 'nActiveActions' followed by inactive onesnn this._nActiveActions = 0;n this._actionsByClip = {}; // inside:n // {n // tknownActions: Array< AnimationAction > - used as prototypesn // tactionByRoot: AnimationAction - lookupn // }nn this._bindings = []; // 'nActiveBindings' followed by inactive onesnn this._nActiveBindings = 0;n this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >nn this._controlInterpolants = []; // same game as abovenn this._nActiveControlInterpolants = 0;n var scope = this;n this.stats = {n actions: {n get total() {n return scope._actions.length;n },nn get inUse() {n return scope._nActiveActions;n }nn },n bindings: {n get total() {n return scope._bindings.length;n },nn get inUse() {n return scope._nActiveBindings;n }nn },n controlInterpolants: {n get total() {n return scope._controlInterpolants.length;n },nn get inUse() {n return scope._nActiveControlInterpolants;n }nn }n };n },n // Memory management for AnimationAction objectsn _isActiveAction: function _isActiveAction(action) {n var index = action._cacheIndex;n return index !== null && index < this._nActiveActions;n },n _addInactiveAction: function _addInactiveAction(action, clipUuid, rootUuid) {n var actions = this._actions,n actionsByClip = this._actionsByClip,n actionsForClip = actionsByClip;nn if (actionsForClip === undefined) {n actionsForClip = {n knownActions: [action],n actionByRoot: {}n };n action._byClipCacheIndex = 0;n actionsByClip = actionsForClip;n } else {n var knownActions = actionsForClip.knownActions;n action._byClipCacheIndex = knownActions.length;n knownActions.push(action);n }nn action._cacheIndex = actions.length;n actions.push(action);n actionsForClip.actionByRoot = action;n },n _removeInactiveAction: function _removeInactiveAction(action) {n var actions = this._actions,n lastInactiveAction = actions[actions.length - 1],n cacheIndex = action._cacheIndex;n lastInactiveAction._cacheIndex = cacheIndex;n actions = lastInactiveAction;n actions.pop();n action._cacheIndex = null;n var clipUuid = action._clip.uuid,n actionsByClip = this._actionsByClip,n actionsForClip = actionsByClip,n knownActionsForClip = actionsForClip.knownActions,n lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],n byClipCacheIndex = action._byClipCacheIndex;n lastKnownAction._byClipCacheIndex = byClipCacheIndex;n knownActionsForClip = lastKnownAction;n knownActionsForClip.pop();n action._byClipCacheIndex = null;n var actionByRoot = actionsForClip.actionByRoot,n rootUuid = (action._localRoot || this._root).uuid;n delete actionByRoot;nn if (knownActionsForClip.length === 0) {n delete actionsByClip;n }nn this._removeInactiveBindingsForAction(action);n },n _removeInactiveBindingsForAction: function _removeInactiveBindingsForAction(action) {n var bindings = action._propertyBindings;nn for (var i = 0, n = bindings.length; i !== n; ++i) {n var binding = bindings;nn if (–binding.referenceCount === 0) {n this._removeInactiveBinding(binding);n }n }n },n _lendAction: function _lendAction(action) {n // [ active actions | inactive actions ]n // [ active actions >| inactive actions ]n // s an // <-swap->n // a sn var actions = this._actions,n prevIndex = action._cacheIndex,n lastActiveIndex = this._nActiveActions++,n firstInactiveAction = actions;n action._cacheIndex = lastActiveIndex;n actions = action;n firstInactiveAction._cacheIndex = prevIndex;n actions = firstInactiveAction;n },n _takeBackAction: function _takeBackAction(action) {n // [ active actions | inactive actions ]n // [ active actions |< inactive actions ]n // a sn // <-swap->n // s an var actions = this._actions,n prevIndex = action._cacheIndex,n firstInactiveIndex = –this._nActiveActions,n lastActiveAction = actions;n action._cacheIndex = firstInactiveIndex;n actions = action;n lastActiveAction._cacheIndex = prevIndex;n actions = lastActiveAction;n },n // Memory management for PropertyMixer objectsn _addInactiveBinding: function _addInactiveBinding(binding, rootUuid, trackName) {n var bindingsByRoot = this._bindingsByRootAndName,n bindingByName = bindingsByRoot,n bindings = this._bindings;nn if (bindingByName === undefined) {n bindingByName = {};n bindingsByRoot = bindingByName;n }nn bindingByName = binding;n binding._cacheIndex = bindings.length;n bindings.push(binding);n },n _removeInactiveBinding: function _removeInactiveBinding(binding) {n var bindings = this._bindings,n propBinding = binding.binding,n rootUuid = propBinding.rootNode.uuid,n trackName = propBinding.path,n bindingsByRoot = this._bindingsByRootAndName,n bindingByName = bindingsByRoot,n lastInactiveBinding = bindings[bindings.length - 1],n cacheIndex = binding._cacheIndex;n lastInactiveBinding._cacheIndex = cacheIndex;n bindings = lastInactiveBinding;n bindings.pop();n delete bindingByName;nn if (Object.keys(bindingByName).length === 0) {n delete bindingsByRoot;n }n },n _lendBinding: function _lendBinding(binding) {n var bindings = this._bindings,n prevIndex = binding._cacheIndex,n lastActiveIndex = this._nActiveBindings++,n firstInactiveBinding = bindings;n binding._cacheIndex = lastActiveIndex;n bindings = binding;n firstInactiveBinding._cacheIndex = prevIndex;n bindings = firstInactiveBinding;n },n _takeBackBinding: function _takeBackBinding(binding) {n var bindings = this._bindings,n prevIndex = binding._cacheIndex,n firstInactiveIndex = –this._nActiveBindings,n lastActiveBinding = bindings;n binding._cacheIndex = firstInactiveIndex;n bindings = binding;n lastActiveBinding._cacheIndex = prevIndex;n bindings = lastActiveBinding;n },n // Memory management of Interpolants for weight and time scalen _lendControlInterpolant: function _lendControlInterpolant() {n var interpolants = this._controlInterpolants,n lastActiveIndex = this._nActiveControlInterpolants++,n interpolant = interpolants;nn if (interpolant === undefined) {n interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);n interpolant.__cacheIndex = lastActiveIndex;n interpolants = interpolant;n }nn return interpolant;n },n _takeBackControlInterpolant: function _takeBackControlInterpolant(interpolant) {n var interpolants = this._controlInterpolants,n prevIndex = interpolant.__cacheIndex,n firstInactiveIndex = –this._nActiveControlInterpolants,n lastActiveInterpolant = interpolants;n interpolant.__cacheIndex = firstInactiveIndex;n interpolants = interpolant;n lastActiveInterpolant.__cacheIndex = prevIndex;n interpolants = lastActiveInterpolant;n },n _controlInterpolantsResultBuffer: new Float32Array(1),n // return an action for a clip optionally using a custom root targetn // object (this method allocates a lot of dynamic memory in case an // previously unknown clip/root combination is specified)n clipAction: function clipAction(clip, optionalRoot) {n var root = optionalRoot || this._root,n rootUuid = root.uuid,n clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,n clipUuid = clipObject !== null ? clipObject.uuid : clip,n actionsForClip = this._actionsByClip,n prototypeAction = null;nn if (actionsForClip !== undefined) {n var existingAction = actionsForClip.actionByRoot;nn if (existingAction !== undefined) {n return existingAction;n } // we know the clip, so we don't have to parse alln // the bindings again but can just copynnn prototypeAction = actionsForClip.knownActions; // also, take the clip from the prototype actionnn if (clipObject === null) clipObject = prototypeAction._clip;n } // clip must be known when specified via stringnnn if (clipObject === null) return null; // allocate all resources required to run itnn var newAction = new AnimationAction(this, clipObject, optionalRoot);nn this._bindAction(newAction, prototypeAction); // and make the action known to the memory managernnn this._addInactiveAction(newAction, clipUuid, rootUuid);nn return newAction;n },n // get an existing actionn existingAction: function existingAction(clip, optionalRoot) {n var root = optionalRoot || this._root,n rootUuid = root.uuid,n clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,n clipUuid = clipObject ? clipObject.uuid : clip,n actionsForClip = this._actionsByClip;nn if (actionsForClip !== undefined) {n return actionsForClip.actionByRoot || null;n }nn return null;n },n // deactivates all previously scheduled actionsn stopAllAction: function stopAllAction() {n var actions = this._actions,n nActions = this._nActiveActions,n bindings = this._bindings,n nBindings = this._nActiveBindings;n this._nActiveActions = 0;n this._nActiveBindings = 0;nn for (var i = 0; i !== nActions; ++i) {n actions.reset();n }nn for (var i = 0; i !== nBindings; ++i) {n bindings.useCount = 0;n }nn return this;n },n // advance the time and update apply the animationn update: function update(deltaTime) {n deltaTime *= this.timeScale;n var actions = this._actions,n nActions = this._nActiveActions,n time = this.time += deltaTime,n timeDirection = Math.sign(deltaTime),n accuIndex = this._accuIndex ^= 1; // run active actionsnn for (var i = 0; i !== nActions; ++i) {n var action = actions;nn action._update(time, deltaTime, timeDirection, accuIndex);n } // update scene graphnnn var bindings = this._bindings,n nBindings = this._nActiveBindings;nn for (var i = 0; i !== nBindings; ++i) {n bindings.apply(accuIndex);n }nn return this;n },n // return this mixer's root target objectn getRoot: function getRoot() {n return this._root;n },n // free all resources specific to a particular clipn uncacheClip: function uncacheClip(clip) {n var actions = this._actions,n clipUuid = clip.uuid,n actionsByClip = this._actionsByClip,n actionsForClip = actionsByClip;nn if (actionsForClip !== undefined) {n // note: just calling _removeInactiveAction would mess up then // iteration state and also require updating the state we cann // just throw awayn var actionsToRemove = actionsForClip.knownActions;nn for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {n var action = actionsToRemove;nn this._deactivateAction(action);nn var cacheIndex = action._cacheIndex,n lastInactiveAction = actions[actions.length - 1];n action._cacheIndex = null;n action._byClipCacheIndex = null;n lastInactiveAction._cacheIndex = cacheIndex;n actions = lastInactiveAction;n actions.pop();nn this._removeInactiveBindingsForAction(action);n }nn delete actionsByClip;n }n },n // free all resources specific to a particular root target objectn uncacheRoot: function uncacheRoot(root) {n var rootUuid = root.uuid,n actionsByClip = this._actionsByClip;nn for (var clipUuid in actionsByClip) {n var actionByRoot = actionsByClip.actionByRoot,n action = actionByRoot;nn if (action !== undefined) {n this._deactivateAction(action);nn this._removeInactiveAction(action);n }n }nn var bindingsByRoot = this._bindingsByRootAndName,n bindingByName = bindingsByRoot;nn if (bindingByName !== undefined) {n for (var trackName in bindingByName) {n var binding = bindingByName;n binding.restoreOriginalState();nn this._removeInactiveBinding(binding);n }n }n },n // remove a targeted clip from the cachen uncacheAction: function uncacheAction(clip, optionalRoot) {n var action = this.existingAction(clip, optionalRoot);nn if (action !== null) {n this._deactivateAction(action);nn this._removeInactiveAction(action);n }n }n});n/**n * @author mrdoob / mrdoob.com/n */nnfunction Uniform(value) {n if (typeof value === 'string') {n console.warn('THREE.Uniform: Type
parameter is no longer needed.');n value = arguments;n }nn this.value = value;n}nnUniform.prototype.clone = function () {n return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());n};n/**n * @author benaadams / twitter.com/ben_a_adamsn */nnnfunction InstancedInterleavedBuffer(array, stride, meshPerAttribute) {n InterleavedBuffer.call(this, array, stride);n this.meshPerAttribute = meshPerAttribute || 1;n}nnInstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {n constructor: InstancedInterleavedBuffer,n isInstancedInterleavedBuffer: true,n copy: function copy(source) {n InterleavedBuffer.prototype.copy.call(this, source);n this.meshPerAttribute = source.meshPerAttribute;n return this;n }n});n/**n * @author mrdoob / mrdoob.com/n * @author bhouston / clara.io/n * @author stephomi / stephaneginier.com/n */nnfunction Raycaster(origin, direction, near, far) {n this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)nn this.near = near || 0;n this.far = far || Infinity;n this.camera = null;n this.params = {n Mesh: {},n Line: {},n LOD: {},n Points: {n threshold: 1n },n Sprite: {}n };n Object.defineProperties(this.params, {n PointCloud: {n get: function get() {n console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');n return this.Points;n }n }n });n}nnfunction ascSort(a, b) {n return a.distance - b.distance;n}nnfunction _intersectObject(object, raycaster, intersects, recursive) {n if (object.visible === false) return;n object.raycast(raycaster, intersects);nn if (recursive === true) {n var children = object.children;nn for (var i = 0, l = children.length; i < l; i++) {n _intersectObject(children, raycaster, intersects, true);n }n }n}nnObject.assign(Raycaster.prototype, {n linePrecision: 1,n set: function set(origin, direction) {n // direction is assumed to be normalized (for accurate distance calculations)n this.ray.set(origin, direction);n },n setFromCamera: function setFromCamera(coords, camera) {n if (camera && camera.isPerspectiveCamera) {n this.ray.origin.setFromMatrixPosition(camera.matrixWorld);n this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();n this.camera = camera;n } else if (camera && camera.isOrthographicCamera) {n this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camerann this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);n this.camera = camera;n } else {n console.error('THREE.Raycaster: Unsupported camera type.');n }n },n intersectObject: function intersectObject(object, recursive, optionalTarget) {n var intersects = optionalTarget || [];nn _intersectObject(object, this, intersects, recursive);nn intersects.sort(ascSort);n return intersects;n },n intersectObjects: function intersectObjects(objects, recursive, optionalTarget) {n var intersects = optionalTarget || [];nn if (Array.isArray(objects) === false) {n console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');n return intersects;n }nn for (var i = 0, l = objects.length; i < l; i++) {n _intersectObject(objects, this, intersects, recursive);n }nn intersects.sort(ascSort);n return intersects;n }n});n/**n * @author bhouston / clara.ion * @author WestLangley / github.com/WestLangleyn *n * Ref: en.wikipedia.org/wiki/Spherical_coordinate_systemn *n * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.n * The azimuthal angle (theta) is measured from the positive z-axiz.n */nnfunction Spherical(radius, phi, theta) {n this.radius = radius !== undefined ? radius : 1.0;n this.phi = phi !== undefined ? phi : 0; // polar anglenn this.theta = theta !== undefined ? theta : 0; // azimuthal anglenn return this;n}nnObject.assign(Spherical.prototype, {n set: function set(radius, phi, theta) {n this.radius = radius;n this.phi = phi;n this.theta = theta;n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(other) {n this.radius = other.radius;n this.phi = other.phi;n this.theta = other.theta;n return this;n },n // restrict phi to be betwee EPS and PI-EPSn makeSafe: function makeSafe() {n var EPS = 0.000001;n this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));n return this;n },n setFromVector3: function setFromVector3(v) {n return this.setFromCartesianCoords(v.x, v.y, v.z);n },n setFromCartesianCoords: function setFromCartesianCoords(x, y, z) {n this.radius = Math.sqrt(x * x + y * y + z * z);nn if (this.radius === 0) {n this.theta = 0;n this.phi = 0;n } else {n this.theta = Math.atan2(x, z);n this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));n }nn return this;n }n});n/**n * @author Mugen87 / github.com/Mugen87n *n * Ref: en.wikipedia.org/wiki/Cylindrical_coordinate_systemn *n */nnfunction Cylindrical(radius, theta, y) {n this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z planenn this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axisnn this.y = y !== undefined ? y : 0; // height above the x-z planenn return this;n}nnObject.assign(Cylindrical.prototype, {n set: function set(radius, theta, y) {n this.radius = radius;n this.theta = theta;n this.y = y;n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(other) {n this.radius = other.radius;n this.theta = other.theta;n this.y = other.y;n return this;n },n setFromVector3: function setFromVector3(v) {n return this.setFromCartesianCoords(v.x, v.y, v.z);n },n setFromCartesianCoords: function setFromCartesianCoords(x, y, z) {n this.radius = Math.sqrt(x * x + z * z);n this.theta = Math.atan2(x, z);n this.y = y;n return this;n }n});n/**n * @author bhouston / clara.ion */nnvar _vector$6 = new Vector2();nnfunction Box2(min, max) {n this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);n this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);n}nnObject.assign(Box2.prototype, {n set: function set(min, max) {n this.min.copy(min);n this.max.copy(max);n return this;n },n setFromPoints: function setFromPoints(points) {n this.makeEmpty();nn for (var i = 0, il = points.length; i < il; i++) {n this.expandByPoint(points);n }nn return this;n },n setFromCenterAndSize: function setFromCenterAndSize(center, size) {n var halfSize = _vector$6.copy(size).multiplyScalar(0.5);nn this.min.copy(center).sub(halfSize);n this.max.copy(center).add(halfSize);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(box) {n this.min.copy(box.min);n this.max.copy(box.max);n return this;n },n makeEmpty: function makeEmpty() {n this.min.x = this.min.y = +Infinity;n this.max.x = this.max.y = -Infinity;n return this;n },n isEmpty: function isEmpty() {n // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axesn return this.max.x < this.min.x || this.max.y < this.min.y;n },n getCenter: function getCenter(target) {n if (target === undefined) {n console.warn('THREE.Box2: .getCenter() target is now required');n target = new Vector2();n }nn return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);n },n getSize: function getSize(target) {n if (target === undefined) {n console.warn('THREE.Box2: .getSize() target is now required');n target = new Vector2();n }nn return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);n },n expandByPoint: function expandByPoint(point) {n this.min.min(point);n this.max.max(point);n return this;n },n expandByVector: function expandByVector(vector) {n this.min.sub(vector);n this.max.add(vector);n return this;n },n expandByScalar: function expandByScalar(scalar) {n this.min.addScalar(-scalar);n this.max.addScalar(scalar);n return this;n },n containsPoint: function containsPoint(point) {n return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;n },n containsBox: function containsBox(box) {n 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;n },n getParameter: function getParameter(point, target) {n // This can potentially have a divide by zero if the boxn // has a size dimension of 0.n if (target === undefined) {n console.warn('THREE.Box2: .getParameter() target is now required');n target = new Vector2();n }nn 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));n },n intersectsBox: function intersectsBox(box) {n // using 4 splitting planes to rule out intersectionsn 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;n },n clampPoint: function clampPoint(point, target) {n if (target === undefined) {n console.warn('THREE.Box2: .clampPoint() target is now required');n target = new Vector2();n }nn return target.copy(point).clamp(this.min, this.max);n },n distanceToPoint: function distanceToPoint(point) {n var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);nn return clampedPoint.sub(point).length();n },n intersect: function intersect(box) {n this.min.max(box.min);n this.max.min(box.max);n return this;n },n union: function union(box) {n this.min.min(box.min);n this.max.max(box.max);n return this;n },n translate: function translate(offset) {n this.min.add(offset);n this.max.add(offset);n return this;n },n equals: function equals(box) {n return box.min.equals(this.min) && box.max.equals(this.max);n }n});n/**n * @author bhouston / clara.ion */nnvar _startP = new Vector3();nnvar _startEnd = new Vector3();nnfunction Line3(start, end) {n this.start = start !== undefined ? start : new Vector3();n this.end = end !== undefined ? end : new Vector3();n}nnObject.assign(Line3.prototype, {n set: function set(start, end) {n this.start.copy(start);n this.end.copy(end);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n },n copy: function copy(line) {n this.start.copy(line.start);n this.end.copy(line.end);n return this;n },n getCenter: function getCenter(target) {n if (target === undefined) {n console.warn('THREE.Line3: .getCenter() target is now required');n target = new Vector3();n }nn return target.addVectors(this.start, this.end).multiplyScalar(0.5);n },n delta: function delta(target) {n if (target === undefined) {n console.warn('THREE.Line3: .delta() target is now required');n target = new Vector3();n }nn return target.subVectors(this.end, this.start);n },n distanceSq: function distanceSq() {n return this.start.distanceToSquared(this.end);n },n distance: function distance() {n return this.start.distanceTo(this.end);n },n at: function at(t, target) {n if (target === undefined) {n console.warn('THREE.Line3: .at() target is now required');n target = new Vector3();n }nn return this.delta(target).multiplyScalar(t).add(this.start);n },n closestPointToPointParameter: function closestPointToPointParameter(point, clampToLine) {n _startP.subVectors(point, this.start);nn _startEnd.subVectors(this.end, this.start);nn var startEnd2 = _startEnd.dot(_startEnd);nn var startEnd_startP = _startEnd.dot(_startP);nn var t = startEnd_startP / startEnd2;nn if (clampToLine) {n t = _Math.clamp(t, 0, 1);n }nn return t;n },n closestPointToPoint: function closestPointToPoint(point, clampToLine, target) {n var t = this.closestPointToPointParameter(point, clampToLine);nn if (target === undefined) {n console.warn('THREE.Line3: .closestPointToPoint() target is now required');n target = new Vector3();n }nn return this.delta(target).multiplyScalar(t).add(this.start);n },n applyMatrix4: function applyMatrix4(matrix) {n this.start.applyMatrix4(matrix);n this.end.applyMatrix4(matrix);n return this;n },n equals: function equals(line) {n return line.start.equals(this.start) && line.end.equals(this.end);n }n});n/**n * @author alteredq / alteredqualia.com/n */nnfunction ImmediateRenderObject(material) {n Object3D.call(this);n this.material = material;nn this.render = function ()n /* renderCallback */n {};n}nnImmediateRenderObject.prototype = Object.create(Object3D.prototype);nImmediateRenderObject.prototype.constructor = ImmediateRenderObject;nImmediateRenderObject.prototype.isImmediateRenderObject = true;n/**n * @author mrdoob / mrdoob.com/n * @author WestLangley / github.com/WestLangleyn */nnvar _v1$5 = new Vector3();nnvar _v2$3 = new Vector3();nnvar _normalMatrix$1 = new Matrix3();nnvar _keys = ['a', 'b', 'c'];nnfunction VertexNormalsHelper(object, size, hex, linewidth) {n this.object = object;n this.size = size !== undefined ? size : 1;n var color = hex !== undefined ? hex : 0xff0000;n var width = linewidth !== undefined ? linewidth : 1; //nn var nNormals = 0;n var objGeometry = this.object.geometry;nn if (objGeometry && objGeometry.isGeometry) {n nNormals = objGeometry.faces.length * 3;n } else if (objGeometry && objGeometry.isBufferGeometry) {n nNormals = objGeometry.attributes.normal.count;n } //nnn var geometry = new BufferGeometry();n var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);n geometry.addAttribute('position', positions);n LineSegments.call(this, geometry, new LineBasicMaterial({n color: color,n linewidth: widthn })); //nn this.matrixAutoUpdate = false;n this.update();n}nnVertexNormalsHelper.prototype = Object.create(LineSegments.prototype);nVertexNormalsHelper.prototype.constructor = VertexNormalsHelper;nnVertexNormalsHelper.prototype.update = function () {n this.object.updateMatrixWorld(true);nn _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);nn var matrixWorld = this.object.matrixWorld;n var position = this.geometry.attributes.position; //nn var objGeometry = this.object.geometry;nn if (objGeometry && objGeometry.isGeometry) {n var vertices = objGeometry.vertices;n var faces = objGeometry.faces;n var idx = 0;nn for (var i = 0, l = faces.length; i < l; i++) {n var face = faces;nn for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {n var vertex = vertices[face[_keys]];n var normal = face.vertexNormals;nn _v1$5.copy(vertex).applyMatrix4(matrixWorld);nn _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);nn position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);n idx = idx + 1;n position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);n idx = idx + 1;n }n }n } else if (objGeometry && objGeometry.isBufferGeometry) {n var objPos = objGeometry.attributes.position;n var objNorm = objGeometry.attributes.normal;n var idx = 0; // for simplicity, ignore index and drawcalls, and render every normalnn for (var j = 0, jl = objPos.count; j < jl; j++) {n _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);nn _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));nn _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);nn position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);n idx = idx + 1;n position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);n idx = idx + 1;n }n }nn position.needsUpdate = true;n};n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n * @author WestLangley / github.com/WestLangleyn */nnnvar _vector$7 = new Vector3();nnfunction SpotLightHelper(light, color) {n Object3D.call(this);n this.light = light;n this.light.updateMatrixWorld();n this.matrix = light.matrixWorld;n this.matrixAutoUpdate = false;n this.color = color;n var geometry = new BufferGeometry();n var positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];nn for (var i = 0, j = 1, l = 32; i < l; i++, j++) {n var p1 = i / l * Math.PI * 2;n var p2 = j / l * Math.PI * 2;n positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);n }nn geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));n var material = new LineBasicMaterial({n fog: falsen });n this.cone = new LineSegments(geometry, material);n this.add(this.cone);n this.update();n}nnSpotLightHelper.prototype = Object.create(Object3D.prototype);nSpotLightHelper.prototype.constructor = SpotLightHelper;nnSpotLightHelper.prototype.dispose = function () {n this.cone.geometry.dispose();n this.cone.material.dispose();n};nnSpotLightHelper.prototype.update = function () {n this.light.updateMatrixWorld();n var coneLength = this.light.distance ? this.light.distance : 1000;n var coneWidth = coneLength * Math.tan(this.light.angle);n this.cone.scale.set(coneWidth, coneWidth, coneLength);nn _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);nn this.cone.lookAt(_vector$7);nn if (this.color !== undefined) {n this.cone.material.color.set(this.color);n } else {n this.cone.material.color.copy(this.light.color);n }n};n/**n * @author Sean Griffin / twitter.com/sgrifn * @author Michael Guerrero / realitymeltdown.comn * @author mrdoob / mrdoob.com/n * @author ikerr / verold.comn * @author Mugen87 / github.com/Mugen87n */nnnvar _vector$8 = new Vector3();nnvar _boneMatrix = new Matrix4();nnvar _matrixWorldInv = new Matrix4();nnfunction getBoneList(object) {n var boneList = [];nn if (object && object.isBone) {n boneList.push(object);n }nn for (var i = 0; i < object.children.length; i++) {n boneList.push.apply(boneList, getBoneList(object.children));n }nn return boneList;n}nnfunction SkeletonHelper(object) {n var bones = getBoneList(object);n var geometry = new BufferGeometry();n var vertices = [];n var colors = [];n var color1 = new Color(0, 0, 1);n var color2 = new Color(0, 1, 0);nn for (var i = 0; i < bones.length; i++) {n var bone = bones;nn if (bone.parent && bone.parent.isBone) {n vertices.push(0, 0, 0);n vertices.push(0, 0, 0);n colors.push(color1.r, color1.g, color1.b);n colors.push(color2.r, color2.g, color2.b);n }n }nn geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));n geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));n var material = new LineBasicMaterial({n vertexColors: VertexColors,n depthTest: false,n depthWrite: false,n transparent: truen });n LineSegments.call(this, geometry, material);n this.root = object;n this.bones = bones;n this.matrix = object.matrixWorld;n this.matrixAutoUpdate = false;n}nnSkeletonHelper.prototype = Object.create(LineSegments.prototype);nSkeletonHelper.prototype.constructor = SkeletonHelper;nnSkeletonHelper.prototype.updateMatrixWorld = function (force) {n var bones = this.bones;n var geometry = this.geometry;n var position = geometry.getAttribute('position');nn _matrixWorldInv.getInverse(this.root.matrixWorld);nn for (var i = 0, j = 0; i < bones.length; i++) {n var bone = bones;nn if (bone.parent && bone.parent.isBone) {n _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);nn _vector$8.setFromMatrixPosition(_boneMatrix);nn position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);nn _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);nn _vector$8.setFromMatrixPosition(_boneMatrix);nn position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);n j += 2;n }n }nn geometry.getAttribute('position').needsUpdate = true;n Object3D.prototype.updateMatrixWorld.call(this, force);n};n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n */nnnfunction PointLightHelper(light, sphereSize, color) {n this.light = light;n this.light.updateMatrixWorld();n this.color = color;n var geometry = new SphereBufferGeometry(sphereSize, 4, 2);n var material = new MeshBasicMaterial({n wireframe: true,n fog: falsen });n Mesh.call(this, geometry, material);n this.matrix = this.light.matrixWorld;n this.matrixAutoUpdate = false;n this.update();n /*n var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );n var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );n tthis.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );n this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );n tvar d = light.distance;n tif ( d === 0.0 ) {n ttthis.lightDistance.visible = false;n t} else {n ttthis.lightDistance.scale.set( d, d, d );n t}n tthis.add( this.lightDistance );n */n}nnPointLightHelper.prototype = Object.create(Mesh.prototype);nPointLightHelper.prototype.constructor = PointLightHelper;nnPointLightHelper.prototype.dispose = function () {n this.geometry.dispose();n this.material.dispose();n};nnPointLightHelper.prototype.update = function () {n if (this.color !== undefined) {n this.material.color.set(this.color);n } else {n this.material.color.copy(this.light.color);n }n /*n var d = this.light.distance;n tif ( d === 0.0 ) {n ttthis.lightDistance.visible = false;n t} else {n ttthis.lightDistance.visible = true;n tthis.lightDistance.scale.set( d, d, d );n t}n */nn};n/**n * @author abelnation / github.com/abelnationn * @author Mugen87 / github.com/Mugen87n * @author WestLangley / github.com/WestLangleyn *n * This helper must be added as a child of the lightn */nnnfunction RectAreaLightHelper(light, color) {n this.type = 'RectAreaLightHelper';n this.light = light;n this.color = color; // optional hardwired color for the helpernn var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];n var geometry = new BufferGeometry();n geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));n geometry.computeBoundingSphere();n var material = new LineBasicMaterial({n fog: falsen });n Line.call(this, geometry, material); //nn var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];n var geometry2 = new BufferGeometry();n geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));n geometry2.computeBoundingSphere();n this.add(new Mesh(geometry2, new MeshBasicMaterial({n side: BackSide,n fog: falsen })));n this.update();n}nnRectAreaLightHelper.prototype = Object.create(Line.prototype);nRectAreaLightHelper.prototype.constructor = RectAreaLightHelper;nnRectAreaLightHelper.prototype.update = function () {n this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);nn if (this.color !== undefined) {n this.material.color.set(this.color);n this.children.material.color.set(this.color);n } else {n this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shiftnn var c = this.material.color;n var max = Math.max(c.r, c.g, c.b);n if (max > 1) c.multiplyScalar(1 / max);n this.children.material.color.copy(this.material.color);n }n};nnRectAreaLightHelper.prototype.dispose = function () {n this.geometry.dispose();n this.material.dispose();n this.children.geometry.dispose();n this.children.material.dispose();n};n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n */nnnvar _vector$9 = new Vector3();nnvar _color1 = new Color();nnvar _color2 = new Color();nnfunction HemisphereLightHelper(light, size, color) {n Object3D.call(this);n this.light = light;n this.light.updateMatrixWorld();n this.matrix = light.matrixWorld;n this.matrixAutoUpdate = false;n this.color = color;n var geometry = new OctahedronBufferGeometry(size);n geometry.rotateY(Math.PI * 0.5);n this.material = new MeshBasicMaterial({n wireframe: true,n fog: falsen });n if (this.color === undefined) this.material.vertexColors = VertexColors;n var position = geometry.getAttribute('position');n var colors = new Float32Array(position.count * 3);n geometry.addAttribute('color', new BufferAttribute(colors, 3));n this.add(new Mesh(geometry, this.material));n this.update();n}nnHemisphereLightHelper.prototype = Object.create(Object3D.prototype);nHemisphereLightHelper.prototype.constructor = HemisphereLightHelper;nnHemisphereLightHelper.prototype.dispose = function () {n this.children.geometry.dispose();n this.children.material.dispose();n};nnHemisphereLightHelper.prototype.update = function () {n var mesh = this.children;nn if (this.color !== undefined) {n this.material.color.set(this.color);n } else {n var colors = mesh.geometry.getAttribute('color');nn _color1.copy(this.light.color);nn _color2.copy(this.light.groundColor);nn for (var i = 0, l = colors.count; i < l; i++) {n var color = i < l / 2 ? _color1 : _color2;n colors.setXYZ(i, color.r, color.g, color.b);n }nn colors.needsUpdate = true;n }nn mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());n};n/**n * @author WestLangley / github.com/WestLangleyn */nnnfunction LightProbeHelper(lightProbe, size) {n this.lightProbe = lightProbe;n this.size = size;n var defines = {};n defines = ""; // materialnn var material = new ShaderMaterial({n defines: defines,n uniforms: {n sh: {n value: this.lightProbe.sh.coefficientsn },n // by referencen intensity: {n value: this.lightProbe.intensityn }n },n vertexShader: ['varying vec3 vNormal;', 'void main() {', 'tvNormal = normalize( normalMatrix * normal );', 'tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),n fragmentShader: ['#define RECIPROCAL_PI 0.318309886', 'vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {', 't// matrix is assumed to be orthogonal', 'treturn normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );', '}', 'vec3 linearToOutput( in vec3 a ) {', 't#ifdef GAMMA_OUTPUT', 'ttreturn pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );', 't#else', 'ttreturn a;', 't#endif', '}', '// source: graphics.stanford.edu/papers/envmap/envmap.pdf', 'vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {', 't// normal is assumed to have unit length', 'tfloat x = normal.x, y = normal.y, z = normal.z;', 't// band 0', 'tvec3 result = shCoefficients[ 0 ] * 0.886227;', 't// band 1', 'tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;', 'tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;', 'tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;', 't// band 2', 'tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;', 'tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;', 'tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );', 'tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;', 'tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );', 'treturn result;', '}', 'uniform vec3 sh[ 9 ]; // sh coefficients', 'uniform float intensity; // light probe intensity', 'varying vec3 vNormal;', 'void main() {', 'tvec3 normal = normalize( vNormal );', 'tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );', 'tvec3 irradiance = shGetIrradianceAt( worldNormal, sh );', 'tvec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;', 'toutgoingLight = linearToOutput( outgoingLight );', 'tgl_FragColor = vec4( outgoingLight, 1.0 );', '}'].join('\n')n });n var geometry = new SphereBufferGeometry(1, 32, 16);n Mesh.call(this, geometry, material);n this.onBeforeRender();n}nnLightProbeHelper.prototype = Object.create(Mesh.prototype);nLightProbeHelper.prototype.constructor = LightProbeHelper;nnLightProbeHelper.prototype.dispose = function () {n this.geometry.dispose();n this.material.dispose();n};nnLightProbeHelper.prototype.onBeforeRender = function () {n this.position.copy(this.lightProbe.position);n this.scale.set(1, 1, 1).multiplyScalar(this.size);n this.material.uniforms.intensity.value = this.lightProbe.intensity;n};n/**n * @author mrdoob / mrdoob.com/n */nnnfunction GridHelper(size, divisions, color1, color2) {n size = size || 10;n divisions = divisions || 10;n color1 = new Color(color1 !== undefined ? color1 : 0x444444);n color2 = new Color(color2 !== undefined ? color2 : 0x888888);n var center = divisions / 2;n var step = size / divisions;n var halfSize = size / 2;n var vertices = [],n colors = [];nn for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {n vertices.push(-halfSize, 0, k, halfSize, 0, k);n vertices.push(k, 0, -halfSize, k, 0, halfSize);n var color = i === center ? color1 : color2;n color.toArray(colors, j);n j += 3;n color.toArray(colors, j);n j += 3;n color.toArray(colors, j);n j += 3;n color.toArray(colors, j);n j += 3;n }nn var geometry = new BufferGeometry();n geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));n geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));n var material = new LineBasicMaterial({n vertexColors: VertexColorsn });n LineSegments.call(this, geometry, material);n}nnGridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {n constructor: GridHelper,n copy: function copy(source) {n LineSegments.prototype.copy.call(this, source);n this.geometry.copy(source.geometry);n this.material.copy(source.material);n return this;n },n clone: function clone() {n return new this.constructor().copy(this);n }n});n/**n * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n * @author Hectate / www.github.com/Hectaten */nnfunction PolarGridHelper(radius, radials, circles, divisions, color1, color2) {n radius = radius || 10;n radials = radials || 16;n circles = circles || 8;n divisions = divisions || 64;n color1 = new Color(color1 !== undefined ? color1 : 0x444444);n color2 = new Color(color2 !== undefined ? color2 : 0x888888);n var vertices = [];n var colors = [];n var x, z;n var v, i, j, r, color; // create the radialsnn for (i = 0; i <= radials; i++) {n v = i / radials * (Math.PI * 2);n x = Math.sin(v) * radius;n z = Math.cos(v) * radius;n vertices.push(0, 0, 0);n vertices.push(x, 0, z);n color = i & 1 ? color1 : color2;n colors.push(color.r, color.g, color.b);n colors.push(color.r, color.g, color.b);n } // create the circlesnnn for (i = 0; i <= circles; i++) {n color = i & 1 ? color1 : color2;n r = radius - radius / circles * i;nn for (j = 0; j < divisions; j++) {n // first vertexn v = j / divisions * (Math.PI * 2);n x = Math.sin(v) * r;n z = Math.cos(v) * r;n vertices.push(x, 0, z);n colors.push(color.r, color.g, color.b); // second vertexnn v = (j + 1) / divisions * (Math.PI * 2);n x = Math.sin(v) * r;n z = Math.cos(v) * r;n vertices.push(x, 0, z);n colors.push(color.r, color.g, color.b);n }n }nn var geometry = new BufferGeometry();n geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));n geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));n var material = new LineBasicMaterial({n vertexColors: VertexColorsn });n LineSegments.call(this, geometry, material);n}nnPolarGridHelper.prototype = Object.create(LineSegments.prototype);nPolarGridHelper.prototype.constructor = PolarGridHelper;n/**n * @author Mugen87 / github.com/Mugen87n */nnfunction PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {n this.audio = audio;n this.range = range || 1;n this.divisionsInnerAngle = divisionsInnerAngle || 16;n this.divisionsOuterAngle = divisionsOuterAngle || 2;n var geometry = new BufferGeometry();n var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;n var positions = new Float32Array((divisions * 3 + 3) * 3);n geometry.addAttribute('position', new BufferAttribute(positions, 3));n var materialInnerAngle = new LineBasicMaterial({n color: 0x00ff00n });n var materialOuterAngle = new LineBasicMaterial({n color: 0xffff00n });n Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);n this.update();n}nnPositionalAudioHelper.prototype = Object.create(Line.prototype);nPositionalAudioHelper.prototype.constructor = PositionalAudioHelper;nnPositionalAudioHelper.prototype.update = function () {n var audio = this.audio;n var range = this.range;n var divisionsInnerAngle = this.divisionsInnerAngle;n var divisionsOuterAngle = this.divisionsOuterAngle;nn var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);nn var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);nn var halfConeInnerAngle = coneInnerAngle / 2;n var halfConeOuterAngle = coneOuterAngle / 2;n var start = 0;n var count = 0;n var i, stride;n var geometry = this.geometry;n var positionAttribute = geometry.attributes.position;n geometry.clearGroups(); //nn function generateSegment(from, to, divisions, materialIndex) {n var step = (to - from) / divisions;n positionAttribute.setXYZ(start, 0, 0, 0);n count++;nn for (i = from; i < to; i += step) {n stride = start + count;n positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);n positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);n positionAttribute.setXYZ(stride + 2, 0, 0, 0);n count += 3;n }nn geometry.addGroup(start, count, materialIndex);n start += count;n count = 0;n } //nnn generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);n generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);n generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //nn positionAttribute.needsUpdate = true;n if (coneInnerAngle === coneOuterAngle) this.material.visible = false;n};nnPositionalAudioHelper.prototype.dispose = function () {n this.geometry.dispose();n this.material.dispose();n this.material.dispose();n};n/**n * @author mrdoob / mrdoob.com/n * @author WestLangley / github.com/WestLangleyn */nnnvar _v1$6 = new Vector3();nnvar _v2$4 = new Vector3();nnvar _normalMatrix$2 = new Matrix3();nnfunction FaceNormalsHelper(object, size, hex, linewidth) {n // FaceNormalsHelper only supports THREE.Geometryn this.object = object;n this.size = size !== undefined ? size : 1;n var color = hex !== undefined ? hex : 0xffff00;n var width = linewidth !== undefined ? linewidth : 1; //nn var nNormals = 0;n var objGeometry = this.object.geometry;nn if (objGeometry && objGeometry.isGeometry) {n nNormals = objGeometry.faces.length;n } else {n console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');n } //nnn var geometry = new BufferGeometry();n var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);n geometry.addAttribute('position', positions);n LineSegments.call(this, geometry, new LineBasicMaterial({n color: color,n linewidth: widthn })); //nn this.matrixAutoUpdate = false;n this.update();n}nnFaceNormalsHelper.prototype = Object.create(LineSegments.prototype);nFaceNormalsHelper.prototype.constructor = FaceNormalsHelper;nnFaceNormalsHelper.prototype.update = function () {n this.object.updateMatrixWorld(true);nn _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);nn var matrixWorld = this.object.matrixWorld;n var position = this.geometry.attributes.position; //nn var objGeometry = this.object.geometry;n var vertices = objGeometry.vertices;n var faces = objGeometry.faces;n var idx = 0;nn for (var i = 0, l = faces.length; i < l; i++) {n var face = faces;n var normal = face.normal;nn _v1$6.copy(vertices).add(vertices).add(vertices).divideScalar(3).applyMatrix4(matrixWorld);nn _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);nn position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);n idx = idx + 1;n position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);n idx = idx + 1;n }nn position.needsUpdate = true;n};n/**n * @author alteredq / alteredqualia.com/n * @author mrdoob / mrdoob.com/n * @author WestLangley / github.com/WestLangleyn */nnnvar _v1$7 = new Vector3();nnvar _v2$5 = new Vector3();nnvar _v3$1 = new Vector3();nnfunction DirectionalLightHelper(light, size, color) {n Object3D.call(this);n this.light = light;n this.light.updateMatrixWorld();n this.matrix = light.matrixWorld;n this.matrixAutoUpdate = false;n this.color = color;n if (size === undefined) size = 1;n var geometry = new BufferGeometry();n geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));n var material = new LineBasicMaterial({n fog: falsen });n this.lightPlane = new Line(geometry, material);n this.add(this.lightPlane);n geometry = new BufferGeometry();n geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));n this.targetLine = new Line(geometry, material);n this.add(this.targetLine);n this.update();n}nnDirectionalLightHelper.prototype = Object.create(Object3D.prototype);nDirectionalLightHelper.prototype.constructor = DirectionalLightHelper;nnDirectionalLightHelper.prototype.dispose = function () {n this.lightPlane.geometry.dispose();n this.lightPlane.material.dispose();n this.targetLine.geometry.dispose();n this.targetLine.material.dispose();n};nnDirectionalLightHelper.prototype.update = function () {n _v1$7.setFromMatrixPosition(this.light.matrixWorld);nn _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);nn _v3$1.subVectors(_v2$5, _v1$7);nn this.lightPlane.lookAt(_v2$5);nn if (this.color !== undefined) {n this.lightPlane.material.color.set(this.color);n this.targetLine.material.color.set(this.color);n } else {n this.lightPlane.material.color.copy(this.light.color);n this.targetLine.material.color.copy(this.light.color);n }nn this.targetLine.lookAt(_v2$5);n this.targetLine.scale.z = _v3$1.length();n};n/**n * @author alteredq / alteredqualia.com/n * @author Mugen87 / github.com/Mugen87n *n *t- shows frustum, line of sight and up of the cameran *t- suitable for fast updatesn * t- based on frustum visualization in lightgl.js shadowmap examplen *ttevanw.github.com/lightgl.js/tests/shadowmap.htmln */nnnvar _vector$a = new Vector3();nnvar _camera = new Camera();nnfunction CameraHelper(camera) {n var geometry = new BufferGeometry();n var material = new LineBasicMaterial({n color: 0xffffff,n vertexColors: FaceColorsn });n var vertices = [];n var colors = [];n var pointMap = {}; // colorsnn var colorFrustum = new Color(0xffaa00);n var colorCone = new Color(0xff0000);n var colorUp = new Color(0x00aaff);n var colorTarget = new Color(0xffffff);n var colorCross = new Color(0x333333); // nearnn addLine('n1', 'n2', colorFrustum);n addLine('n2', 'n4', colorFrustum);n addLine('n4', 'n3', colorFrustum);n addLine('n3', 'n1', colorFrustum); // farnn addLine('f1', 'f2', colorFrustum);n addLine('f2', 'f4', colorFrustum);n addLine('f4', 'f3', colorFrustum);n addLine('f3', 'f1', colorFrustum); // sidesnn addLine('n1', 'f1', colorFrustum);n addLine('n2', 'f2', colorFrustum);n addLine('n3', 'f3', colorFrustum);n addLine('n4', 'f4', colorFrustum); // conenn addLine('p', 'n1', colorCone);n addLine('p', 'n2', colorCone);n addLine('p', 'n3', colorCone);n addLine('p', 'n4', colorCone); // upnn addLine('u1', 'u2', colorUp);n addLine('u2', 'u3', colorUp);n addLine('u3', 'u1', colorUp); // targetnn addLine('c', 't', colorTarget);n addLine('p', 'c', colorCross); // crossnn addLine('cn1', 'cn2', colorCross);n addLine('cn3', 'cn4', colorCross);n addLine('cf1', 'cf2', colorCross);n addLine('cf3', 'cf4', colorCross);nn function addLine(a, b, color) {n addPoint(a, color);n addPoint(b, color);n }nn function addPoint(id, color) {n vertices.push(0, 0, 0);n colors.push(color.r, color.g, color.b);nn if (pointMap === undefined) {n pointMap = [];n }nn pointMap.push(vertices.length / 3 - 1);n }nn geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));n geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));n LineSegments.call(this, geometry, material);n this.camera = camera;n if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();n this.matrix = camera.matrixWorld;n this.matrixAutoUpdate = false;n this.pointMap = pointMap;n this.update();n}nnCameraHelper.prototype = Object.create(LineSegments.prototype);nCameraHelper.prototype.constructor = CameraHelper;nnCameraHelper.prototype.update = function () {n var geometry = this.geometry;n var pointMap = this.pointMap;n var w = 1,n h = 1; // we need just camera projection matrix inversen // world matrix must be identitynn _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / targetnnn setPoint('c', pointMap, geometry, _camera, 0, 0, -1);n setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // nearnn setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);n setPoint('n2', pointMap, geometry, _camera, w, -h, -1);n setPoint('n3', pointMap, geometry, _camera, -w, h, -1);n setPoint('n4', pointMap, geometry, _camera, w, h, -1); // farnn setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);n setPoint('f2', pointMap, geometry, _camera, w, -h, 1);n setPoint('f3', pointMap, geometry, _camera, -w, h, 1);n setPoint('f4', pointMap, geometry, _camera, w, h, 1); // upnn setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);n setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);n setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // crossnn setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);n setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);n setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);n setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);n setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);n setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);n setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);n setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);n geometry.getAttribute('position').needsUpdate = true;n};nnfunction setPoint(point, pointMap, geometry, camera, x, y, z) {n _vector$a.set(x, y, z).unproject(camera);nn var points = pointMap;nn if (points !== undefined) {n var position = geometry.getAttribute('position');nn for (var i = 0, l = points.length; i < l; i++) {n position.setXYZ(points, _vector$a.x, _vector$a.y, _vector$a.z);n }n }n}n/**n * @author mrdoob / mrdoob.com/n * @author Mugen87 / github.com/Mugen87n */nnnvar _box$2 = new Box3();nnfunction BoxHelper(object, color) {n this.object = object;n if (color === undefined) color = 0xffff00;n var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);n var positions = new Float32Array(8 * 3);n var geometry = new BufferGeometry();n geometry.setIndex(new BufferAttribute(indices, 1));n geometry.addAttribute('position', new BufferAttribute(positions, 3));n LineSegments.call(this, geometry, new LineBasicMaterial({n color: colorn }));n this.matrixAutoUpdate = false;n this.update();n}nnBoxHelper.prototype = Object.create(LineSegments.prototype);nBoxHelper.prototype.constructor = BoxHelper;nnBoxHelper.prototype.update = function (object) {n if (object !== undefined) {n console.warn('THREE.BoxHelper: .update() has no longer arguments.');n }nn if (this.object !== undefined) {n _box$2.setFromObject(this.object);n }nn if (_box$2.isEmpty()) return;n var min = _box$2.min;n var max = _box$2.max;n /*n 5____4n 1/___0/|n | 6__|_7n 2/___3/n t0: max.x, max.y, max.zn 1: min.x, max.y, max.zn 2: min.x, min.y, max.zn 3: max.x, min.y, max.zn 4: max.x, max.y, min.zn 5: min.x, max.y, min.zn 6: min.x, min.y, min.zn 7: max.x, min.y, min.zn */nn var position = this.geometry.attributes.position;n var array = position.array;n array = max.x;n array = max.y;n array = max.z;n array = min.x;n array = max.y;n array = max.z;n array = min.x;n array = min.y;n array = max.z;n array = max.x;n array = min.y;n array = max.z;n array = max.x;n array = max.y;n array = min.z;n array = min.x;n array = max.y;n array = min.z;n array = min.x;n array = min.y;n array = min.z;n array = max.x;n array = min.y;n array = min.z;n position.needsUpdate = true;n this.geometry.computeBoundingSphere();n};nnBoxHelper.prototype.setFromObject = function (object) {n this.object = object;n this.update();n return this;n};nnBoxHelper.prototype.copy = function (source) {n LineSegments.prototype.copy.call(this, source);n this.object = source.object;n return this;n};nnBoxHelper.prototype.clone = function () {n return new this.constructor().copy(this);n};n/**n * @author WestLangley / github.com/WestLangleyn */nnnfunction Box3Helper(box, color) {n this.type = 'Box3Helper';n this.box = box;n color = color || 0xffff00;n var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);n var 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];n var geometry = new BufferGeometry();n geometry.setIndex(new BufferAttribute(indices, 1));n geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));n LineSegments.call(this, geometry, new LineBasicMaterial({n color: colorn }));n this.geometry.computeBoundingSphere();n}nnBox3Helper.prototype = Object.create(LineSegments.prototype);nBox3Helper.prototype.constructor = Box3Helper;nnBox3Helper.prototype.updateMatrixWorld = function (force) {n var box = this.box;n if (box.isEmpty()) return;n box.getCenter(this.position);n box.getSize(this.scale);n this.scale.multiplyScalar(0.5);n Object3D.prototype.updateMatrixWorld.call(this, force);n};n/**n * @author WestLangley / github.com/WestLangleyn */nnnfunction PlaneHelper(plane, size, hex) {n this.type = 'PlaneHelper';n this.plane = plane;n this.size = size === undefined ? 1 : size;n var color = hex !== undefined ? hex : 0xffff00;n var 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];n var geometry = new BufferGeometry();n geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));n geometry.computeBoundingSphere();n Line.call(this, geometry, new LineBasicMaterial({n color: colorn })); //nn var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];n var geometry2 = new BufferGeometry();n geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));n geometry2.computeBoundingSphere();n this.add(new Mesh(geometry2, new MeshBasicMaterial({n color: color,n opacity: 0.2,n transparent: true,n depthWrite: falsen })));n}nnPlaneHelper.prototype = Object.create(Line.prototype);nPlaneHelper.prototype.constructor = PlaneHelper;nnPlaneHelper.prototype.updateMatrixWorld = function (force) {n var scale = -this.plane.constant;n if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matternn this.scale.set(0.5 * this.size, 0.5 * this.size, scale);n this.children.material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted herenn this.lookAt(this.plane.normal);n Object3D.prototype.updateMatrixWorld.call(this, force);n};n/**n * @author WestLangley / github.com/WestLangleyn * @author zz85 / github.com/zz85n * @author bhouston / clara.ion *n * Creates an arrow for visualizing directionsn *n * Parameters:n * dir - Vector3n * origin - Vector3n * length - Numbern * color - color in hex valuen * headLength - Numbern * headWidth - Numbern */nnnvar _axis = new Vector3();nnvar _lineGeometry, _coneGeometry;nnfunction ArrowHelper(dir, origin, length, color, headLength, headWidth) {n // dir is assumed to be normalizedn Object3D.call(this);n if (dir === undefined) dir = new Vector3(0, 0, 1);n if (origin === undefined) origin = new Vector3(0, 0, 0);n if (length === undefined) length = 1;n if (color === undefined) color = 0xffff00;n if (headLength === undefined) headLength = 0.2 * length;n if (headWidth === undefined) headWidth = 0.2 * headLength;nn if (_lineGeometry === undefined) {n _lineGeometry = new BufferGeometry();nn _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));nn _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);nn _coneGeometry.translate(0, -0.5, 0);n }nn this.position.copy(origin);n this.line = new Line(_lineGeometry, new LineBasicMaterial({n color: colorn }));n this.line.matrixAutoUpdate = false;n this.add(this.line);n this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({n color: colorn }));n this.cone.matrixAutoUpdate = false;n this.add(this.cone);n this.setDirection(dir);n this.setLength(length, headLength, headWidth);n}nnArrowHelper.prototype = Object.create(Object3D.prototype);nArrowHelper.prototype.constructor = ArrowHelper;nnArrowHelper.prototype.setDirection = function (dir) {n // dir is assumed to be normalizedn if (dir.y > 0.99999) {n this.quaternion.set(0, 0, 0, 1);n } else if (dir.y < -0.99999) {n this.quaternion.set(1, 0, 0, 0);n } else {n _axis.set(dir.z, 0, -dir.x).normalize();nn var radians = Math.acos(dir.y);n this.quaternion.setFromAxisAngle(_axis, radians);n }n};nnArrowHelper.prototype.setLength = function (length, headLength, headWidth) {n if (headLength === undefined) headLength = 0.2 * length;n if (headWidth === undefined) headWidth = 0.2 * headLength;n this.line.scale.set(1, Math.max(0, length - headLength), 1);n this.line.updateMatrix();n this.cone.scale.set(headWidth, headLength, headWidth);n this.cone.position.y = length;n this.cone.updateMatrix();n};nnArrowHelper.prototype.setColor = function (color) {n this.line.material.color.set(color);n this.cone.material.color.set(color);n};nnArrowHelper.prototype.copy = function (source) {n Object3D.prototype.copy.call(this, source, false);n this.line.copy(source.line);n this.cone.copy(source.cone);n return this;n};nnArrowHelper.prototype.clone = function () {n return new this.constructor().copy(this);n};n/**n * @author sroucheray / sroucheray.org/n * @author mrdoob / mrdoob.com/n */nnnfunction AxesHelper(size) {n size = size || 1;n var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];n var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];n var geometry = new BufferGeometry();n geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));n geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));n var material = new LineBasicMaterial({n vertexColors: VertexColorsn });n LineSegments.call(this, geometry, material);n}nnAxesHelper.prototype = Object.create(LineSegments.prototype);nAxesHelper.prototype.constructor = AxesHelper;n/**n * @author mrdoob / mrdoob.com/n */nnfunction Face4(a, b, c, d, normal, color, materialIndex) {n console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');n return new Face3(a, b, c, normal, color, materialIndex);n}nnvar LineStrip = 0;nvar LinePieces = 1;nnfunction MeshFaceMaterial(materials) {n console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');n return materials;n}nnfunction MultiMaterial(materials) {n if (materials === undefined) materials = [];n console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');n materials.isMultiMaterial = true;n materials.materials = materials;nn materials.clone = function () {n return materials.slice();n };nn return materials;n}nnfunction PointCloud(geometry, material) {n console.warn('THREE.PointCloud has been renamed to THREE.Points.');n return new Points(geometry, material);n}nnfunction Particle(material) {n console.warn('THREE.Particle has been renamed to THREE.Sprite.');n return new Sprite(material);n}nnfunction ParticleSystem(geometry, material) {n console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');n return new Points(geometry, material);n}nnfunction PointCloudMaterial(parameters) {n console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');n return new PointsMaterial(parameters);n}nnfunction ParticleBasicMaterial(parameters) {n console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');n return new PointsMaterial(parameters);n}nnfunction ParticleSystemMaterial(parameters) {n console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');n return new PointsMaterial(parameters);n}nnfunction Vertex(x, y, z) {n console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');n return new Vector3(x, y, z);n} //nnnfunction DynamicBufferAttribute(array, itemSize) {n console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');n return new BufferAttribute(array, itemSize).setDynamic(true);n}nnfunction Int8Attribute(array, itemSize) {n console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');n return new Int8BufferAttribute(array, itemSize);n}nnfunction Uint8Attribute(array, itemSize) {n console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');n return new Uint8BufferAttribute(array, itemSize);n}nnfunction Uint8ClampedAttribute(array, itemSize) {n console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');n return new Uint8ClampedBufferAttribute(array, itemSize);n}nnfunction Int16Attribute(array, itemSize) {n console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');n return new Int16BufferAttribute(array, itemSize);n}nnfunction Uint16Attribute(array, itemSize) {n console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');n return new Uint16BufferAttribute(array, itemSize);n}nnfunction Int32Attribute(array, itemSize) {n console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');n return new Int32BufferAttribute(array, itemSize);n}nnfunction Uint32Attribute(array, itemSize) {n console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');n return new Uint32BufferAttribute(array, itemSize);n}nnfunction Float32Attribute(array, itemSize) {n console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');n return new Float32BufferAttribute(array, itemSize);n}nnfunction Float64Attribute(array, itemSize) {n console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');n return new Float64BufferAttribute(array, itemSize);n} //nnnCurve.create = function (construct, getPoint) {n console.log('THREE.Curve.create() has been deprecated');n construct.prototype = Object.create(Curve.prototype);n construct.prototype.constructor = construct;n construct.prototype.getPoint = getPoint;n return construct;n}; //nnnObject.assign(CurvePath.prototype, {n createPointsGeometry: function createPointsGeometry(divisions) {n console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from path points (for Line or Points objects)nn var pts = this.getPoints(divisions);n return this.createGeometry(pts);n },n createSpacedPointsGeometry: function createSpacedPointsGeometry(divisions) {n console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the pathnn var pts = this.getSpacedPoints(divisions);n return this.createGeometry(pts);n },n createGeometry: function createGeometry(points) {n console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');n var geometry = new Geometry();nn for (var i = 0, l = points.length; i < l; i++) {n var point = points;n geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));n }nn return geometry;n }n}); //nnObject.assign(Path.prototype, {n fromPoints: function fromPoints(points) {n console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');n this.setFromPoints(points);n }n}); //nnfunction ClosedSplineCurve3(points) {n console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');n CatmullRomCurve3.call(this, points);n this.type = 'catmullrom';n this.closed = true;n}nnClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //nnfunction SplineCurve3(points) {n console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');n CatmullRomCurve3.call(this, points);n this.type = 'catmullrom';n}nnSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //nnfunction Spline(points) {n console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');n CatmullRomCurve3.call(this, points);n this.type = 'catmullrom';n}nnSpline.prototype = Object.create(CatmullRomCurve3.prototype);nObject.assign(Spline.prototype, {n initFromArray: function initFromArray()n /* a */n {n console.error('THREE.Spline: .initFromArray() has been removed.');n },n getControlPointsArray: function getControlPointsArray()n /* optionalTarget */n {n console.error('THREE.Spline: .getControlPointsArray() has been removed.');n },n reparametrizeByArcLength: function reparametrizeByArcLength()n /* samplingCoef */n {n console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');n }n}); //nnfunction AxisHelper(size) {n console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');n return new AxesHelper(size);n}nnfunction BoundingBoxHelper(object, color) {n console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');n return new BoxHelper(object, color);n}nnfunction EdgesHelper(object, hex) {n console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');n return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({n color: hex !== undefined ? hex : 0xffffffn }));n}nnGridHelper.prototype.setColors = function () {n console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');n};nnSkeletonHelper.prototype.update = function () {n console.error('THREE.SkeletonHelper: update() no longer needs to be called.');n};nnfunction WireframeHelper(object, hex) {n console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');n return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({n color: hex !== undefined ? hex : 0xffffffn }));n} //nnnObject.assign(Loader.prototype, {n extractUrlBase: function extractUrlBase(url) {n console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');n return LoaderUtils.extractUrlBase(url);n }n});nnfunction XHRLoader(manager) {n console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');n return new FileLoader(manager);n}nnfunction BinaryTextureLoader(manager) {n console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');n return new DataTextureLoader(manager);n}nnObject.assign(ObjectLoader.prototype, {n setTexturePath: function setTexturePath(value) {n console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');n return this.setResourcePath(value);n }n}); //nnObject.assign(Box2.prototype, {n center: function center(optionalTarget) {n console.warn('THREE.Box2: .center() has been renamed to .getCenter().');n return this.getCenter(optionalTarget);n },n empty: function empty() {n console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');n return this.isEmpty();n },n isIntersectionBox: function isIntersectionBox(box) {n console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');n return this.intersectsBox(box);n },n size: function size(optionalTarget) {n console.warn('THREE.Box2: .size() has been renamed to .getSize().');n return this.getSize(optionalTarget);n }n});nObject.assign(Box3.prototype, {n center: function center(optionalTarget) {n console.warn('THREE.Box3: .center() has been renamed to .getCenter().');n return this.getCenter(optionalTarget);n },n empty: function empty() {n console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');n return this.isEmpty();n },n isIntersectionBox: function isIntersectionBox(box) {n console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');n return this.intersectsBox(box);n },n isIntersectionSphere: function isIntersectionSphere(sphere) {n console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');n return this.intersectsSphere(sphere);n },n size: function size(optionalTarget) {n console.warn('THREE.Box3: .size() has been renamed to .getSize().');n return this.getSize(optionalTarget);n }n});nnLine3.prototype.center = function (optionalTarget) {n console.warn('THREE.Line3: .center() has been renamed to .getCenter().');n return this.getCenter(optionalTarget);n};nnObject.assign(_Math, {n random16: function random16() {n console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');n return Math.random();n },n nearestPowerOfTwo: function nearestPowerOfTwo(value) {n console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');n return _Math.floorPowerOfTwo(value);n },n nextPowerOfTwo: function nextPowerOfTwo(value) {n console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');n return _Math.ceilPowerOfTwo(value);n }n});nObject.assign(Matrix3.prototype, {n flattenToArrayOffset: function flattenToArrayOffset(array, offset) {n console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");n return this.toArray(array, offset);n },n multiplyVector3: function multiplyVector3(vector) {n console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');n return vector.applyMatrix3(this);n },n multiplyVector3Array: function multiplyVector3Array()n /* a */n {n console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');n },n applyToBuffer: function applyToBuffer(buffern /*, offset, length */n ) {n console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');n return this.applyToBufferAttribute(buffer);n },n applyToVector3Array: function applyToVector3Array()n /* array, offset, length */n {n console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');n }n});nObject.assign(Matrix4.prototype, {n extractPosition: function extractPosition(m) {n console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');n return this.copyPosition(m);n },n flattenToArrayOffset: function flattenToArrayOffset(array, offset) {n console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");n return this.toArray(array, offset);n },n getPosition: function getPosition() {n console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');n return new Vector3().setFromMatrixColumn(this, 3);n },n setRotationFromQuaternion: function setRotationFromQuaternion(q) {n console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');n return this.makeRotationFromQuaternion(q);n },n multiplyToArray: function multiplyToArray() {n console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');n },n multiplyVector3: function multiplyVector3(vector) {n console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');n return vector.applyMatrix4(this);n },n multiplyVector4: function multiplyVector4(vector) {n console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');n return vector.applyMatrix4(this);n },n multiplyVector3Array: function multiplyVector3Array()n /* a */n {n console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');n },n rotateAxis: function rotateAxis(v) {n console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');n v.transformDirection(this);n },n crossVector: function crossVector(vector) {n console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');n return vector.applyMatrix4(this);n },n translate: function translate() {n console.error('THREE.Matrix4: .translate() has been removed.');n },n rotateX: function rotateX() {n console.error('THREE.Matrix4: .rotateX() has been removed.');n },n rotateY: function rotateY() {n console.error('THREE.Matrix4: .rotateY() has been removed.');n },n rotateZ: function rotateZ() {n console.error('THREE.Matrix4: .rotateZ() has been removed.');n },n rotateByAxis: function rotateByAxis() {n console.error('THREE.Matrix4: .rotateByAxis() has been removed.');n },n applyToBuffer: function applyToBuffer(buffern /*, offset, length */n ) {n console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');n return this.applyToBufferAttribute(buffer);n },n applyToVector3Array: function applyToVector3Array()n /* array, offset, length */n {n console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');n },n makeFrustum: function makeFrustum(left, right, bottom, top, near, far) {n console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');n return this.makePerspective(left, right, top, bottom, near, far);n }n});nnPlane.prototype.isIntersectionLine = function (line) {n console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');n return this.intersectsLine(line);n};nnQuaternion.prototype.multiplyVector3 = function (vector) {n console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');n return vector.applyQuaternion(this);n};nnObject.assign(Ray.prototype, {n isIntersectionBox: function isIntersectionBox(box) {n console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');n return this.intersectsBox(box);n },n isIntersectionPlane: function isIntersectionPlane(plane) {n console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');n return this.intersectsPlane(plane);n },n isIntersectionSphere: function isIntersectionSphere(sphere) {n console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');n return this.intersectsSphere(sphere);n }n});nObject.assign(Triangle.prototype, {n area: function area() {n console.warn('THREE.Triangle: .area() has been renamed to .getArea().');n return this.getArea();n },n barycoordFromPoint: function barycoordFromPoint(point, target) {n console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');n return this.getBarycoord(point, target);n },n midpoint: function midpoint(target) {n console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');n return this.getMidpoint(target);n },n normal: function normal(target) {n console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');n return this.getNormal(target);n },n plane: function plane(target) {n console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');n return this.getPlane(target);n }n});nObject.assign(Triangle, {n barycoordFromPoint: function barycoordFromPoint(point, a, b, c, target) {n console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');n return Triangle.getBarycoord(point, a, b, c, target);n },n normal: function normal(a, b, c, target) {n console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');n return Triangle.getNormal(a, b, c, target);n }n});nObject.assign(Shape.prototype, {n extractAllPoints: function extractAllPoints(divisions) {n console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');n return this.extractPoints(divisions);n },n extrude: function extrude(options) {n console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');n return new ExtrudeGeometry(this, options);n },n makeGeometry: function makeGeometry(options) {n console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');n return new ShapeGeometry(this, options);n }n});nObject.assign(Vector2.prototype, {n fromAttribute: function fromAttribute(attribute, index, offset) {n console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');n return this.fromBufferAttribute(attribute, index, offset);n },n distanceToManhattan: function distanceToManhattan(v) {n console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');n return this.manhattanDistanceTo(v);n },n lengthManhattan: function lengthManhattan() {n console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');n return this.manhattanLength();n }n});nObject.assign(Vector3.prototype, {n setEulerFromRotationMatrix: function setEulerFromRotationMatrix() {n console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');n },n setEulerFromQuaternion: function setEulerFromQuaternion() {n console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');n },n getPositionFromMatrix: function getPositionFromMatrix(m) {n console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');n return this.setFromMatrixPosition(m);n },n getScaleFromMatrix: function getScaleFromMatrix(m) {n console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');n return this.setFromMatrixScale(m);n },n getColumnFromMatrix: function getColumnFromMatrix(index, matrix) {n console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');n return this.setFromMatrixColumn(matrix, index);n },n applyProjection: function applyProjection(m) {n console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');n return this.applyMatrix4(m);n },n fromAttribute: function fromAttribute(attribute, index, offset) {n console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');n return this.fromBufferAttribute(attribute, index, offset);n },n distanceToManhattan: function distanceToManhattan(v) {n console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');n return this.manhattanDistanceTo(v);n },n lengthManhattan: function lengthManhattan() {n console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');n return this.manhattanLength();n }n});nObject.assign(Vector4.prototype, {n fromAttribute: function fromAttribute(attribute, index, offset) {n console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');n return this.fromBufferAttribute(attribute, index, offset);n },n lengthManhattan: function lengthManhattan() {n console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');n return this.manhattanLength();n }n}); //nnObject.assign(Geometry.prototype, {n computeTangents: function computeTangents() {n console.error('THREE.Geometry: .computeTangents() has been removed.');n },n computeLineDistances: function computeLineDistances() {n console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');n }n});nObject.assign(Object3D.prototype, {n getChildByName: function getChildByName(name) {n console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');n return this.getObjectByName(name);n },n renderDepth: function renderDepth() {n console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');n },n translate: function translate(distance, axis) {n console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');n return this.translateOnAxis(axis, distance);n },n getWorldRotation: function getWorldRotation() {n console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');n }n});nObject.defineProperties(Object3D.prototype, {n eulerOrder: {n get: function get() {n console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');n return this.rotation.order;n },n set: function set(value) {n console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');n this.rotation.order = value;n }n },n useQuaternion: {n get: function get() {n console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');n },n set: function set() {n console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');n }n }n});nObject.defineProperties(LOD.prototype, {n objects: {n get: function get() {n console.warn('THREE.LOD: .objects has been renamed to .levels.');n return this.levels;n }n }n});nObject.defineProperty(Skeleton.prototype, 'useVertexTexture', {n get: function get() {n console.warn('THREE.Skeleton: useVertexTexture has been removed.');n },n set: function set() {n console.warn('THREE.Skeleton: useVertexTexture has been removed.');n }n});nnSkinnedMesh.prototype.initBones = function () {n console.error('THREE.SkinnedMesh: initBones() has been removed.');n};nnObject.defineProperty(Curve.prototype, '__arcLengthDivisions', {n get: function get() {n console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');n return this.arcLengthDivisions;n },n set: function set(value) {n console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');n this.arcLengthDivisions = value;n }n}); //nnPerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {n console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");n if (filmGauge !== undefined) this.filmGauge = filmGauge;n this.setFocalLength(focalLength);n}; //nnnObject.defineProperties(Light.prototype, {n onlyShadow: {n set: function set() {n console.warn('THREE.Light: .onlyShadow has been removed.');n }n },n shadowCameraFov: {n set: function set(value) {n console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');n this.shadow.camera.fov = value;n }n },n shadowCameraLeft: {n set: function set(value) {n console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');n this.shadow.camera.left = value;n }n },n shadowCameraRight: {n set: function set(value) {n console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');n this.shadow.camera.right = value;n }n },n shadowCameraTop: {n set: function set(value) {n console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');n this.shadow.camera.top = value;n }n },n shadowCameraBottom: {n set: function set(value) {n console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');n this.shadow.camera.bottom = value;n }n },n shadowCameraNear: {n set: function set(value) {n console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');n this.shadow.camera.near = value;n }n },n shadowCameraFar: {n set: function set(value) {n console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');n this.shadow.camera.far = value;n }n },n shadowCameraVisible: {n set: function set() {n console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');n }n },n shadowBias: {n set: function set(value) {n console.warn('THREE.Light: .shadowBias is now .shadow.bias.');n this.shadow.bias = value;n }n },n shadowDarkness: {n set: function set() {n console.warn('THREE.Light: .shadowDarkness has been removed.');n }n },n shadowMapWidth: {n set: function set(value) {n console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');n this.shadow.mapSize.width = value;n }n },n shadowMapHeight: {n set: function set(value) {n console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');n this.shadow.mapSize.height = value;n }n }n}); //nnObject.defineProperties(BufferAttribute.prototype, {n length: {n get: function get() {n console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');n return this.array.length;n }n },n copyIndicesArray: function copyIndicesArray()n /* indices */n {n console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');n }n});nObject.assign(BufferGeometry.prototype, {n addIndex: function addIndex(index) {n console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');n this.setIndex(index);n },n addDrawCall: function addDrawCall(start, count, indexOffset) {n if (indexOffset !== undefined) {n console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');n }nn console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');n this.addGroup(start, count);n },n clearDrawCalls: function clearDrawCalls() {n console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');n this.clearGroups();n },n computeTangents: function computeTangents() {n console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');n },n computeOffsets: function computeOffsets() {n console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');n }n});nObject.defineProperties(BufferGeometry.prototype, {n drawcalls: {n get: function get() {n console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');n return this.groups;n }n },n offsets: {n get: function get() {n console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');n return this.groups;n }n }n}); //nnObject.assign(ExtrudeBufferGeometry.prototype, {n getArrays: function getArrays() {n console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');n },n addShapeList: function addShapeList() {n console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');n },n addShape: function addShape() {n console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');n }n}); //nnObject.defineProperties(Uniform.prototype, {n dynamic: {n set: function set() {n console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');n }n },n onUpdate: {n value: function value() {n console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');n return this;n }n }n}); //nnObject.defineProperties(Material.prototype, {n wrapAround: {n get: function get() {n console.warn('THREE.Material: .wrapAround has been removed.');n },n set: function set() {n console.warn('THREE.Material: .wrapAround has been removed.');n }n },n overdraw: {n get: function get() {n console.warn('THREE.Material: .overdraw has been removed.');n },n set: function set() {n console.warn('THREE.Material: .overdraw has been removed.');n }n },n wrapRGB: {n get: function get() {n console.warn('THREE.Material: .wrapRGB has been removed.');n return new Color();n }n },n shading: {n get: function get() {n console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');n },n set: function set(value) {n console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');n this.flatShading = value === FlatShading;n }n }n});nObject.defineProperties(MeshPhongMaterial.prototype, {n metal: {n get: function get() {n console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');n return false;n },n set: function set() {n console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');n }n }n});nObject.defineProperties(ShaderMaterial.prototype, {n derivatives: {n get: function get() {n console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');n return this.extensions.derivatives;n },n set: function set(value) {n console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');n this.extensions.derivatives = value;n }n }n}); //nnObject.assign(WebGLRenderer.prototype, {n clearTarget: function clearTarget(renderTarget, color, depth, stencil) {n console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');n this.setRenderTarget(renderTarget);n this.clear(color, depth, stencil);n },n animate: function animate(callback) {n console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');n this.setAnimationLoop(callback);n },n getCurrentRenderTarget: function getCurrentRenderTarget() {n console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');n return this.getRenderTarget();n },n getMaxAnisotropy: function getMaxAnisotropy() {n console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');n return this.capabilities.getMaxAnisotropy();n },n getPrecision: function getPrecision() {n console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');n return this.capabilities.precision;n },n resetGLState: function resetGLState() {n console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');n return this.state.reset();n },n supportsFloatTextures: function supportsFloatTextures() {n console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');n return this.extensions.get('OES_texture_float');n },n supportsHalfFloatTextures: function supportsHalfFloatTextures() {n console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');n return this.extensions.get('OES_texture_half_float');n },n supportsStandardDerivatives: function supportsStandardDerivatives() {n console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');n return this.extensions.get('OES_standard_derivatives');n },n supportsCompressedTextureS3TC: function supportsCompressedTextureS3TC() {n console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');n return this.extensions.get('WEBGL_compressed_texture_s3tc');n },n supportsCompressedTexturePVRTC: function supportsCompressedTexturePVRTC() {n console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');n return this.extensions.get('WEBGL_compressed_texture_pvrtc');n },n supportsBlendMinMax: function supportsBlendMinMax() {n console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');n return this.extensions.get('EXT_blend_minmax');n },n supportsVertexTextures: function supportsVertexTextures() {n console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');n return this.capabilities.vertexTextures;n },n supportsInstancedArrays: function supportsInstancedArrays() {n console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');n return this.extensions.get('ANGLE_instanced_arrays');n },n enableScissorTest: function enableScissorTest(_boolean2) {n console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');n this.setScissorTest(_boolean2);n },n initMaterial: function initMaterial() {n console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');n },n addPrePlugin: function addPrePlugin() {n console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');n },n addPostPlugin: function addPostPlugin() {n console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');n },n updateShadowMap: function updateShadowMap() {n console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');n },n setFaceCulling: function setFaceCulling() {n console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');n },n allocTextureUnit: function allocTextureUnit() {n console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');n },n setTexture: function setTexture() {n console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');n },n setTexture2D: function setTexture2D() {n console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');n },n setTextureCube: function setTextureCube() {n console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');n },n getActiveMipMapLevel: function getActiveMipMapLevel() {n console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');n return this.getActiveMipmapLevel();n }n});nObject.defineProperties(WebGLRenderer.prototype, {n shadowMapEnabled: {n get: function get() {n return this.shadowMap.enabled;n },n set: function set(value) {n console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');n this.shadowMap.enabled = value;n }n },n shadowMapType: {n get: function get() {n return this.shadowMap.type;n },n set: function set(value) {n console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');n this.shadowMap.type = value;n }n },n shadowMapCullFace: {n get: function get() {n console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');n return undefined;n },n set: function set()n /* value */n {n console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');n }n },n context: {n get: function get() {n console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');n return this.getContext();n }n }n});nObject.defineProperties(WebGLShadowMap.prototype, {n cullFace: {n get: function get() {n console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');n return undefined;n },n set: function set()n /* cullFace */n {n console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');n }n },n renderReverseSided: {n get: function get() {n console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');n return undefined;n },n set: function set() {n console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');n }n },n renderSingleSided: {n get: function get() {n console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');n return undefined;n },n set: function set() {n console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');n }n }n}); //nnObject.defineProperties(WebGLRenderTargetCube.prototype, {n activeCubeFace: {n set: function set()n /* value */n {n console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');n }n },n activeMipMapLevel: {n set: function set()n /* value */n {n console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');n }n }n}); //nnObject.defineProperties(WebGLRenderTarget.prototype, {n wrapS: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');n return this.texture.wrapS;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');n this.texture.wrapS = value;n }n },n wrapT: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');n return this.texture.wrapT;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');n this.texture.wrapT = value;n }n },n magFilter: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');n return this.texture.magFilter;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');n this.texture.magFilter = value;n }n },n minFilter: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');n return this.texture.minFilter;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');n this.texture.minFilter = value;n }n },n anisotropy: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');n return this.texture.anisotropy;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');n this.texture.anisotropy = value;n }n },n offset: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');n return this.texture.offset;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');n this.texture.offset = value;n }n },n repeat: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');n return this.texture.repeat;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');n this.texture.repeat = value;n }n },n format: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');n return this.texture.format;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');n this.texture.format = value;n }n },n type: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');n return this.texture.type;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');n this.texture.type = value;n }n },n generateMipmaps: {n get: function get() {n console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');n return this.texture.generateMipmaps;n },n set: function set(value) {n console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');n this.texture.generateMipmaps = value;n }n }n}); //nnObject.defineProperties(WebVRManager.prototype, {n standing: {n set: function set()n /* value */n {n console.warn('THREE.WebVRManager: .standing has been removed.');n }n },n userHeight: {n set: function set()n /* value */n {n console.warn('THREE.WebVRManager: .userHeight has been removed.');n }n }n}); //nnAudio.prototype.load = function (file) {n console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');n var scope = this;n var audioLoader = new AudioLoader();n audioLoader.load(file, function (buffer) {n scope.setBuffer(buffer);n });n return this;n};nnAudioAnalyser.prototype.getData = function () {n console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');n return this.getFrequencyData();n}; //nnnCubeCamera.prototype.updateCubeMap = function (renderer, scene) {n console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');n return this.update(renderer, scene);n}; //nnnvar GeometryUtils = {n merge: function merge(geometry1, geometry2, materialIndexOffset) {n console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');n var matrix;nn if (geometry2.isMesh) {n geometry2.matrixAutoUpdate && geometry2.updateMatrix();n matrix = geometry2.matrix;n geometry2 = geometry2.geometry;n }nn geometry1.merge(geometry2, matrix, materialIndexOffset);n },n center: function center(geometry) {n console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');n return geometry.center();n }n};nImageUtils.crossOrigin = undefined;nnImageUtils.loadTexture = function (url, mapping, onLoad, onError) {n console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');n var loader = new TextureLoader();n loader.setCrossOrigin(this.crossOrigin);n var texture = loader.load(url, onLoad, undefined, onError);n if (mapping) texture.mapping = mapping;n return texture;n};nnImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {n console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');n var loader = new CubeTextureLoader();n loader.setCrossOrigin(this.crossOrigin);n var texture = loader.load(urls, onLoad, undefined, onError);n if (mapping) texture.mapping = mapping;n return texture;n};nnImageUtils.loadCompressedTexture = function () {n console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');n};nnImageUtils.loadCompressedTextureCube = function () {n console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');n}; //nnnfunction CanvasRenderer() {n console.error('THREE.CanvasRenderer has been removed');n} //nnnfunction JSONLoader() {n console.error('THREE.JSONLoader has been removed.');n} //nnnvar SceneUtils = {n createMultiMaterialObject: function createMultiMaterialObject()n /* geometry, materials */n {n console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');n },n detach: function detach()n /* child, parent, scene */n {n console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');n },n attach: function attach()n /* child, scene, parent */n {n console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');n }n}; //nnfunction LensFlare() {n console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');n}nnexport { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, ClosedSplineCurve3, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, BoxGeometry as CubeGeometry, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DirectionalLightShadow, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, Face3, Face4, FaceColors, FaceNormalsHelper, FileLoader, FlatShading, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontFaceDirectionCCW, FrontFaceDirectionCW, FrontSide, Frustum, GammaEncoding, Geometry, GeometryUtils, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeHelper, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, _Math as Math, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PositionalAudioHelper, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RectAreaLightHelper, RedFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SphericalReflectionMapping, Spline, SplineCurve, SplineCurve3, SpotLight, SpotLightHelper, SpotLightShadow, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StereoCamera, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uncharted2ToneMapping, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VertexNormalsHelper, VideoTexture, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding };”,“map”:null,“metadata”:{},“sourceType”:“module”}